Android 里面的ViewHolder找不到

图片说明
import android.content.Context;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

/**

  • Created by xiao on 2016/7/29.
    */
    public class MsgAdapter extends ArrayAdapter {
    private int resourceID;

    public MsgAdapter(Context context, int textViewResourcedId, List objects) {
    super(context, textViewResourcedId, objects);
    resourceID = textViewResourcedId;

    }

    @Override
    public View getView(int postion, View convertView, ViewGroup parent) {
    Msg msg = getItem(postion);
    View view;

    ViewHolder viewHolder;
    if (convertView == null) {
        view = LayoutInflater.from(getContext()).inflate(resourceID, null);
        viewHolder = new ViewHolder();
        viewHolder.leftLayoyt = (LinearLayout) view.findViewById(R.id.left_layout);
        viewHolder.rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
        viewHolder.leftMsg = (TextView) view.findViewById(R.id.left_msg);
        viewHolder.rightMsg = (TextView) view.findViewById(R.id.righy_msg);
    } else {
        view = convertView;
        viewHolder = (ViewHolder) view.getTag();
    

3个回答

ViewHolder是自己定义的类啊

ViewHolder需要自己定义

class ViewHolder {
//这里面写你自己的控件
private TextView testTV;
private Button testBtn;

}

这玩意儿是需要自定义的

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Android recycleview的 viewholder中的 editview获取不到焦点,也设置焦点无效。
recycleview的item中的editview点击时光标闪一下就没了,不弹出键盘。 跪求路过的大神赐教。
在写一个AndroidBLE程序时,遇到了搜索不到设备的原因,怎么解决?
代码如下: 1.MainActivity部分 ``` public class MainActivity extends AppCompatActivity implements View.OnClickListener { private BluetoothAdapter mBluetoothAdapter; private RecyclerView mRecyclerView; private ScanResultAdapter mScanResultAdapter; private BluetoothLeScanner mBluetoothLeScanner; private Button mStartScaleButton,mStopScaleButton; private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1; //动态申请权限 private static final int SCAN_START = 1000; //开始搜索 private static final int SCAN_TIME = 10 * 1000; //扫描时间 private static final String TAG = "BLE"; private List<ScanResult> mList = new ArrayList<>(); private List<String> mListAddress = new ArrayList<>(); private Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { switch (msg.what){ case SCAN_START: scanBluetooth(false); } return false; } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); SetOnClickListener(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时 //判断是否具有权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //判断是否需要向用户解释为什么需要申请该权限 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) { Toast.makeText(MainActivity.this, "自Android 6.0开始需要打开位置权限才可以搜索到Ble设备", Toast.LENGTH_LONG).show(); } //请求权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_ACCESS_COARSE_LOCATION); } } } private void initView(){ /*找到控件*/ mStartScaleButton = findViewById(R.id.bt_1); mStopScaleButton = findViewById(R.id.bt_2); mRecyclerView = findViewById(R.id.rv_1); mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL)); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mScanResultAdapter = new ScanResultAdapter(this,mList); mRecyclerView.setAdapter(mScanResultAdapter); mScanResultAdapter.setOnItemClickListener(new ScanResultAdapter.OnItemClickListener() { @Override public void OnClick(int position) { scanBluetooth(false); ScanResult scanResult = mList.get(position); } }); /*获取本地蓝牙适配器*/ BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "设备不支持BLE", Toast.LENGTH_SHORT).show(); finish(); } /*打开蓝牙*/ if(mBluetoothAdapter == null ||!mBluetoothAdapter.isEnabled()){ Intent TrunOnBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(TrunOnBtIntent,0); } } /*控件点击事件*/ private void SetOnClickListener(){ mStartScaleButton.setOnClickListener(this); mStopScaleButton.setOnClickListener(this); } /*对应控件执行相关操作*/ @Override public void onClick(View v){ switch (v.getId()){ case R.id.bt_1: scanBluetooth(true); Toast.makeText(MainActivity.this,"扫描",Toast.LENGTH_LONG).show(); break; case R.id.bt_2: scanBluetooth(false); break; } } /*开始搜索设备及停止搜索设备函数*/ private void scanBluetooth(boolean isSan){ if(isSan==true){ mBluetoothLeScanner.startScan(mScanCallback); mHandler.sendEmptyMessageDelayed(SCAN_START,SCAN_TIME);//定时搜索蓝牙设备 }else { mBluetoothLeScanner.stopScan(mScanCallback); if(mHandler.hasMessages(SCAN_START)){ mHandler.removeMessages(SCAN_START); } } } /*搜索的回调函数*/ private ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { Log.i(TAG,"result:" + result + "callbackType:" + callbackType); /*通过扫描到的设备地址与新扫描的地址作比较,避免重复*/ if(!mListAddress.contains(result.getDevice().getAddress())){ mList.add(result); mListAddress.add(result.getDevice().getAddress()); } super.onScanResult(callbackType, result); } @Override /*扫描失败的处理*/ public void onScanFailed(int errorCode){ Log.e(TAG,"onScanFailed:" + errorCode); } }; } ``` 2. ScanResultAdapter部分 ``` public class ScanResultAdapter extends RecyclerView.Adapter<ScanResultAdapter.ViewHolder> { private Context mContext; private List<ScanResult> mList; private LayoutInflater inflater; private OnItemClickListener onItemClickListener; public ScanResultAdapter(Context mContext,List<ScanResult>mList){ this.mContext = mContext; this.mList = mList; inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setOnItemClickListener(OnItemClickListener onItemClickListener){ this.onItemClickListener = onItemClickListener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(inflater.from(mContext).inflate(R.layout.layout_scanadapter_item,parent,false)); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { ScanResult scanResult = mList.get(position); holder.tv_name.setText("设备名:"+scanResult.getDevice().getName()); holder.tv_address.setText("设备地址:"+scanResult.getDevice().getAddress()); holder.tv_rssi.setText("信号:"+scanResult.getRssi()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(null != onItemClickListener){ onItemClickListener.OnClick(position); } } }); } @Override public int getItemCount() { return mList.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private TextView tv_name; private TextView tv_address; private TextView tv_rssi; public ViewHolder(@NonNull View itemView) { super(itemView); tv_name = itemView.findViewById(R.id.tv_name); tv_address = itemView.findViewById(R.id.tv_address); tv_rssi = itemView.findViewById(R.id.tv_rssi); } } public interface OnItemClickListener{ void OnClick(int position); } } ```
写Android BLE程序测试发现无法发现设备,请问怎么解决?
代码如下: 1.MainActivity部分 ``` public class MainActivity extends AppCompatActivity implements View.OnClickListener { private BluetoothAdapter mBluetoothAdapter; private RecyclerView mRecyclerView; private ScanResultAdapter mScanResultAdapter; private BluetoothLeScanner mBluetoothLeScanner; private Button mStartScaleButton,mStopScaleButton; private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1; //动态申请权限 private static final int SCAN_START = 1000; //开始搜索 private static final int SCAN_TIME = 10 * 1000; //扫描时间 private static final String TAG = "BLE"; private List<ScanResult> mList = new ArrayList<>(); private List<String> mListAddress = new ArrayList<>(); private Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { switch (msg.what){ case SCAN_START: scanBluetooth(false); } return false; } }); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); SetOnClickListener(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时 //判断是否具有权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //判断是否需要向用户解释为什么需要申请该权限 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) { Toast.makeText(MainActivity.this, "自Android 6.0开始需要打开位置权限才可以搜索到Ble设备", Toast.LENGTH_LONG).show(); } //请求权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_ACCESS_COARSE_LOCATION); } } } private void initView(){ /*找到控件*/ mStartScaleButton = findViewById(R.id.bt_1); mStopScaleButton = findViewById(R.id.bt_2); mRecyclerView = findViewById(R.id.rv_1); mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL)); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mScanResultAdapter = new ScanResultAdapter(this,mList); mRecyclerView.setAdapter(mScanResultAdapter); mScanResultAdapter.setOnItemClickListener(new ScanResultAdapter.OnItemClickListener() { @Override public void OnClick(int position) { scanBluetooth(false); ScanResult scanResult = mList.get(position); } }); /*获取本地蓝牙适配器*/ BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "设备不支持BLE", Toast.LENGTH_SHORT).show(); finish(); } /*打开蓝牙*/ if(mBluetoothAdapter == null ||!mBluetoothAdapter.isEnabled()){ Intent TrunOnBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(TrunOnBtIntent,0); } } /*控件点击事件*/ private void SetOnClickListener(){ mStartScaleButton.setOnClickListener(this); mStopScaleButton.setOnClickListener(this); } /*对应控件执行相关操作*/ @Override public void onClick(View v){ switch (v.getId()){ case R.id.bt_1: scanBluetooth(true); Toast.makeText(MainActivity.this,"扫描",Toast.LENGTH_LONG).show(); break; case R.id.bt_2: scanBluetooth(false); break; } } /*开始搜索设备及停止搜索设备函数*/ private void scanBluetooth(boolean isSan){ if(isSan==true){ mBluetoothLeScanner.startScan(mScanCallback); mHandler.sendEmptyMessageDelayed(SCAN_START,SCAN_TIME);//定时搜索蓝牙设备 }else { mBluetoothLeScanner.stopScan(mScanCallback); if(mHandler.hasMessages(SCAN_START)){ mHandler.removeMessages(SCAN_START); } } } /*搜索的回调函数*/ private ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { Log.i(TAG,"result:" + result + "callbackType:" + callbackType); /*通过扫描到的设备地址与新扫描的地址作比较,避免重复*/ if(!mListAddress.contains(result.getDevice().getAddress())){ mList.add(result); mListAddress.add(result.getDevice().getAddress()); } super.onScanResult(callbackType, result); } @Override /*扫描失败的处理*/ public void onScanFailed(int errorCode){ Log.e(TAG,"onScanFailed:" + errorCode); } }; } ``` 2.ScanResultAdapter部分 ``` public class ScanResultAdapter extends RecyclerView.Adapter<ScanResultAdapter.ViewHolder> { private Context mContext; private List<ScanResult> mList; private LayoutInflater inflater; private OnItemClickListener onItemClickListener; public ScanResultAdapter(Context mContext,List<ScanResult>mList){ this.mContext = mContext; this.mList = mList; inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setOnItemClickListener(OnItemClickListener onItemClickListener){ this.onItemClickListener = onItemClickListener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(inflater.from(mContext).inflate(R.layout.layout_scanadapter_item,parent,false)); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { ScanResult scanResult = mList.get(position); holder.tv_name.setText("设备名:"+scanResult.getDevice().getName()); holder.tv_address.setText("设备地址:"+scanResult.getDevice().getAddress()); holder.tv_rssi.setText("信号:"+scanResult.getRssi()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(null != onItemClickListener){ onItemClickListener.OnClick(position); } } }); } @Override public int getItemCount() { return mList.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private TextView tv_name; private TextView tv_address; private TextView tv_rssi; public ViewHolder(@NonNull View itemView) { super(itemView); tv_name = itemView.findViewById(R.id.tv_name); tv_address = itemView.findViewById(R.id.tv_address); tv_rssi = itemView.findViewById(R.id.tv_rssi); } } public interface OnItemClickListener{ void OnClick(int position); } } ``` 另:测试手机为小米mix2s,SDK版本为29
android开发,在后台里面有数据,但Adapter没有接收到数据,找不到原因,帮忙看一下!!!
activity文件如下: //任务列表显示 listView = (ListView)findViewById(R.id.agv_rw); adapter = new AGV任务Adapter(this,dataList); listView.setAdapter(adapter); new 查询Task().execute();//查询任务 //任务列表选中一行数据 执行操作 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //点击执行 任务编号 = adapter.getItem(position).get任务编号(); if(!任务编号.equals("")){ //隐藏 ScrollView.setVisibility(View.GONE); //显示 rlrenwu.setVisibility(View.VISIBLE); } } }); class 查询Task extends AsyncTask<Void, Void, Result<List<物流任务表>>>{ @Override protected Result<List<物流任务表>> doInBackground(Void... voids) { Result<List<物流任务表>> res = new Result<>(); 物流任务表 wl = new 物流任务表(); String param = App.gson.toJson(wl); String result = HttpUtil.sendPost(PathUtil.查询任务, param); res = TaskUtil.handle(res, result, new TypeToken<Result<List<物流任务表>>>() { }.getType()); return res; } //事后执行 @Override protected void onPostExecute(Result<List<物流任务表>> res) { if(res.isFlag()){ adapter.setDatalist(res.getData()); adapter.notifyDataSetChanged(); } } } Adapter文件如下: public class AGV任务Adapter extends BaseAdapter { private Context context; private List<物流任务表> datalist; public AGV任务Adapter(Context context, List<物流任务表> datalist) { this.context = context; this.datalist = datalist; } public void setDatalist(List<物流任务表> datalist) { this.datalist = datalist; } @Override public int getCount() { return datalist.size(); } @Override public 物流任务表 getItem(int position) { return datalist.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View view, ViewGroup parent) { if(view == null){ view = LayoutInflater.from(context).inflate(R.layout.list_agvexception_item,null); } boolean ifdraw = true; ViewHolder viewHolder = null; if(view.getTag() != null && view.getTag() instanceof ViewHolder){ viewHolder = (ViewHolder)view.getTag(); } if(ifdraw){ viewHolder = new ViewHolder(); viewHolder.物流任务表 = datalist.get(position); viewHolder.tv任务编号 = (TextView)view.findViewById(R.id.rwbh); viewHolder.tvAGV编号 = (TextView)view.findViewById(R.id.agvbh); viewHolder.tv任务状态 = (TextView)view.findViewById(R.id.rwzt); viewHolder.tv任务类型 = (TextView)view.findViewById(R.id.rwlx); viewHolder.tv任务优先级 = (TextView)view.findViewById(R.id.rwyxj); viewHolder.tv起始站点 = (TextView)view.findViewById(R.id.qszd); viewHolder.tv目的站点 = (TextView)view.findViewById(R.id.mdzd); viewHolder.tv任务编号.setText(viewHolder.物流任务表.get任务编号()); viewHolder.tvAGV编号.setText(viewHolder.物流任务表.getAGV编号()); if(viewHolder.物流任务表.get任务状态().equals("0")){ viewHolder.tv任务状态.setText("未执行"); }else if(viewHolder.物流任务表.get任务状态().equals("1")){ viewHolder.tv任务状态.setText("执行中"); }else if(viewHolder.物流任务表.get任务状态().equals("2")){ viewHolder.tv任务状态.setText("已完成"); }else if(viewHolder.物流任务表.get任务状态().equals("3")){ viewHolder.tv任务状态.setText("强制取消"); }else if(viewHolder.物流任务表.get任务状态().equals("4")){ viewHolder.tv任务状态.setText("强制完成"); }else if(viewHolder.物流任务表.get任务状态().equals("5")){ viewHolder.tv任务状态.setText("任务已获取"); }else if(viewHolder.物流任务表.get任务状态().equals("6")){ viewHolder.tv任务状态.setText("任务中止"); }else if(viewHolder.物流任务表.get任务状态().equals("9")){ viewHolder.tv任务状态.setText("任务解析错误"); } if(viewHolder.物流任务表.get任务类型().equals("I")){ viewHolder.tv任务类型.setText("生产入库"); }else if(viewHolder.物流任务表.get任务类型().equals("O")){ viewHolder.tv任务类型.setText("物料出库"); }else if(viewHolder.物流任务表.get任务类型().equals("M")){ viewHolder.tv任务类型.setText("生产上料"); }else if(viewHolder.物流任务表.get任务类型().equals("T")){ viewHolder.tv任务类型.setText("物料入库"); }else if(viewHolder.物流任务表.get任务类型().equals("R")){ viewHolder.tv任务类型.setText("木制托盘回收"); }else if(viewHolder.物流任务表.get任务类型().equals("S")){ viewHolder.tv任务类型.setText("成品托盘运送"); }else if(viewHolder.物流任务表.get任务类型().equals("E")){ viewHolder.tv任务类型.setText("调拨"); }else if(viewHolder.物流任务表.get任务类型().equals("F")){ viewHolder.tv任务类型.setText("塑料托盘回收"); }else if(viewHolder.物流任务表.get任务类型().equals("G")){ viewHolder.tv任务类型.setText("塑料托盘循环"); } if(viewHolder.物流任务表.get任务优先级().equals("S")){ viewHolder.tv任务优先级.setText("1"); }else if(viewHolder.物流任务表.get任务优先级().equals("P")){ viewHolder.tv任务优先级.setText("2"); }else if(viewHolder.物流任务表.get任务优先级().equals("I")){ viewHolder.tv任务优先级.setText("3"); }else if(viewHolder.物流任务表.get任务优先级().equals("O")){ viewHolder.tv任务优先级.setText("4"); } viewHolder.tv起始站点.setText(viewHolder.物流任务表.get起始站点()); viewHolder.tv目的站点.setText(viewHolder.物流任务表.get目的站点()); } return view; } class ViewHolder{ 物流任务表 物流任务表; TextView tv任务编号,tvAGV编号,tv任务状态,tv任务类型,tv任务优先级,tv起始站点,tv目的站点; } } 其他数据都显示唯独AGV编号这个不显示,DEBUG一下发现没有接收到数据,是NULL,但是其他都有数据,后台WEBserver中也用测试类测试了,可以查到数据,没有报错日志很奇怪,麻烦大家帮忙看看是什么原因造成的。
eclipse里,在线性布局里再嵌入一个线性布局,为什么R文件里找不到布局里添加的id
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <LinearLayout android:id="@+id/left_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:background="@drawable/message_left"> <TextView android:id="@+id/left_msg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textColor="#fff"/> </LinearLayout> <LinearLayout android:id="@+id/right_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:background="@drawable/message_right"> <TextView android:id="@+id/right_msg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp"/> </LinearLayout> </LinearLayout> if(convertView == null) { view = LayoutInflater.from(getContext()).inflate(resourceId, null); viewHolder = new ViewHolder(); viewHolder.leftLayout = (LinearLayout) view.findViewById(R.id.left_layout); viewHolder.rightLayout = (LinearLayout) view.findViewById(R.id.right_layout); viewHolder.leftMsg = (TextView) view.findViewById(R.id.left_msg); viewHolder.rightMsg = (TextView) view.findViewById(R.id.right_msg); view.setTag(viewHolder); }
Recyclerview嵌套recyclerview的深坑,我坐在Recyclerview这个坑里很久了,仰望天空希望能把我拉上去。
Recyclerview嵌套recyclerview的深坑,对于一个新手来说怎么也上不去,特来邀请键盘中的高手高高手,拉拉我; ## 第一个Recyclerview布局: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/area_LinearLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:background="@drawable/drawable_black_one" android:orientation="horizontal" android:layout_margin="3dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_gravity="center" android:text="" android:textColor="@drawable/drawable_white_pure" android:lines="1" android:layout_weight="1"/> <TextView android:layout_width="1dp" android:layout_height="30dp" android:layout_gravity="center" android:layout_margin="5dp" android:background="@color/whiteness" /> <TextView android:id="@+id/peers_location_TextView" android:layout_width="70dp" android:layout_height="40dp" android:layout_marginLeft="5sp" android:layout_marginRight="10dp" android:ellipsize="end" android:gravity="center" android:text="" android:textColor="@color/whiteness" android:textSize="14sp" android:lines="1" android:textStyle="bold" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:layout_width="20dp" android:layout_height="20dp" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_marginTop="0dp" android:layout_marginEnd="10dp" android:scaleType="fitStart" android:src="@drawable/location" /> </RelativeLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="40dp" android:background="@drawable/drawable_black_one" android:layout_gravity="center" android:focusable="true" android:focusableInTouchMode="true" android:layout_margin="3dp"> <EditText android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_margin="1dp" android:background="@color/text_white" android:hint="行业人员" android:textSize="13dp" android:gravity="center" android:lines="1" android:layout_weight="1"/> <TextView android:layout_width="50dp" android:layout_height="wrap_content" android:text="搜索" android:textSize="14dp" android:layout_marginLeft="14dp" android:layout_gravity="center" android:textColor="@color/whiteness" android:layout_margin="5dp" android:gravity="center"/> </LinearLayout> <android.support.v7.widget.RecyclerView android:id="@+id/user_info_layout" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> ``` ## 在第一个Recycleview的item里面嵌套了第二个Recyclerview不知道这样对不对? ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/portrait" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/user_portrait" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="5dp" android:src="@drawable/em_default_avatar" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="20dp" android:layout_marginTop="5dp" android:gravity="clip_horizontal"> <TextView android:id="@+id/user_industry" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/dialog_circular_whiteness" android:ellipsize="end" android:gravity="center" android:text="建筑" android:textColor="@color/colorPrimary" android:textSize="14sp" android:textStyle="bold" /> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom" android:layout_marginLeft="5dp" android:background="@drawable/dialog_circular_whiteness" android:ellipsize="end" android:gravity="center" android:text="努力改变自己" android:textColor="#323232" android:textSize="10sp" android:textStyle="bold" /> <TextView android:id="@+id/name_voip" android:layout_width="20dp" android:layout_height="wrap_content" android:layout_gravity="center" android:ellipsize="end" android:gravity="center" android:text="voip" android:textColor="@color/text_pink" android:textSize="7sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="35dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="努力改变自己" android:textSize="12dp" /> </LinearLayout> </LinearLayout> <RelativeLayout android:layout_width="60dp" android:layout_height="match_parent" android:gravity="center"> <TextView android:id="@+id/user_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/dialog_circular_whiteness" android:text="" android:textSize="12dp" android:textStyle="bold" /> </RelativeLayout> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1"> **<!-- 导入RecyclerView-->** <android.support.v7.widget.RecyclerView android:id="@+id/user_peesr_info" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="10dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:text="访问:10000人" android:textSize="8dp" /> </LinearLayout> </LinearLayout> </LinearLayout> ``` ## 第一个Recyclerview的适配器: ``` public class Home_RecyclerView_Adapter extends RecyclerView.Adapter<Home_RecyclerView_Adapter.myViewHodler> { private Context context; private LinkedList<Home_list_get_set> LinkedList; public LinkedList<User_Recruitment_get_set> mLinkedList; public Home_list_get_set mHome_list_get_set; //创建构造函数 public Home_RecyclerView_Adapter(Context context, LinkedList<Home_list_get_set> industrytitlegetsetList) { //将传递过来的数据,赋值给本地变量 this.context = context;//上下文 this.LinkedList = industrytitlegetsetList;//实体类数据ArrayList } /** * 创建viewhodler,相当于listview中getview中的创建view和viewhodler * * @param parent * @param viewType * @return */ @Override public myViewHodler onCreateViewHolder(ViewGroup parent, int viewType) { RecyclerView user_peesr_info;//自定义recyclerveiw的适配器 //创建自定义布局 // View itemView = View.inflate(context, R.layout.peers_list_item, null);//用这个布局item宽高无效 // myViewHodler itemView = new myViewHodler(LayoutInflater.from(context).inflate(R.layout.peers_list_item, parent, false)); View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.peers_list_item, parent, false); user_peesr_info = view.findViewById (R.id.user_peesr_info); //给嵌套的RecyclerView设置适配器 User_Recruitment_Adapter user_recruitment_adapter = new User_Recruitment_Adapter (context,mLinkedList); user_peesr_info.setAdapter (user_recruitment_adapter); user_peesr_info.setLayoutManager (new LinearLayoutManager (context, LinearLayoutManager.HORIZONTAL, false)); //给嵌套的RecyclerView设置item的分割线 user_peesr_info.addItemDecoration (new DividerItemDecoration (context, DividerItemDecoration.HORIZONTAL)); return new myViewHodler(view); // return itemView; } /** * 绑定数据,数据与view绑定 * * @param holder * @param position */ @SuppressLint("ClickableViewAccessibility") @Override public void onBindViewHolder(myViewHodler holder, int position) { //根据点击位置绑定数据 mHome_list_get_set = LinkedList.get(position); // holder.mItemGoodsImg; holder.user_name.setText(mHome_list_get_set.getUser_name()); holder.user_industry.setText(mHome_list_get_set.getUser_work()); // holder.user_portrait.setImageDrawable (data.getHead_portait ());//改为下面Glide获取图上 Glide.with(context) .load(mHome_list_get_set.getHead_portait ())//图片信息 .apply(RequestOptions.bitmapTransform(new CircleCrop ()))//设置圆形 .into(holder.user_portrait);//设置到那个部位 holder.name_voip.setText(mHome_list_get_set.getUser_Vip()); holder.user_location.setText(mHome_list_get_set.getUser_location()); } /** * 得到总条数 * * @return */ @Override public int getItemCount() { // return LinkedList.size(); return LinkedList == null ? 0 : LinkedList.size(); } //自定义viewhodler class myViewHodler extends RecyclerView.ViewHolder { private ImageView user_portrait; private TextView user_name; private TextView user_industry; private TextView name_voip; private TextView user_location; public RecyclerView user_peesr_info;//自定义recyclerveiw的适配器 public myViewHodler(View itemView) { super(itemView); user_peesr_info = itemView.findViewById (R.id.user_peesr_info); user_portrait = itemView.findViewById(R.id.user_portrait); user_name = itemView.findViewById(R.id.user_name); user_industry = itemView.findViewById(R.id.user_industry); name_voip = itemView.findViewById(R.id.name_voip); user_location = itemView.findViewById(R.id.user_location); user_portrait.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //可以选择直接在本位置直接写业务处理 //Toast.makeText(context,"点击了xxx",Toast.LENGTH_SHORT).show(); //此处回传点击监听事件 if (onItemClickListener != null) { onItemClickListener.OnItemClick(v, LinkedList.get(getLayoutPosition())); } } }); } public View getItemView() { return itemView; } } /** * 设置item的监听事件的接口 */ public interface OnItemClickListener { /** * 接口中的点击每一项的实现方法 * * @param view 点击的item的视图 * @param data 点击的item的数据 */ public void OnItemClick(View view, Home_list_get_set data); } //需要外部访问,所以需要设置set方法,方便调用 private OnItemClickListener onItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } ``` ## 第二个Recyclerview的适配器: ``` public class User_Recruitment_Adapter extends RecyclerView.Adapter<User_Recruitment_Adapter.myViewHodler> { public LinkedList<User_Recruitment_get_set> m_LinkedList; private Context context; public User_Recruitment_get_set mUser_Recruitment_get_set; //创建构造函数 public User_Recruitment_Adapter(Context context, LinkedList<User_Recruitment_get_set> mLinkedList) { //将传递过来的数据,赋值给本地变量 this.context = context;//上下文 this.m_LinkedList = mLinkedList; } @NonNull @Override public myViewHodler onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_peers_recruitment_item, viewGroup, false); return new myViewHodler(view); } @Override public void onBindViewHolder(@NonNull myViewHodler myViewHodler, int i) { mUser_Recruitment_get_set = m_LinkedList.get(i); myViewHodler.recruitment.setText (mUser_Recruitment_get_set.getRecruitment ()); } @Override public int getItemCount() { return m_LinkedList == null ? 0 : m_LinkedList.size(); } public class myViewHodler extends RecyclerView.ViewHolder { private TextView recruitment; public myViewHodler(@NonNull View itemView) { super (itemView); recruitment = itemView.findViewById(R.id.recruitment); } } } ``` ## 现问题是嵌套里面的Recyclerview无显示内容?我该如何写?
android 关于listview convertview的一些问题,求解!
![图片说明](https://img-ask.csdn.net/upload/201603/14/1457947694_116075.png) 做的是一个聊天界面,这是adapter代码。 运行时只能输入一次,输第二次时,参数convertview是第二次view的对象,不知道为什么啊。 ``` package com.example.chattest; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; public class ChatActivity extends Activity implements OnClickListener { private Button btnSend; private ListView lvChat; private EditText etSendContent; //聊天内容的适配器 private ChatMsgViewAdapter chatMsgAdapter; //聊天内容 private List<ChatMsgInfo> chatMsgDataArrays = new ArrayList<ChatMsgInfo>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //不显示标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.chat); initView(); initData(); } //初始化视图 private void initView() { lvChat = (ListView) findViewById(R.id.chat_listview); btnSend = (Button) findViewById(R.id.btn_send); btnSend.setOnClickListener(this); etSendContent = (EditText) findViewById(R.id.et_sendmessage); } //聊天数据 //private final static int COUNT = 10 private String text = new String("第1种写法果然最慢,第二种写法由于用了StringBuffer,快了很多。奇怪的是" + "第4种写法竟然也很快,比用StringBuffer还快,怎么回事?其实慢,第二种写" + "法由于用了StringBuffer,快了很多。奇怪的是第4种写法竟然也很快,比用StringBuffer还快,怎" + "比用StringBuffer还快,怎么回事?其r还快,怎么回事?其回事?其如果你调试过字符串连接的执行过程就会知"); private String date = new String("2016-3-10 18:11"); //初始化数据 private void initData() { ChatMsgInfo msgExample = new ChatMsgInfo("XiaoMing", date, text, true); chatMsgDataArrays.add(msgExample); chatMsgAdapter = new ChatMsgViewAdapter(this, chatMsgDataArrays); //listview绑定adapter lvChat.setAdapter(chatMsgAdapter); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.btn_send: send(); break; } } //发送按钮的响应函数 private void send() { //获取输入文本框内容 String sendContent = etSendContent.getText().toString(); if (sendContent.length() > 0) { ChatMsgInfo msg = new ChatMsgInfo("XiaoHong", getDate(), sendContent, false); chatMsgDataArrays.add(msg); //通过一个外部的方法控制如果适配器的内容改变时需要强制调用getView来刷新每个Item的内容。 Log.d("chattest", "after setchanged!"); chatMsgAdapter.notifyDataSetChanged(); etSendContent.setText(""); //定位到最后一行 Log.d("chattest", "after setSelection!"); lvChat.setSelection(lvChat.getCount() -1 ); } } //获取时间 private String getDate() { Calendar c = Calendar.getInstance(); String year = String.valueOf(c.get(Calendar.YEAR)); String month = String.valueOf(c.get(Calendar.MONTH)); String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1); String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY)); String mins = String.valueOf(c.get(Calendar.MINUTE)); StringBuffer buffer = new StringBuffer(); buffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); return buffer.toString(); } } ``` ``` package com.example.chattest; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class ChatMsgViewAdapter extends BaseAdapter { private static final int TYPE_COM_MSG = 0; private static final int TYPE_TO_MSG = 1; //private static final int TAG_KEY_ITEM_TYPE = 0; //private static final int TAG_KEY_VIEWHOLDER = 1; private List<ChatMsgInfo> data;//数据list private LayoutInflater myInflater;//layout convert view对象 private Context context;//环境 //构造 public ChatMsgViewAdapter(Context context, List<ChatMsgInfo> data) { this.context = context; this.data = data; myInflater = LayoutInflater.from(context); } @Override public int getItemViewType(int position) { // TODO Auto-generated method stub ChatMsgInfo msg = data.get(position); if (msg.getMsgType()) { return TYPE_COM_MSG; } else { return TYPE_TO_MSG; } } @Override public int getViewTypeCount() { // TODO Auto-generated method stub return 2; } //获取ListView的个数 @Override public int getCount() { return data.size(); } //获取项 @Override public Object getItem(int position) { return data.get(position); } //获取项的id @Override public long getItemId(int position) { return position; } //获取view @Override public View getView(int position, View convertView, ViewGroup parent) { ChatMsgInfo chatMsg = data.get(position);//聊天数据 boolean isComMsg = chatMsg.getMsgType();//数据类型(发送、接收) LeftItemViewHolder leftViewHolder = null; RightItemViewHolder rightViewHolder = null; int viewType = getItemViewType(position); System.out.println(position + " " + convertView); if (convertView == null || ((Integer)convertView.getTag(R.id.tag_item_viewtype)) != viewType) { //区分消息类别,展示不同的界面 if (viewType == TYPE_COM_MSG) { convertView = myInflater.inflate(R.layout.chat_msg_text_left_item, null); leftViewHolder = new LeftItemViewHolder(); leftViewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime); leftViewHolder.tvUserName = (TextView) convertView.findViewById(R.id.tv_username); leftViewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent); leftViewHolder.isComMsg = isComMsg; convertView.setTag(R.id.tag_item_viewholder, leftViewHolder); } else { convertView = myInflater.inflate(R.layout.chat_msg_text_right_item, null); rightViewHolder = new RightItemViewHolder(); rightViewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime); rightViewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent); rightViewHolder.isComMsg = isComMsg; convertView.setTag(R.id.tag_item_viewtype, rightViewHolder); } convertView.setTag(R.id.tag_item_viewtype, viewType); } else { if (viewType == TYPE_COM_MSG) { leftViewHolder = (LeftItemViewHolder) convertView.getTag(R.id.tag_item_viewholder); } else { rightViewHolder = (RightItemViewHolder) convertView.getTag(R.id.tag_item_viewholder); } } if (viewType == TYPE_COM_MSG) { leftViewHolder.tvUserName.setText(chatMsg.getName()); leftViewHolder.tvSendTime.setText(chatMsg.getDate()); leftViewHolder.tvContent.setText(chatMsg.getText()); } else { rightViewHolder.tvSendTime.setText(chatMsg.getDate()); rightViewHolder.tvContent.setText(chatMsg.getText()); } System.out.println(position + " " + convertView); return convertView; } //保存项,显示项的内容 static class LeftItemViewHolder { public TextView tvSendTime; public TextView tvUserName; public TextView tvContent; public boolean isComMsg = true; } static class RightItemViewHolder { public TextView tvSendTime; public TextView tvContent; public boolean isComMsg = true; } } ```
Android中怎样用自定义的adapter加载日期列表
想实现以下的效果,因为自己技术大白,不知道怎么处理,贴出代码: 我是用ViewPager + Fragment实现页面切换的,其中在fragmentB中有个按钮button,fragmentA中有个listview,现在想实现的是,通过点击B中的button,在A中的listview中显示一个item,item的名字用当前时间来设置。我用的是自定义的adapter, ``` private class DateAdapter extends ArrayAdapter<Date_item> { private int resourceId; public DateAdapter(Context context, int dateresourceId, List<Date_item> objects){ super(context, dateresourceId,objects); resourceId = dateresourceId; } @Override public View getView(int position,View convertView, ViewGroup parent){ Date_item date_item = getItem(position);//获取当前项的date实例 View view; ViewHolder viewHolder; if(convertView == null){ view = LayoutInflater.from(getContext()).inflate(resourceId,null); viewHolder = new ViewHolder(); viewHolder.date = (TextView)view.findViewById(R.id.chart_date); view.setTag(viewHolder);//将viewHolder缓存到view中 }else { view = convertView; viewHolder = (ViewHolder)view.getTag(); } return view; } class ViewHolder{ TextView date; } } ``` 我将A中列表的item也设置在了B中: ``` //列表item的时间形式 //设置时间格式 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss"); //获取当前时间 long time = System.currentTimeMillis(); //将long转化为Date Date date = new Data(time); String timeSave = format.format(date); ``` 在B中的button的监听事件里面: ``` btn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ DateAdapter dateAdapter =new DateAdapter(getActivity(),R.layout.item_layout,dateList); listView.setAdapter(dateAdapter); } }) ``` 程序一运行就闪退,错误是NullPointerException:Attempt to invoke virtual method'void android widget.ListView.setAdapter(android.widget.ListAdapter)'on a null object reference. 请问这是什么情况,这问题困了我很久了,在线等,感谢各位
进入页面虚拟机崩溃,找不到错误,求大神帮改下源码,谢谢啦
import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class StartCanteenActivity extends Activity { private static final String urlPath = "http://www.imooc.com/api/teacher?type=4&num=30"; //private static final String urlPath = "http://14.117.17.161/json.php"; private RecyclerView mRvDemoMain; private MyRecyclerAdapter mAdapter; private List<NewsBeam> mList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.canteen); mRvDemoMain = (RecyclerView) findViewById(R.id.canteen_recyclerview); new NewAsyncTask().execute(urlPath); initView(); } /** * 初始化本页面的控件 */ private void initView() { mRvDemoMain.setAdapter(mAdapter); // 设置RecyclerView的布局管理器 mRvDemoMain.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)); mRvDemoMain.setItemAnimator(new DefaultItemAnimator()); // 调用Adapter中的设置监听器的方法 mAdapter.setOnItemClickListener(new MyRecyclerAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Toast.makeText(StartCanteenActivity.this, "click : " + position, Toast.LENGTH_SHORT).show(); } }); } /** * 实现网络的异步访问 */ class NewAsyncTask extends AsyncTask<String, Void, List<NewsBeam>> { @Override protected void onPostExecute(List<NewsBeam> newsBeams) { super.onPostExecute(newsBeams); MyRecyclerAdapter adapter = new MyRecyclerAdapter(StartCanteenActivity.this, newsBeams, mRvDemoMain); mRvDemoMain.setAdapter(adapter); } @Override protected List<NewsBeam> doInBackground(String... params) { return getJsonData(params[0]); } /** * 从 URL 中获取数据 * * @param url * @return */ private List<NewsBeam> getJsonData(String url) { List<NewsBeam> newsBeamsList = new ArrayList<NewsBeam>(); try { String jsonString = readStream(new URL(urlPath).openStream()); JSONObject jsonObject; NewsBeam newsBeam; jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("data"); for(int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); newsBeam = new NewsBeam(); newsBeam.newsIconUrl = jsonObject.getString("picSmall"); newsBeam.newsTitle = jsonObject.getString("name"); newsBeamsList.add(newsBeam); } } catch(IOException e) { e.printStackTrace(); } catch(JSONException e) { e.printStackTrace(); } return newsBeamsList; } /** * 从 inpustStream 获取的信息 * * @param is * @return */ private String readStream(InputStream is) { InputStreamReader isr; String result = ""; try { isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String line = ""; while((line = br.readLine()) != null) { result += line; } } catch(UnsupportedEncodingException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } return result; } } } import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyRecyclerHolder> { protected LayoutInflater mLayoutInflater; private Context mContext; protected List<NewsBeam> mList; private List<Integer> mHeights; // 随机高度的集合 private ImgLoader mImgLoader; private int mStart; private int mEnd; public static String[] URLS; private boolean mFirstIn; private MyRecyclerAdapter(List<NewsBeam> mList) { this.mList = mList; } /** * 自定义一个OnItemClickListener的回调接口 */ public interface OnItemClickListener{ void onItemClick(View view, int position); } /** * 创建接口的成员变量 */ private OnItemClickListener mOnItemClickListener; /** * 设置监听器的方法 * @param listener listener */ public void setOnItemClickListener(OnItemClickListener listener){ this.mOnItemClickListener = listener; } /** * 构造方法 * @param context context * @param data data */ public MyRecyclerAdapter(Context context, List<NewsBeam> data,RecyclerView recyclerView) { this.mContext = context; this.mList = data; mLayoutInflater = LayoutInflater.from(mContext); mImgLoader = new ImgLoader(recyclerView); mLayoutInflater = LayoutInflater.from(mContext); mHeights = new ArrayList<Integer>(); // 向随机高度集合中添加随机数(100 ~ 400) for (int i = 0; i < mList.size(); i++) { mHeights.add((int) (100 + Math.random() * 300)); } URLS = new String[data.size()]; for(int i = 0; i < data.size(); i++) { URLS[i] = data.get(i).newsIconUrl; } mFirstIn = true; } /** * RecyclerView中条目的数量 * * @return count */ @Override public int getItemCount() { return mList.size(); } /** * 创建ViewHolder * * @param parent parent * @param viewType viewType * @return holder */ @Override public MyRecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) { // zz 测试 System.out.println("====onCreateViewHolder : " + viewType + " == " + parent); View view = mLayoutInflater.inflate(R.layout.recycler_item, parent, false); MyRecyclerHolder mHolder = new MyRecyclerHolder(view); return mHolder; } /** * 绑定ViewHolder * * @param holder holder * @param position position */ @Override public void onBindViewHolder(final MyRecyclerHolder holder, final int position) { // 为ViewHolder的父控件(也即一条Item)设置高度 ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); lp.height = mHeights.get(position); holder.itemView.setLayoutParams(lp); holder.mIvItem.setImageBitmap(null); holder.mIvItem.setImageResource(R.mipmap.ic_launcher); String url = mList.get(position).newsIconUrl; holder.mIvItem.setTag(url); mImgLoader.showImgByAysncTask(holder.mIvItem, url); holder.mTvItem.setText(mList.get(position).newsTitle); // 调用条目的点击事件设置方法 setUpItemEvent(holder); // zz 测试 System.out.println("====onBindViewHolder : " + position + " == " + holder); } /** * 设置条目的点击事件(点按) * @param holder holder */ protected void setUpItemEvent(final MyRecyclerHolder holder) { if (mOnItemClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int layoutPosition = holder.getLayoutPosition(); mOnItemClickListener.onItemClick(holder.itemView, layoutPosition); } }); } } /** * RecyclerView的ViewHolder类 */ public class MyRecyclerHolder extends RecyclerView.ViewHolder { ImageView mIvItem; TextView mTvItem; public MyRecyclerHolder(View itemView) { super(itemView); mIvItem = (ImageView) itemView.findViewById(R.id.id_image); mTvItem = (TextView) itemView.findViewById(R.id.id_name); } } }
Android ListView 自定义Adapter 滑动时报空指针异常
问题背景:在制作一个即时聊天的APP中,聊天界面聊天消息的显示我使用了ListView,并且使用了自定义的Adapter,获取到聊天记录之后ListView可以正常显示,但是一旦滑动就会报空指针异常。我查看了很多博客,都没有提到与这个相关或者类似的错误已经被这个错误逼疯了,希望有了解的大神能够给予指点。 具体相关代码如下: 自定义的Adapter: ``` public class ChatMessageAdapter extends BaseAdapter { private LayoutInflater layoutInflater; private List<MessageShow> messageShowList; public ChatMessageAdapter(Context context, List<MessageShow> messageShowList){ layoutInflater = LayoutInflater.from(context); this.messageShowList = messageShowList; } @Override public int getCount() { return messageShowList.size(); } @Override public Object getItem(int position) { return messageShowList.get(position); } @Override public int getItemViewType(int position) { if(messageShowList.get(position).getMessageType()==0) return 0; else return 1; } //Item类型的总数 @Override public int getViewTypeCount() { return 2; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { MessageShow messageShow = messageShowList.get(position); ViewHolder viewHolder = null; if(convertView == null){ if(messageShow.getMessageType() == 0){ convertView = layoutInflater.inflate(R.layout.from_message_item,null); viewHolder = new ViewHolder(); // viewHolder.imageView = (ImageView) convertView.findViewById(R.id.from_user_icons); viewHolder.time = (TextView) convertView.findViewById(R.id.from_time); viewHolder.message = (TextView) convertView.findViewById(R.id.from_message); } else{ convertView = layoutInflater.inflate(R.layout.to_message_item,null); viewHolder = new ViewHolder(); // viewHolder.imageView = (ImageView) convertView.findViewById(R.id.to_user_icons); viewHolder.time = (TextView) convertView.findViewById(R.id.to_time); viewHolder.message = (TextView) convertView.findViewById(R.id.to_message); } } else { viewHolder = (ViewHolder) convertView.getTag(); } System.out.println("我到了这里"+position); System.out.println("我添加了适配器: "+messageShow.getContents()); // viewHolder.imageView.setImageResource(R.drawable.photo); //报空指针异常的是这里 viewHolder.message.setText(messageShow.getContents()); viewHolder.time.setText(messageShow.getTime()); return convertView; } private final class ViewHolder{ // ImageView imageView; TextView time; TextView message; } ``` ,ChatActivity代码如下: ``` private List<MessageShow> showMessageList; private ChatMessageAdapter chatMessageAdapter; 、、、省略无关 //初始化数据 private void initData(){ showMessageList = new ArrayList<MessageShow>(); chatMessageAdapter = new ChatMessageAdapter(this,showMessageList); listView.setAdapter(chatMessageAdapter); getMessageRecord(); chatMessageAdapter.notifyDataSetChanged(); } ``` 其中获取聊天记录我已经在控制台打印出来检查过了,没有错误,而ListView能够显示说明Apapter也不会有基本的错误,但是还是报空指针。我对错误的猜测如下: 虽然给的数据集可能有几十项,但是Adapter加载的时候只加载了当前显示的几项,后面的没加载,等我我滑动之后去加载的时候没加载到数据就报空指针了。但是这不太科学啊,我看了好多博客发现都没有专门说到这点,仔细检查代码也不知道应该怎么改,求指教。报错信息如下: ``` I/System.out: 我到了这里1 I/System.out: 我添加了适配器: 图片这些不能点击? I/System.out: 我到了这里2 I/System.out: 我添加了适配器: 还没做那些功能呢233 I/System.out: 我到了这里3 I/System.out: 我添加了适配器: 图片和表情 I/System.out: 我到了这里4 I/System.out: 我添加了适配器: 额 I/System.out: 我到了这里5 I/System.out: 我添加了适配器: 准备等APP开发完之后再说 I/System.out: 我到了这里6 I/System.out: 我添加了适配器: 真的挺费脑的 I/System.out: 我到了这里7 I/System.out: 我添加了适配器: 嗯 加油 E/InputEventReceiver: Exception dispatching input event. D/AndroidRuntime: Shutting down VM W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6160908) E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException at cn.justwithme.withme.Adapaer.ChatMessageAdapter$override.getView(ChatMessageAdapter.java:84) at cn.justwithme.withme.Adapaer.ChatMessageAdapter$override.access$dispatch(ChatMessageAdapter.java) at cn.justwithme.withme.Adapaer.ChatMessageAdapter.getView(ChatMessageAdapter.java:0) ``` 本来有十几项的,第一页只有7项,我在Adapter的输出就只出输出了7项。 ![图片说明](https://img-ask.csdn.net/upload/201702/19/1487495789_116858.png) ![图片说明](https://img-ask.csdn.net/upload/201702/19/1487495801_419892.png)
Android新手急求:ListView点击删除按钮时,总是最后一个item被删除
如题,我的ListView的每个item都有一个删除按钮,但是每次点击按钮后都是删除了最后一个item。 调试后position是正确的,索引是没有问题的,每次删除的都是正确的位置,而且每次item一删除就调用notifyDataSetChanged()去刷新,这个问题困扰好几天了…麻烦大神帮帮忙。 另外我这个MyAdapter类是写在MainActivity类里面的,我是有添加到arr里的,纯粹是为了方便……我不知道是不是这个引起的问题。 public class MyAdapter extends BaseAdapter { private Context context; private LayoutInflater inflater; public ArrayList<String> arr; public MyAdapter(Context context) { super(); this.context = context; inflater = LayoutInflater.from(context); arr = new ArrayList<String>(); } @Override public int getCount() { return arr.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(final int position, View convertView, ViewGroup arg2) { // TODO Auto-generated method stub ViewHolder viewHolder = null; if(convertView == null){ viewHolder = new ViewHolder(); convertView = inflater.inflate(R.layout.mission_item, null); viewHolder.mission_name = (TextView) convertView.findViewById(R.id.pro_name); viewHolder.mission_add = (TextView) convertView.findViewById(R.id.pro_add); viewHolder.mission_phone = (TextView) convertView.findViewById(R.id.pro_phone); viewHolder.del = (Button) convertView.findViewById(R.id.del); SharedPreferences shared_mission = getSharedPreferences("mission", Activity.MODE_PRIVATE); viewHolder.mission_name.setText(shared_mission.getString("name", "")); viewHolder.mission_add.setText(shared_mission.getString("address", "")); viewHolder.mission_phone.setText(shared_mission.getString("phone", "")); convertView.setTag(viewHolder); }else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.del.setTag(position); viewHolder.del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub arr.remove(position); mission_adapter.notifyDataSetChanged(); } }); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) { Intent intent = new Intent(); intent.setClass(MainActivity.this, MissionInfo.class); startActivity(intent); } }); return convertView; } class ViewHolder { //任务界面 TextView mission_name,mission_add,mission_phone; Button del; } }
pulltorefresh下拉后不能恢复刷新前
我用 ContentProvider 做了一个查询系统中联系人的 DEMO,将查询出来的联系人信息放在 ListView 里面展示,用到了 pulltorefresh 框架,但是遇到一个问题,就是在下拉刷新之后那个“正在刷新” 会一起显示,并不会自己恢复。求大家帮忙看一下,我用的列表适配器是自定义的 CursorAdapter ,官方文档上面说用 CursorAdapter 要备份一个 ListView 和一个 Cursor ,我不明白是什么意思,我在 onrefresh 里面调用了 listview.onRefreshComplete() 方法,但是也不会恢复,我估计是因为用了 CursorAdapter 的缘故。 这个是 Activity 页面 ``` package com.caoligai.contentproviderdemo.activity; import com.caoligai.contentproviderdemo.R; import com.caoligai.contentproviderdemo.adapter.MyCursorAdapter; import com.handmark.pulltorefresh.library.IPullToRefresh; import com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshListView; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.opengl.Visibility; import android.os.AsyncTask; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.Contacts; import android.support.v4.widget.SimpleCursorAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; /** * * @author caoligai E-mail: * @date 创建时间:2015-5-7 下午8:50:08 * @version 1.0 * @parameter * * @since * @return */ public class ContactList extends Activity { String tag = "ContactList"; PullToRefreshListView listview; MyCursorAdapter adapter; ProgressDialog pd; Cursor cursor; Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, }; boolean isFirstLoad = true; public ListView actualListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contactlist); // Log.d(tag, "cursor's length = " + cursor.getCount()); listview = (PullToRefreshListView) findViewById(R.id.listview); listview.setMode(Mode.PULL_FROM_START); listview.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { refreshView.setRefreshing(true); listview.onRefreshComplete(); } }); new listviewLoader().execute(null, null, null); } class listviewLoader extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { Log.d(tag, "listviewLoader.onPreExecute()"); pd = new ProgressDialog(ContactList.this); pd.setCancelable(false); pd.setMessage("正在查询数据..."); pd.show(); } @Override protected Void doInBackground(Void... params) { Log.d(tag, "listviewLoader.doInBackground()"); cursor = getContentResolver().query(Contacts.CONTENT_URI, projection, null, null, null); Log.d(tag, "cursor.length = " + cursor.getCount()); isFirstLoad = false; return null; } @Override protected void onPostExecute(Void result) { Log.d(tag, "listviewLoader.onPostExecute()"); pd.dismiss(); adapter = new MyCursorAdapter(ContactList.this, cursor, getLayoutInflater(), getContentResolver()); listview.setAdapter(adapter); } } @Override protected void onDestroy() { super.onDestroy(); finish(); } } ``` 这个是自定义的 CursorAdapter ``` package com.caoligai.contentproviderdemo.adapter; import com.caoligai.contentproviderdemo.R; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; /** * * @author caoligai * * 自定义游标适配器,用于将 cursor 游标的数据映射到 ListView 中 * */ public class MyCursorAdapter extends CursorAdapter { LayoutInflater flater; Context context; ContentResolver cr; public MyCursorAdapter(Context context, Cursor c, LayoutInflater flater, ContentResolver cr) { super(context, c); this.context = context; this.flater = LayoutInflater.from(context); this.cr = cr; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { ViewHolder holder = new ViewHolder(); View item = flater.inflate(R.layout.list_item, null); holder.name = (TextView) item.findViewById(R.id.item_name); holder.number = (TextView) item.findViewById(R.id.item_number); item.setTag(holder); return item; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); // TextView name = (TextView) view.findViewById(R.id.item_name); // 设置姓名的值 holder.name.setText(cursor.getString(cursor .getColumnIndex(Contacts.DISPLAY_NAME))); // 根据联系人 id 查询电话号码 Cursor idcursor = cr .query(CommonDataKinds.Phone.CONTENT_URI, null, CommonDataKinds.Phone.CONTACT_ID + " = " + cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts._ID)), null, null); //一个联系人可能有多个电话号码,这里只处理同一个联系人的第一个号码 Log.d(null, "idcursor.length = " + idcursor.getCount()); if (idcursor.moveToNext()) { holder.number .setText(idcursor.getString(idcursor .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))); } } static class ViewHolder { TextView name; TextView number; } } ``` 运行之后一起保持这个样子 ![图片说明](https://img-ask.csdn.net/upload/201505/08/1431070940_919643.png)
android 怎么优化ListView
怎么优化listView,普通的优化我知道(convertView+ViewHolder),我主要是想知道关于数据方面怎么优化, 比如说,我的adpater中有一个ArrayList用来保存从服务端获取的数据集合。ArrayList中存放的是Person这个类, Person类中定义的都是String类型的数据,不过有一个有点占内存,就是图片的16进制字符串。 那么当我初始化这个ListView的时候,服务端向我发过来10条Person数据,那么10条数据就会添加到ArrayList中, 当我上拉刷新,又向服务端请求,服务端又返回了10条数据,那么就会又向ArrayList里面添加10条数据。那么假如一直上拉刷新?程序不就OOM了吗? 在网上查找了一些资料,还是没有完全弄明白到底要怎么解决。求帮助 (๑>m<๑)
ListView列表文字无故变灰
我参考了官方的代码listview Adapter用法,但是移植过来listview文字就变成灰了,并且能选中 下面贴出代码。已经DEBUG 子线程返回data没问题。 这是运行图片。 ![图片说明](https://img-ask.csdn.net/upload/201503/20/1426828176_449082.png) ``` package com.wastrel.activity; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import com.wastrel.provider.Tabletbl; import com.wastrel.provider.TabletblDAO; import com.wastrel.util.HttpUtil; import android.app.ListActivity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class ChaZhuoActivity extends ListActivity { private Handler myhander = null; // private ListView tablelist = null; // private TextView tableid = null; private List<Tabletbl> data = new ArrayList<Tabletbl>(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO 自动生成的方法存根 super.onCreate(savedInstanceState); // setContentView(R.layout.activity_chazhuo); // tablelist = (ListView) findViewById(R.id.tablelist); // tableid = (TextView) findViewById(R.id.tablenum); myhander = new Handler() { @SuppressWarnings("unchecked") @Override public void handleMessage(Message msg) { // TODO 自动生成的方法存根 switch (msg.what) { case 1: data = (List<Tabletbl>) msg.obj; TableListAdapter tblAdapter = new TableListAdapter(data, getApplicationContext()); setListAdapter(tblAdapter); break; default: break; } } }; new Thread(updatetable).start(); } Runnable updatetable = new Runnable() { @Override public void run() { // TODO 自动生成的方法存根 String urlStr = HttpUtil.Base_URL + "servlet/UpdateTableServlet"; try { // 实例化URL对象 URL url = new URL(urlStr); // 打开连接 URLConnection conn = url.openConnection(); // 获得输入流 InputStream in = conn.getInputStream(); // 实例化DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); // 实例化DocumentBuilder DocumentBuilder builder = factory.newDocumentBuilder(); // 获得Document Document doc = builder.parse(in); // 获得节点列表 NodeList nl = doc.getElementsByTagName("table"); TabletblDAO tabletblDAO = new TabletblDAO( getApplicationContext()); if (nl.getLength() > 0) { tabletblDAO.DeleteData(); } // 循环将数据保存到菜谱表 List<Tabletbl> list = new ArrayList<Tabletbl>(); for (int i = 0; i < nl.getLength(); i++) { // 实例化ContentValues // 解析XML文件获得桌号id int id = Integer.parseInt(doc.getElementsByTagName("id") .item(i).getFirstChild().getNodeValue()); int num = Integer.parseInt(doc.getElementsByTagName("num") .item(i).getFirstChild().getNodeValue()); // 名称 String name = doc.getElementsByTagName("name").item(i) .getFirstChild().getNodeValue(); int flag = Integer.parseInt(doc .getElementsByTagName("flag").item(i) .getFirstChild().getNodeValue()); String description = doc .getElementsByTagName("description").item(i) .getFirstChild().getNodeValue(); /* * values.put("id", id); values.put("num", num); * values.put("name", name); values.put("flag", flag); * values.put("description", description); */ list.add(new Tabletbl(id, num, name, flag, description)); // 添加到ContenValues对象 // 插入到数据库 // tabletblDAO.AddTabletblDAO(values); } Message msg = myhander.obtainMessage(); msg.what = 1; msg.obj = list; myhander.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } }; private static class TableListAdapter extends BaseAdapter { public List<Tabletbl> mlist = null; private Context context; public TableListAdapter(List<Tabletbl> list, Context c) { mlist = list; context = c; } @Override public int getCount() { // TODO 自动生成的方法存根 return mlist.size(); } @Override public Object getItem(int position) { // TODO 自动生成的方法存根 return position; } @Override public long getItemId(int position) { // TODO 自动生成的方法存根 return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO 自动生成的方法存根 ViewHolder holder; // When convertView is not null, we can reuse it directly, there is // no // need // to reinflate it. We only inflate a new View when the convertView // supplied // by ListView is null. if (convertView == null) { LayoutInflater mInflater = LayoutInflater.from(context); convertView = mInflater.inflate(R.layout.chazhuo_list, null); // Creates a ViewHolder and store references to the two children // views // we want to bind data to. holder = new ViewHolder(); holder.idtext = (TextView) convertView .findViewById(R.id.chazhuo_id); holder.nametext = (TextView) convertView .findViewById(R.id.chazhuo_name); holder.flagtext = (TextView) convertView .findViewById(R.id.chazhuo_flag); holder.remarktext = (TextView) convertView .findViewById(R.id.chazhuo_remark); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } // Bind the data efficiently with the holder. holder.idtext.setText(String.valueOf(mlist.get(position).getId())); holder.nametext.setText(mlist.get(position).getName()); if (mlist.get(position).getFlag() == 0) holder.flagtext.setText(context .getString(R.string.chazhuo_kongxian)); else if (mlist.get(position).getFlag() == 1) { holder.flagtext.setText(context .getString(R.string.chazhuo_youren)); } else { holder.flagtext.setText(context .getString(R.string.chazhuo_unkown)); } holder.remarktext.setText(mlist.get(position).getDescription()); return convertView; } static class ViewHolder { TextView idtext; TextView nametext; TextView flagtext; TextView remarktext; } } } ``` 这段XML 我在官方的demo上试了 没问题。 ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:padding="5dp" > <TextView android:id="@+id/textView1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:id="@+id/textView2" android:layout_width="0dp" android:layout_weight="2" android:layout_height="wrap_content" /> <TextView android:id="@+id/textView3" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> <TextView android:id="@+id/textView4" android:layout_width="0dp" android:layout_weight="2" android:layout_height="wrap_content" /> </LinearLayout> ``` 这个问题我搞了一两天了 找不到哪里的问题。求大神解决。
求助大神!android的baseadapter老是报空指针
package com.example.kaoqin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.ObjectUtils.Null; import android.R.integer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class User_TiaoZhuan_Activity2 extends Activity { private ListView list; private SimpleAdapter SAda; public String huoquuser; private String[] From = new String[]{"yonghu","kaishi","jieshu","zong","yuanyin","zhuangtai","id"}; public ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>(); private ArrayList<ItemBean> datalist = new ArrayList<ItemBean>(); public String NAME; public String START; public String END; public String SUM; public String REASON; public String STATE; public String ID; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.user_tiaozhuan_activity2); list = (ListView)findViewById(R.id.listViewuser); Intent intent = getIntent();//将检索出来的intent赋值给一个Intent类型的变量intent,getIntent()方法用于直接返回Intent实例 Bundle bundle = intent.getExtras();///获取前面的那个activity传过来的数据 huoquuser = bundle.getString("username"); HttpClien httpClien = new HttpClien(); data = httpClien.HTTPLeaveListView(huoquuser, "2"); //SAda = new SimpleAdapter(User_TiaoZhuan_Activity2.this, getdata(data),R.layout.user_tiaozhuan_buju2, From,new int[]{R.id.tiaozhuan_user2, //R.id.tiaozhuan_start2,R.id.tiaozhuan_end2,R.id.tiaozhuan_sum2,R.id.tiaozhuan_reason2,R.id.tiaozhuan_shenhe2,R.id.tiaozhuan_id2}); //list.setAdapter(SAda); Edit nihao = new Edit(this, getdata(data));//把数据源放入baseadapter list.setAdapter(nihao); } public ArrayList<ItemBean> getdata(ArrayList<HashMap<String,Object>> shuju) { for (int i = 0; i < data.size(); i++) { NAME = String.valueOf(shuju.get(i).get("name")); START = String.valueOf(shuju.get(i).get("start")); END = String.valueOf(shuju.get(i).get("end")); SUM = String.valueOf(shuju.get(i).get("sum")); REASON = String.valueOf(shuju.get(i).get("reason")); STATE = String.valueOf(shuju.get(i).get("state")); ID = String.valueOf(shuju.get(i).get("id")); ItemBean it = new ItemBean(NAME, START, END, SUM, REASON, STATE,ID); datalist.add(it); } return datalist; } } class Edit extends BaseAdapter { private Context context; private ArrayList<ItemBean> list; private LayoutInflater miInflater; public Edit(Context context,ArrayList<ItemBean> list) { LayoutInflater miInflater; miInflater = LayoutInflater.from(context); this.context = context; this.list = list; //根据context上下文加载布局,这里的是User_TiaoZhuan_Activity本身,即this } @Override public int getCount() { // TODO Auto-generated method stub //在此适配器中所代表的数据集中的条目数 return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub //获取数据集中与指定索引对应的数据项 return list.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub //获取在列表中与指定索引对应的行id return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder kongjian = null; if(convertView == null) { convertView = miInflater.inflate(R.layout.user_tiaozhuan_buju2, null); kongjian = new ViewHolder(); kongjian.TV_sure = (TextView)convertView.findViewById(R.id.yunxu); kongjian.TV_cancel = (TextView)convertView.findViewById(R.id.bohui); kongjian.TVuser = (TextView)convertView.findViewById(R.id.tiaozhuan_user2); kongjian.TVstart = (TextView)convertView.findViewById(R.id.tiaozhuan_start2); kongjian.TVend = (TextView)convertView.findViewById(R.id.tiaozhuan_end2); kongjian.TVsum = (TextView)convertView.findViewById(R.id.tiaozhuan_sum2); kongjian.TVreason = (TextView)convertView.findViewById(R.id.tiaozhuan_reason2); kongjian.TVstate = (TextView)convertView.findViewById(R.id.tiaozhuan_shenhe2); kongjian.TVid = (TextView)convertView.findViewById(R.id.tiaozhuan_id2); //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag convertView.setTag(kongjian); }else { kongjian = (ViewHolder)convertView.getTag(); } kongjian.TV_sure.setText("允许请假"); kongjian.TV_cancel.setText("驳回请假"); ItemBean bean = list.get(position); kongjian.TVuser.setText(bean.Itemuser);; kongjian.TVstart.setText(bean.Itemstarttime); kongjian.TVend.setText(bean.Itemendtime); kongjian.TVsum.setText(bean.Itemsumtime); kongjian.TVreason.setText(bean.Itemreason); kongjian.TVstate.setText(bean.Itemstate); kongjian.TVid.setText(bean.ItemId); kongjian.TV_sure.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub System.out.println("通过"); } }); kongjian.TV_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub System.out.println("不通过"); } }); return convertView; } } class ViewHolder { TextView TV_sure; TextView TV_cancel; TextView TVuser; TextView TVstart; TextView TVend; TextView TVsum; TextView TVreason; TextView TVid; TextView TVstate; } class ItemBean { public String Itemuser; public String Itemstarttime; public String Itemendtime; public String Itemsumtime; public String Itemreason; public String Itemstate; public String ItemId; public ItemBean(String a,String b,String c, String d,String e,String f,String g) { Itemuser = a; Itemstarttime = b; Itemendtime = c; Itemsumtime = d; Itemreason = e; Itemstate = f; ItemId = g; } }![图片说明](https://img-ask.csdn.net/upload/201611/10/1478771417_684227.png) 错误显示的是121行存在空指针,inflate里的布局文件是存在的啊,R类里也有 地址啊(R.layout.user_tiaozhuan_buju2, null);
HorizontalScrollView在ListView被回收利用
我有一个ListView,子view是HorizontalScrollView,当我对的ListView中的第一个子HorizontalScrollView从右边滑动到左边,把删除按钮显示出来之后,我再操作ListView上下滚动时,ListView会复用之前滑动HorizontalScrollView的view. ![图片说明](https://img-ask.csdn.net/upload/201605/08/1462722379_958525.png) ![图片说明](https://img-ask.csdn.net/upload/201605/08/1462722547_369286.png) 我的代码: ListView 子view布局: ``` <?xml version="1.0" encoding="utf-8"?> <com.example.administrator.myapplication.DeleteView android:id="@+id/GrafDelete_root" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#f1f1f1" android:scrollbars="none" > <LinearLayout android:id="@+id/ll_content" android:layout_width="920px" android:layout_height="180px" android:orientation="horizontal"> <RelativeLayout android:id="@+id/re_select" android:layout_width="80px" android:layout_height="180px" android:background="@color/colorAccent"> <ImageView android:id="@+id/select" android:layout_width="36px" android:layout_height="36px" android:layout_centerInParent="true" android:scaleType="centerCrop"/> </RelativeLayout> <AbsoluteLayout android:id="@+id/ab_view_bg" android:layout_width="720px" android:layout_height="180px"> <TextView android:id="@+id/text_title" android:layout_width="450px" android:layout_height="80px" android:layout_x="20px" android:layout_y="30px" android:gravity="center_vertical" android:maxLines="2" android:textColor="#515151" android:textSize="30px" /> </AbsoluteLayout> <AbsoluteLayout android:id="@+id/ab_delete_bg" android:layout_width="wrap_content" android:layout_height="wrap_content"> <View android:id="@+id/view_delete_bg" android:layout_width="120px" android:layout_height="180px" android:background="#ff0000" ></View> <TextView android:id="@+id/text_delete" android:layout_width="120px" android:layout_height="60px" android:layout_y="90px" android:gravity="center" android:text="删除" android:textColor="#ffffff" android:textSize="30px" /> </AbsoluteLayout> </LinearLayout> </com.example.administrator.myapplication.DeleteView> ``` 自定义的HorizontalScrollView,可以从又滑动到左边,显示被影藏的删除按钮: ``` public class DeleteView extends HorizontalScrollView { private static final int SWIPE_MIN_DISTANCE = 5; private static final int SWIPE_THRESHOLD_VELOCITY = 600; private GestureDetector gestureDetector; private Context context; private int start;//开始滑动的位置 private int end;//结束滑动的位置 private VelocityTracker velocityTracker; private int width;//屏幕宽度的额外宽度。 private boolean isEnableScroll;//是否打开水平滑动 true可以水平滑动 false不能水平滑动 public DeleteView(Context context) { super(context); } public DeleteView(Context context, AttributeSet attrs) { super(context, attrs); width = 120;//设定额外的宽度 gestureDetector = new GestureDetector(new MyGestureDetector()); } public DeleteView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent event) { if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } if (!isEnableScroll) return true; if (gestureDetector.onTouchEvent(event)) return true; if (event.getAction() == MotionEvent.ACTION_DOWN) { start = (int) event.getRawX(); } if (event.getAction() == MotionEvent.ACTION_UP) { end = (int) event.getRawX(); if (start > end) { if (getScrollX() < width / 2 || velocityTracker.getXVelocity() > SWIPE_THRESHOLD_VELOCITY) { smoothScrollTo(0, 0); } else { smoothScrollTo(width, 0); } } if (start < end) { if (getScrollX() > width / 2 || velocityTracker.getXVelocity() > SWIPE_THRESHOLD_VELOCITY) { smoothScrollTo(width, 0); } else { smoothScrollTo(0, 0); } } velocityTracker.clear(); return true; } if (event.getAction() == MotionEvent.ACTION_MOVE) { velocityTracker.addMovement(event); } return super.onTouchEvent(event); } class MyGestureDetector extends GestureDetector.SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (!isEnableScroll) return true; try { //right to left if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { smoothScrollTo(width, 0); return true; } } catch (Exception e) { // nothing } return false; } } //是否开启水平滑动 public void setEnAbleHorizontalScroll(boolean b) { if (b == isEnableScroll) { return; } else { isEnableScroll = b; } if (!isEnableScroll) { smoothScrollTo(0, 0); } } } ``` Adapter: ``` public class ListAdapter extends BaseAdapter { private Context context; private ArrayList<ListItem> items; private boolean isAble; public ListAdapter(Context context, ArrayList<ListItem> items) { this.context = context; this.items = items; } @Override public int getCount() { return items.size(); } @Override public ListItem getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null); holder.mDelete_Item_root = (DeleteView) convertView.findViewById(R.id.GrafDelete_root); holder.ll_content = (LinearLayout) convertView.findViewById(R.id.ll_content); holder.re_select = (RelativeLayout) convertView.findViewById(R.id.re_select); holder.select = (ImageView) convertView.findViewById(R.id.select); holder.ab_view_bg = (AbsoluteLayout) convertView.findViewById(R.id.ab_view_bg); holder.text_title = (TextView) convertView.findViewById(R.id.text_title); AbsoluteLayout ab_delete_bg = (AbsoluteLayout) convertView.findViewById(R.id.ab_delete_bg); holder.view_delete_bg = convertView.findViewById(R.id.view_delete_bg); TextView text_delete = (TextView) convertView.findViewById(R.id.text_delete); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if (isAble) {//Open edit DeleteView.LayoutParams layoutParams = new DeleteView.LayoutParams(920, 180); layoutParams.leftMargin = 0; holder.ll_content.setLayoutParams(layoutParams); ((DeleteView) convertView).setEnAbleHorizontalScroll(false); } else {//Editing is not open DeleteView.LayoutParams layoutParams = new DeleteView.LayoutParams(920, 180); layoutParams.leftMargin = -80; holder.ll_content.setLayoutParams(layoutParams); ((DeleteView) convertView).setEnAbleHorizontalScroll(true); } if (items.get(position).isSelected) { holder.select.setBackgroundResource(R.mipmap.item_selected1); } else { holder.select.setBackgroundResource(R.mipmap.item_select_un); } View.OnTouchListener listener = new View.OnTouchListener() { boolean select_out, delete_out; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: switch (v.getId()) { case R.id.re_select: select_out = false; break; case R.id.view_delete_bg: holder.view_delete_bg.setAlpha(0.5f); delete_out = false; break; } break; case MotionEvent.ACTION_MOVE: switch (v.getId()) { case R.id.re_select: int x = (int) event.getX(); int y = (int) event.getY(); if (x < 0 || y < 0 || x > holder.re_select.getWidth() || y > holder.re_select.getHeight()) { select_out = true; } break; case R.id.view_delete_bg: int x2 = (int) event.getX(); int y2 = (int) event.getY(); if (x2 < 0 || y2 < 0 || x2 > holder.view_delete_bg.getWidth() || y2 > holder.view_delete_bg.getHeight()) { holder.view_delete_bg.setAlpha(1.0f); delete_out = true; } break; } break; case MotionEvent.ACTION_UP: switch (v.getId()) { case R.id.re_select: if (select_out) { return true; } if (items.get(position).isSelected) { items.get(position).isSelected = false; holder.select.setBackgroundResource(R.mipmap.item_select_un); } else { items.get(position).isSelected = true; holder.select.setBackgroundResource(R.mipmap.item_selected1); } break; case R.id.view_delete_bg: holder.view_delete_bg.setAlpha(1.0f); if (delete_out) return true; if (isAble) return true; break; } break; case MotionEvent.ACTION_CANCEL: switch (v.getId()) { case R.id.re_select: break; case R.id.view_delete_bg: holder.view_delete_bg.setAlpha(1.0f); break; } break; } return true; } }; holder.re_select.setOnTouchListener(listener); holder.view_delete_bg.setOnTouchListener(listener); holder.text_title.setText(items.get(position).mString); return convertView; } private class ViewHolder { TextView text_title; RelativeLayout re_select; ImageView select; AbsoluteLayout ab_view_bg, ab_delete_bg; View view_delete_bg; // TextView text_delete; LinearLayout ll_content; DeleteView mDelete_Item_root; } /** * You can edit */ public void setIsAble(boolean b) { if (b == isAble) { return; } else { isAble = b; notifyDataSetChanged(); } } } ``` Activity: ``` public class MainActivity extends AppCompatActivity { private ListView listView; private TextView tv_button; private ArrayList<ListItem> mArrayList = new ArrayList<>(); private boolean isAble; private ListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); tv_button = (TextView) findViewById(R.id.tv_button); getListItem(); adapter = new ListAdapter(this, mArrayList); listView.setAdapter(adapter); setListener(); } public void setListener() { View.OnTouchListener listener = new View.OnTouchListener() { boolean delete_out; @Override public boolean onTouch(View arg0, MotionEvent arg1) { switch (arg1.getAction()) { case MotionEvent.ACTION_DOWN: switch (arg0.getId()) { case R.id.tv_button: tv_button.setAlpha(0.5f); delete_out = false; break; } break; case MotionEvent.ACTION_MOVE: switch (arg0.getId()) { case R.id.tv_button: int x2 = (int) arg1.getX(); int y2 = (int) arg1.getY(); if (x2 < 0 || y2 < 0 || x2 > tv_button.getWidth() || y2 > tv_button.getHeight()) { tv_button.setAlpha(1.0f); delete_out = true; } break; } break; case MotionEvent.ACTION_UP: switch (arg0.getId()) { case R.id.tv_button: tv_button.setAlpha(1.0f); if (delete_out) return true; changeState(); break; } break; case MotionEvent.ACTION_CANCEL: switch (arg0.getId()) { case R.id.tv_button: tv_button.setAlpha(1.0f); break; } } return true; } }; tv_button.setOnTouchListener(listener); } //点编辑或完成时切换状态 private void changeState() { if (isAble) { isAble = false; tv_button.setText("编辑"); } else { isAble = true; tv_button.setText("完成"); } adapter.setIsAble(isAble); } private void getListItem() { for (int i = 0; i < 20; i++) { ListItem listItem = new ListItem(); listItem.mString = i + "\t" + "ScrollView and HorizontalScrollView conflict"; mArrayList.add(listItem); } } } ```
android listview添加出现问题
我是一枚新手,在写添加listview并对数据库进行增删改查时遇到了问题,添加listview时我想添加一个item可是一添加就添加了好多行,还有插入数据后不能listview没有显示之前插入的值,求大神给看看!这是我的代码: ``` public class DLXMainActivity extends AppCompatActivity { private Toolbar mToolbar; public static EditText mDlxInput1, mDlxInput2;//输入框 public TextView mTitle, mContent, mTime;//显示内容 DatabaseHelper mDatabaseHelper = new DatabaseHelper(this); static List<Comment> mList = new ArrayList<>(); static Comment mComment = new Comment(); MyAdapter mAdapter; ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dlx_task3_dlxmain); initViewValue(); } public void initViewValue() { findViews(); setSupportActionBar(mToolbar); setOnclicklistener(); } //数据库的初始化和按下删除的监听事件 public void setOnclicklistener() { mDatabaseHelper = new DatabaseHelper(this); mAdapter = new MyAdapter(this, mList); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mComment = mList.get(position); int positioncurrent = mComment.getId(); mDatabaseHelper.databaseDelete(positioncurrent); mList.remove(mComment); mAdapter.notifyDataSetChanged(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.dlx_task3_menu, menu); return super.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add: showDialog_Layout(DLXMainActivity.this); break; } return super.onOptionsItemSelected(item); } //对话框 private void showDialog_Layout(final Context context) { LayoutInflater inflater = LayoutInflater.from(this); final View textEntryView = inflater.inflate(R.layout.dlx_task3_dialoglayout, null); final AlertDialog.Builder builder = new AlertDialog.Builder(context); mDlxInput1 = (EditText) textEntryView.findViewById(R.id.dlx_Input1); mDlxInput2 = (EditText) textEntryView.findViewById(R.id.dlx_Input2); builder.setCancelable(false); builder.setTitle(R.string.dlx_add); builder.setView(textEntryView); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle(""); } }); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDatabaseHelper.databaseInsert(); mDatabaseHelper.databaseFind(context); mAdapter.notifyDataSetChanged(); } }); builder.show(); } public void findViews() { mToolbar = (Toolbar) findViewById(R.id.toolbar); mTitle = (TextView) findViewById(R.id.dlx_maintitle); mContent = (TextView) findViewById(R.id.dlx_maincontent); mTime = (TextView) findViewById(R.id.dlx_maintime); mListView = (ListView) findViewById(R.id.dlx_lv); } } public class MyAdapter extends BaseAdapter { public List<Comment> list; public LayoutInflater mInflater = null; Context context; DatabaseHelper mDatabaseHelper = new DatabaseHelper(context); public MyAdapter(Context context, List<Comment> list) { this.mInflater = LayoutInflater.from(context); this.context = context; this.list = list; } //ViewHolder静态类 static class ViewHolder { public TextView title; public TextView content; public TextView time; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } //获取一个在数据集中指定索引的视图来显示数据 public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; //如果缓存convertView为空,则需要创建View if (convertView == null) { holder = new ViewHolder(); //根据自定义的Item布局加载布局 convertView = mInflater.inflate(R.layout.dlx_task3_commentlayout, null); holder.title = (TextView) convertView.findViewById(R.id.dlx_maintitle); holder.content = (TextView) convertView.findViewById(R.id.dlx_maincontent); holder.time = (TextView) convertView.findViewById(R.id.dlx_maintime); //将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出Tag convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.title.setText(list.get(position).getTitle()); holder.content.setText(list.get(position).getContent()); holder.time.setText(mDatabaseHelper.getTimeShow(context, (list.get(position).getTime()))); return convertView; } } public class DatabaseHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "Comment.db"; public static final String TABLE_NAME = " comment"; public long mDatetimecurrent; Context context; public long mDatetime; // TODO: 2016/5/18 public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE" + TABLE_NAME + "(" + Comment.Commentinter.EVENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Comment.Commentinter.EVENT_TITLE + " TEXT NOT NULL, " + Comment.Commentinter.EVENT_CONTENT + " TEXT NOT NULL, " + Comment.Commentinter.EVENT_TIME + " INTEGER NOT NULL);"); } public void databaseInsert() { SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); mDatetime = System.currentTimeMillis(); //开始组装第一条数据 values.put("title", String.valueOf(DLXMainActivity.mDlxInput1.getText())); values.put("content", String.valueOf(DLXMainActivity.mDlxInput2.getText())); values.put("time", mDatetime); db.insert(TABLE_NAME, null, values);//插入第一条数据 db.close(); } /** * 删除数据库元素 * * @param */ public void databaseDelete(int positioncurrent) { SQLiteDatabase db = getWritableDatabase(); String[] args = {String.valueOf(positioncurrent)}; db.delete("comment", Comment.Commentinter.EVENT_ID + "=?", args); db.close(); } /** * 从数据库中取值并放到listview中 * @param context */ public void databaseFind(Context context) { this.context = context; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(DatabaseHelper.TABLE_NAME,new String[] {Comment.Commentinter.EVENT_ID, Comment.Commentinter.EVENT_TITLE, Comment.Commentinter.EVENT_CONTENT,Comment.Commentinter.EVENT_TIME}, null, null, null, null, null, null); //DLXMainActivity.mList.clear(); while (cursor.moveToNext()) { String title = cursor.getString(cursor.getColumnIndex(Comment.Commentinter.EVENT_TITLE)); String content = cursor.getString(cursor.getColumnIndex(Comment.Commentinter.EVENT_CONTENT)); long time = cursor.getLong(cursor.getColumnIndex(Comment.Commentinter.EVENT_TIME)); int id = cursor.getInt(cursor.getColumnIndex(Comment.Commentinter.EVENT_ID)); DLXMainActivity.mComment.setTitle(title); DLXMainActivity.mComment.setContent(content); DLXMainActivity.mComment.setTime(time); DLXMainActivity.mComment.setId(id); DLXMainActivity.mList.add(DLXMainActivity.mComment); } cursor.close(); db.close(); } public String getTimeShow(Context context, long datetime) { mDatetimecurrent = System.currentTimeMillis(); long time = mDatetimecurrent - datetime; if (time / 1000 != 0) { if (time / 60000 != 0) { if (time / 3600000 != 0) { if (time / 86400000 != 0) { return time / 86400000 + context.getString(R.string.dlx_day1); } else { return time / 3600000 + context.getString(R.string.dlx_hour); } } else { return time / 60000 + context.getString(R.string.dlx_minute); } } else { return time / 1000 + context.getString(R.string.dlx_second); } } else { return context.getString(R.string.dlx_gang); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { onCreate(db); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); } ```
安卓问题,代码如下:想显示一个listView。但是跳转到合格activity什么都不显示。
package com.coolweather.app.activity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.coolweather.app.R; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebIconDatabase.IconListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class Future extends Activity{ private ListView lvFur; private static List<Furweather> list= new ArrayList<Furweather>(); private TextView tvTest; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.furture); lvFur = (ListView) findViewById(R.id.listView1); WeatherActivity wa = new WeatherActivity(); handleWeatherResponse(wa.result); lvFur.setAdapter(adapter); } public BaseAdapter adapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub LayoutInflater inflater = LayoutInflater.from(Future.this); if(convertView==null){ convertView = inflater.inflate(R.layout.item, null); TextView tv_data = (TextView) convertView.findViewById(R.id.textView_data); TextView tv_wendu = (TextView) convertView.findViewById(R.id.textView_wendu); ImageView iv_head = (ImageView)convertView.findViewById(R.id.imageView_head); tv_data.setText(list.get(position).getCityname()+list.get(position).getDate()); tv_wendu.setText(list.get(position).getWeather()+list.get(position).getTmper()); ViewHolder vh= new ViewHolder(tv_data,tv_wendu); convertView.setTag(vh); }else{ ViewHolder vh = (ViewHolder) convertView.getTag(); vh.tv_data.setText(list.get(position).getCityname()+list.get(position).getDate()); vh.tv_wendu.setText(list.get(position).getWeather()+list.get(position).getTmper()); } return convertView; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } }; public class ViewHolder{ private TextView tv_data; private TextView tv_wendu; //private ImageView iv_head; public TextView getTv_data() { return tv_data; } public void setTv_data(TextView tv_data) { this.tv_data = tv_data; } public TextView getTv_wendu() { return tv_wendu; } public void setTv_wendu(TextView tv_wendu) { this.tv_wendu = tv_wendu; } // public ImageView getIv_head() { // return iv_head; // } // public void setIv_head(ImageView iv_head) { // this.iv_head = iv_head; // } public ViewHolder(TextView tv_data, TextView tv_wendu) { super(); this.tv_data = tv_data; this.tv_wendu = tv_wendu; //this.iv_head = iv_head; } } //解析joson数据 public static void handleWeatherResponse(String response) { try { JSONArray root = new JSONArray(response); for(int i = 0;i < root.length();i++){ JSONObject item = root.getJSONObject(i); String date = item.getString("days"); String week = item.getString("week"); String weather = item.getString("weather"); String cityname = item.getString("citynm"); String tmp = item.getString("temperature"); list.add(new Furweather(date+week,weather,cityname, tmp)); } }catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Furweather{ private String date; private String weather; private String cityname; private String tmper; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public String getCityname() { return cityname; } public void setCityname(String cityname) { this.cityname = cityname; } public String getTmper() { return tmper; } public void setTmper(String tmper) { this.tmper = tmper; } public Furweather(String date, String weather, String cityname, String tmper) { super(); this.date = date; this.weather = weather; this.cityname = cityname; this.tmper = tmper; } } 其中result是从另一个activity中传过来的joson数据。现在打开这个activity没有显示。求大神指出是哪里的问题。。
新手请教ListView 刷新问题
这是显示ListView的界面 package com.security.phonepolice.view; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.security.phonepolice.ContantValues; import com.security.phonepolice.R; import com.security.phonepolice.entity.Msgbean; import com.security.phonepolice.http.MyHttpclient; import com.security.phonepolice.util.SharedPreferenceUtil; import com.security.phonepolice.view.MessageManager.NotificationAdapter; import com.security.phonepolice.view.OAFileFragment.FileViewHolder; import com.security.phonepolice.view.widget.MyListView; import com.security.phonepolice.view.widget.MyListView.RefreshListener; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class OANotifyFragment extends Fragment implements OnClickListener, OnItemClickListener{ private View view; private ImageView mPreIv; private MyListView mNotifyLv; private LayoutInflater mInflater; private NotifyAdapter adapter = null; private TextView notifyUpload; private List<Msgbean> mList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.oa_notify_ui, container, false); mInflater = inflater; init(); initEvent(); return view; } private void init() { mNotifyLv = (MyListView) view.findViewById(R.id.oa_notify_lv); } private void initEvent() { mList = new ArrayList<Msgbean>(); adapter = new NotifyAdapter(mList); mNotifyLv.setOnItemClickListener(this); mNotifyLv.setAdapter(adapter); mNotifyLv.setOnRefreshListener(new RefreshListener() { @Override public Object refreshing() { RequestParams params = new RequestParams(); params.put("action", "Message"); String serverAdd = SharedPreferenceUtil.getServerStringSP(getActivity(), "config", "serverAdd"); MyHttpclient.post(serverAdd+ContantValues.IDCARD_URL, params, new AsyncHttpResponseHandler(){ @Override public void onSuccess( int statusCode, Header[] headers, String content) { super.onSuccess(statusCode, headers, content); if (!content.equals("failed")) { Msgbean msgBean = new Msgbean(); try { JSONObject jsonObject=new JSONObject(content); msgBean.setTitle(jsonObject.getString("TITLE")); msgBean.setContent(jsonObject.getString("CONTENT")); Log.i("-----------", jsonObject.getString("TITLE")); List<Msgbean> list = new ArrayList<Msgbean>(); list.add(msgBean); mList = list; adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } }else { Toast.makeText(getActivity(), "刷新失败", Toast.LENGTH_LONG).show(); } } @Override public void onFailure( Throwable error, String content) { Toast.makeText(getActivity(), "连接失败", Toast.LENGTH_LONG).show(); super.onFailure(error, content); } } ); return null; } @Override public void refreshed(Object obj) { Toast.makeText(getActivity(), "刷新完毕", Toast.LENGTH_LONG).show(); } @Override public void more() { Toast.makeText(getActivity(), "正在加载", Toast.LENGTH_LONG).show(); } }); } class NotifyAdapter extends BaseAdapter{ private List<Msgbean> list; public NotifyAdapter(List<Msgbean> list) { this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { NotifyViewHolder viewHolder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.oa_item, null); viewHolder = new NotifyViewHolder(); viewHolder.itemIv = (ImageView) convertView.findViewById(R.id.oa_item_iv); viewHolder.itemTitle = (TextView) convertView.findViewById(R.id.oa_item_title); viewHolder.itemContent = (TextView) convertView.findViewById(R.id.oa_item_content); convertView.setTag(viewHolder); }else { viewHolder = (NotifyViewHolder) convertView.getTag(); } viewHolder.itemIv.setImageResource(R.drawable.notification_small); viewHolder.itemTitle.setText(list.get(position).getTitle()); viewHolder.itemContent.setText(list.get(position).getContent()); return convertView; } } public static class NotifyViewHolder{ public ImageView itemIv; public TextView itemTitle; public TextView itemContent; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = null; if (position > 0) { //去服务器拉取警情的详细信息 intent = new Intent(); intent.putExtra("InfoTag", "OANotify"); intent.setClass(getActivity(), MessageDetail.class); startActivity(intent); } } } 这是在网上找到的自定义的ListView package com.security.phonepolice.view.widget; import java.text.SimpleDateFormat; import java.util.Date; import com.security.phonepolice.R; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; /** * 下拉刷新,底部更多 * */ public class MyListView extends ListView implements OnScrollListener{ private float mDownY; private float mMoveY; private int mHeaderHeight; private int mCurrentScrollState; private final static int NONE_PULL_REFRESH = 0; //正常状态 private final static int ENTER_PULL_REFRESH = 1; //进入下拉刷新状态 private final static int OVER_PULL_REFRESH = 2; //进入松手刷新状态 private final static int EXIT_PULL_REFRESH = 3; //松手后反弹和加载状态 private int mPullRefreshState = 0; //记录刷新状态 private final static int REFRESH_BACKING = 0; //反弹中 private final static int REFRESH_BACED = 1; //达到刷新界限,反弹结束后 private final static int REFRESH_RETURN = 2; //没有达到刷新界限,返回 private final static int REFRESH_DONE = 3; //加载数据结束 private LinearLayout mHeaderLinearLayout = null; private LinearLayout mFooterLinearLayout = null; private TextView mHeaderTextView = null; private TextView mHeaderUpdateText = null; private ImageView mHeaderPullDownImageView = null; private ImageView mHeaderReleaseDownImageView = null; private ProgressBar mHeaderProgressBar = null; private TextView mFooterTextView = null; private ProgressBar mFooterProgressBar = null; private SimpleDateFormat mSimpleDateFormat; private Object mRefreshObject = null; private RefreshListener mRefreshListener = null; public void setOnRefreshListener(RefreshListener refreshListener) { this.mRefreshListener = refreshListener; } public MyListView(Context context) { this(context, null); } public MyListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } void init(final Context context) { mHeaderLinearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.refresh_list_header, null); addHeaderView(mHeaderLinearLayout); mHeaderTextView = (TextView) findViewById(R.id.refresh_list_header_text); mHeaderUpdateText = (TextView) findViewById(R.id.refresh_list_header_last_update); mHeaderPullDownImageView = (ImageView) findViewById(R.id.refresh_list_header_pull_down); mHeaderReleaseDownImageView = (ImageView) findViewById(R.id.refresh_list_header_release_up); mHeaderProgressBar = (ProgressBar) findViewById(R.id.refresh_list_header_progressbar); mFooterLinearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.refresh_list_footer, null); addFooterView(mFooterLinearLayout); mFooterProgressBar = (ProgressBar) findViewById(R.id.refresh_list_footer_progressbar); mFooterTextView = (TextView) mFooterLinearLayout.findViewById(R.id.refresh_list_footer_text); mFooterLinearLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if ("加载更多".equals(mFooterTextView.getText())) { mFooterTextView.setText("正在加载"); mFooterProgressBar.setVisibility(View.VISIBLE); if (mRefreshListener != null) { mRefreshListener.more(); } } } }); setSelection(1); setOnScrollListener(this); measureView(mHeaderLinearLayout); mHeaderHeight = mHeaderLinearLayout.getMeasuredHeight(); mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm"); mHeaderUpdateText.setText("下拉刷新"+ mSimpleDateFormat.format(new Date())); } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: mDownY = ev.getY(); break; case MotionEvent.ACTION_MOVE: mMoveY = ev.getY(); if (mPullRefreshState == OVER_PULL_REFRESH) { mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), (int)((mMoveY - mDownY)/3), mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); } break; case MotionEvent.ACTION_UP: //when you action up, it will do these: //1. roll back util header topPadding is 0 //2. hide the header by setSelection(1) if (mPullRefreshState == OVER_PULL_REFRESH || mPullRefreshState == ENTER_PULL_REFRESH) { new Thread() { public void run() { Message msg; while(mHeaderLinearLayout.getPaddingTop() > 1) { msg = mHandler.obtainMessage(); msg.what = REFRESH_BACKING; mHandler.sendMessage(msg); try { sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } msg = mHandler.obtainMessage(); if (mPullRefreshState == OVER_PULL_REFRESH) { msg.what = REFRESH_BACED; } else { msg.what = REFRESH_RETURN; } mHandler.sendMessage(msg); }; }.start(); } break; } return super.onTouchEvent(ev); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && firstVisibleItem == 0 && (mHeaderLinearLayout.getBottom() >= 0 && mHeaderLinearLayout.getBottom() < mHeaderHeight)) { //进入且仅进入下拉刷新状态 if (mPullRefreshState == NONE_PULL_REFRESH) { mPullRefreshState = ENTER_PULL_REFRESH; } } else if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && firstVisibleItem == 0 && (mHeaderLinearLayout.getBottom() >= mHeaderHeight)) { //下拉达到界限,进入松手刷新状态 if (mPullRefreshState == ENTER_PULL_REFRESH || mPullRefreshState == NONE_PULL_REFRESH) { mPullRefreshState = OVER_PULL_REFRESH; mDownY = mMoveY; //为下拉1/3折扣效果记录开始位置 mHeaderTextView.setText("松手刷新");//显示松手刷新 mHeaderPullDownImageView.setVisibility(View.GONE);//隐藏"下拉刷新" mHeaderReleaseDownImageView.setVisibility(View.VISIBLE);//显示向上的箭头 } } else if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && firstVisibleItem != 0) { //不刷新了 if (mPullRefreshState == ENTER_PULL_REFRESH) { mPullRefreshState = NONE_PULL_REFRESH; } } else if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0) { //飞滑状态,不能显示出header,也不能影响正常的飞滑 //只在正常情况下才纠正位置 if (mPullRefreshState == NONE_PULL_REFRESH) { setSelection(1); } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCurrentScrollState = scrollState; } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); setSelection(1); } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case REFRESH_BACKING: mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), (int) (mHeaderLinearLayout.getPaddingTop()*0.75f), mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); break; case REFRESH_BACED: mHeaderTextView.setText("正在加载..."); mHeaderProgressBar.setVisibility(View.VISIBLE); mHeaderPullDownImageView.setVisibility(View.GONE); mHeaderReleaseDownImageView.setVisibility(View.GONE); mPullRefreshState = EXIT_PULL_REFRESH; new Thread() { public void run() { if (mRefreshListener != null) { mRefreshObject = mRefreshListener.refreshing(); } Message msg = mHandler.obtainMessage(); msg.what = REFRESH_DONE; mHandler.sendMessage(msg); }; }.start(); break; case REFRESH_RETURN: mHeaderTextView.setText("下拉刷新"); mHeaderProgressBar.setVisibility(View.INVISIBLE); mHeaderPullDownImageView.setVisibility(View.VISIBLE); mHeaderReleaseDownImageView.setVisibility(View.GONE); mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), 0, mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); mPullRefreshState = NONE_PULL_REFRESH; setSelection(1); break; case REFRESH_DONE: mHeaderTextView.setText("下拉刷新"); mHeaderProgressBar.setVisibility(View.INVISIBLE); mHeaderPullDownImageView.setVisibility(View.VISIBLE); mHeaderReleaseDownImageView.setVisibility(View.GONE); mHeaderUpdateText.setText("最新更新"+ mSimpleDateFormat.format(new Date())); mHeaderLinearLayout.setPadding(mHeaderLinearLayout.getPaddingLeft(), 0, mHeaderLinearLayout.getPaddingRight(), mHeaderLinearLayout.getPaddingBottom()); mPullRefreshState = NONE_PULL_REFRESH; setSelection(1); if (mRefreshListener != null) { mRefreshListener.refreshed(mRefreshObject); } break; default: break; } } }; public interface RefreshListener { Object refreshing(); void refreshed(Object obj); void more(); } public void finishFootView() { mFooterProgressBar.setVisibility(View.GONE); mFooterTextView.setText("更多"); } public void addFootView() { if (getFooterViewsCount() == 0) { addFooterView(mFooterLinearLayout); } } public void removeFootView() { removeFooterView(mFooterLinearLayout); } } 这是实体类: package com.security.phonepolice.entity; public class Msgbean { private int id; private String title; private String content; private String relName; private String relTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getRelName() { return relName; } public void setRelName(String relName) { this.relName = relName; } public String getRelTime() { return relTime; } public void setRelTime(String relTime) { this.relTime = relTime; } } 走到这一步法mNotifyLv.setOnRefreshListener(new RefreshListener() 就停了 为什么刷新的时候就是不走接口中的refreshing()方法。求大神指教啊!
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
JSON解析——net.sf.json.JSONObject
简介 在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,同时也易于机器解析和生成、易于理解、阅读和撰写,而且Json采用完全独立于语言的文本格式,这使得Json成为理想的数据交换语言。 JSON建构于两种结构: “名称/值”对的集合(A Collection of name/va...
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
2019年还剩1天,我从外包公司离职了
这日子过的可真快啊,2019年还剩1天,外包公司干了不到3个月,我离职了
我一个37岁的程序员朋友
周末了,人一旦没有点事情干,心里就瞎想,而且跟几个老男人坐在一起,更容易瞎想,我自己现在也是 30 岁了,也是无时无刻在担心自己的职业生涯,担心丢掉工作没有收入,担心身体机能下降,担心突...
计算机网络的核心概念
这是《计算机网络》系列文章的第二篇文章 我们第一篇文章讲述了计算机网络的基本概念,互联网的基本名词,什么是协议以及几种接入网以及网络传输的物理媒体,那么本篇文章我们来探讨一下网络核心、交换网络、时延、丢包、吞吐量以及计算机网络的协议层次和网络攻击。 网络核心 网络的核心是由因特网端系统和链路构成的网状网络,下面这幅图正确的表达了这一点 那么在不同的 ISP 和本地以及家庭网络是如何交换信息的呢?...
python自动下载图片
近日闲来无事,总有一种无形的力量萦绕在朕身边,让朕精神涣散,昏昏欲睡。 可是,像朕这么有职业操守的社畜怎么能在上班期间睡瞌睡呢,我不禁陷入了沉思。。。。 突然旁边的IOS同事问:‘嘿,兄弟,我发现一个网站的图片很有意思啊,能不能帮我保存下来提升我的开发灵感?’ 作为一个坚强的社畜怎么能说自己不行呢,当时朕就不假思索的答应:‘oh, It’s simple. Wait for me for a ...
一名大专同学的四个问题
【前言】   收到一封来信,赶上各种事情拖了几日,利用今天要放下工作的时机,做个回复。   2020年到了,就以这一封信,作为开年标志吧。 【正文】   您好,我是一名现在有很多困惑的大二学生。有一些问题想要向您请教。   先说一下我的基本情况,高考失利,不想复读,来到广州一所大专读计算机应用技术专业。学校是偏艺术类的,计算机专业没有实验室更不用说工作室了。而且学校的学风也不好。但我很想在计算机领...
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
达摩院十大科技趋势发布:2020 非同小可!
【CSDN编者按】1月2日,阿里巴巴发布《达摩院2020十大科技趋势》,十大科技趋势分别是:人工智能从感知智能向认知智能演进;计算存储一体化突破AI算力瓶颈;工业互联网的超融合;机器间大规模协作成为可能;模块化降低芯片设计门槛;规模化生产级区块链应用将走入大众;量子计算进入攻坚期;新材料推动半导体器件革新;保护数据隐私的AI技术将加速落地;云成为IT技术创新的中心 。 新的画卷,正在徐徐展开。...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
程序员如何通过造轮子走向人生巅峰?
前言:你所做的事情,也许暂时看不到成果。但不要灰心,你不是没有成长,而是在扎根。 程序员圈经常流行的一句话:“不要重复造轮子”。在计算机领域,我们将封装好的组件、库,叫做轮子。因为它可以拿来直接用,直接塞进我们的项目中,就能实现对应的功能。 有些同学会问,人家都已经做好了,你再来重新弄一遍,有什么意义?这不是在浪费时间吗。 殊不知,造轮子是一种学习方式,能快速进步,造得好,是自己超强能力的表...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试一个ArrayList我都能跟面试官扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
立即提问