handler里面的listview不刷新

做一个聊天工具,开一个线程接收消息,在handler里面不刷新listview,第一次打开页面时是可以刷新,但是再此打开不刷新页面。

1个回答

这种问题需要结合代码来看

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
adapter.notifyDataSetChanged()正常执行,可是ListView不刷新

Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { if(msg == null)return ; switch (msg.what) { case 1:// 收到聊天信息 ChatMsg chatMsg = new ChatMsg(); adapter.getList().add(chatMsg); adapter.notifyDataSetChanged(); break; default: break; } }; }; 当第一次,登陆到这个类所在的actitvity之时,这个Handlers可以正常工作,adapter.notifyDataSetChanged()也能正常工作。列表会被刷新! 但是,当跳到另一个activity,再跳回到这个类所在的activity之后。虽然Handlers可以正常工作,但adapter.notifyDataSetChanged()执行,列表不会被刷新。

ListView自动刷新多个Item

![图片说明](https://img-ask.csdn.net/upload/201601/04/1451909397_404376.png)ListView自定刷新Item中有改变的数据,并将此项 item背景闪烁一下。 ``` package master.modle.masterfinance.adapter; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; import java.util.Objects; import master.modle.masterfinance.R; import master.modle.masterfinance.model.biz.MarketList; import master.modle.masterfinance.utils.LogUtils; import master.modle.masterfinance.utils.UIUtils; import master.modle.masterfinance.utils.ViewHolderUtils; /** * * @action: * @author: YangShao * @date: 2016/1/4 @time: 10:46 */ public class MarkItmeAapter extends BaseAdapter{ List<MarketList> listEntitys; ListView listView; public MarkItmeAapter(List<MarketList> listEntitys,ListView listView){ this.listEntitys=listEntitys; this.listView=listView; } @Override public int getCount() { return listEntitys.size(); } @Override public Object getItem(int i) { return listEntitys.get(i); } @Override public long getItemId(int i) { return i; } public static ViewHolder mviewHolder; @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder; if (view==null){ view = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.item_market, viewGroup, false); holder = new ViewHolder(); holder.tx_name = (TextView) view.findViewById(R.id.id_mr_name); holder.tx_new = (TextView) view.findViewById(R.id.id_mr_new); holder.tv_range = (TextView) view.findViewById(R.id.id_mr_range); view.setTag(holder); }else{ holder = (ViewHolder) view.getTag(); } setData(holder,i); return view; } private static class ViewHolder { private TextView tx_name; private TextView tx_new; private TextView tv_range; private MarketList market; } public List<MarketList> getListViewData(){ return listEntitys; } public void setListEntitys(List<MarketList> listEntitys) { this.listEntitys = listEntitys; } /** * 设置viewHolder的数据 * @param holder * @param itemIndex */ private void setData(ViewHolder holder, int itemIndex) { holder.tx_name.setText(listEntitys.get(itemIndex).getName()); holder.tx_new.setText(listEntitys.get(itemIndex).getLatestpri() + ""); holder.tv_range.setText(listEntitys.get(itemIndex).getMarkup() + ""); holder.market=listEntitys.get(itemIndex); //int markup=Integer.valueOf(String.valueOf(listEntitys.get(i).getMarkup())); // int markup = Integer.parseInt(new java.text.DecimalFormat("0").format(listEntitys.get(i).getMarkup())); int markup = (int)listEntitys.get(itemIndex).getMarkup(); if (markup>=0){ holder.tv_range.setTextColor(Color.RED); holder.tx_new.setTextColor(Color.RED); }else{ holder.tv_range.setTextColor(Color.GREEN); holder.tx_new.setTextColor(Color.GREEN); } } } ``` ``` package master.modle.masterfinance.frg; 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.ListView; import java.util.List; import java.util.Timer; import java.util.TimerTask; import butterknife.Bind; import butterknife.ButterKnife; import master.modle.masterfinance.R; import master.modle.masterfinance.adapter.MarkItmeAapter; import master.modle.masterfinance.adapter.PagerItmeAapter; import master.modle.masterfinance.base.BaseApplication; import master.modle.masterfinance.base.BaseFragment; import master.modle.masterfinance.model.biz.InformatTitle; import master.modle.masterfinance.model.biz.MarketList; import master.modle.masterfinance.mpresenter.IMarketListPresnter; import master.modle.masterfinance.mview.IMarketView; import master.modle.masterfinance.utils.LogUtils; import master.modle.masterfinance.utils.ToastUtils; /** * @action: * @author: YangShao VapagerFragment * @date: 2015/12/24 @time: 16:22 */ public class MarkItmeFrag extends BaseFragment implements IMarketView { @Bind(R.id.id_mr_list) ListView idMrList; private View rootView; InformatTitle categoryEntitie; //标签内容 IMarketListPresnter iMarketListPresnter = new IMarketListPresnter(this); private String actName; public static MarkItmeFrag informationItmeFrag; private PagerItmeAapter itmeFragAapter; Handler handler = new Handler(){ public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what == 1){ iMarketListPresnter.getMarkList(String.valueOf(categoryEntitie.getId())); } } }; private Timer timer = new Timer(true); //任务 private TimerTask task = new TimerTask() { public void run() { Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } }; public static MarkItmeFrag getFragment(InformatTitle categoryEntitie, String mactName) { LogUtils.e("InformationItmeFrag getFragment" + mactName); informationItmeFrag = new MarkItmeFrag(); informationItmeFrag.categoryEntitie = categoryEntitie; informationItmeFrag.actName = mactName; return informationItmeFrag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = getRootView(); ButterKnife.bind(this, rootView); initView(); return rootView; } public void initView() { //启动定时器 timer.schedule(task, 0, 10 * 1000); // iMarketListPresnter.getMarkList(String.valueOf(categoryEntitie.getId())); } public View getRootView() { rootView = LayoutInflater.from(getActivity()).inflate( R.layout.frag_mark_home, null); return rootView; } /* 摧毁视图 */ @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); timer.cancel(); timer=null; } /* 摧毁该Fragment,一般是FragmentActivity 被摧毁的时候伴随着摧毁 */ @Override public void onDestroy() { super.onDestroy(); BaseApplication.requestQueue.cancelAll(this); if (timer!=null){ timer.cancel(); timer=null; } } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } MarkItmeAapter markItmeAapter; @Override public void setInfomatList(final List<MarketList> listEntitys) { if (listEntitys.size()==0){ return; }if (markItmeAapter==null){ markItmeAapter=new MarkItmeAapter(listEntitys,idMrList); idMrList.setAdapter(markItmeAapter); }else { setUpdateListView(listEntitys); } } public void setUpdateListView(List<MarketList> mlistEntitys){ //得到原有数据 List<MarketList> liste = markItmeAapter.getListViewData(); for (int i=0;i<liste.size();i++){ double markup1=liste.get(i).getLatestpri(); double markup2=mlistEntitys.get(i).getLatestpri(); if (!equal(markup1,markup2)){ ToastUtils.showToastReal(markup2 + ""); LogUtils.e("发生改变的数据id" + i); } } markItmeAapter.setListEntitys(mlistEntitys); markItmeAapter.notifyDataSetChanged(); } boolean equal(double num1,double num2) { if((num1-num2>-0.000001)&&(num1-num2)<0.000001) return true; else return false; } @Override public void noData() { } } ``` ``` package master.modle.masterfinance.model.biz; public class MarketList { private int id; private String name; private double latestpri; private double markup; public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setLatestpri(double latestpri) { this.latestpri = latestpri; } public void setMarkup(double markup) { this.markup = markup; } public int getId() { return id; } public String getName() { return name; } public double getLatestpri() { return latestpri; } public double getMarkup() { return markup; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MarketList)) return false; MarketList that = (MarketList) o; return getId() == that.getId(); } @Override public int hashCode() { return getId(); } } ```

做了一个listview的下拉刷新和底部自动加载,但我做完之后项目能运行,但就是始终加载不出来,求教

底下是代码 ``` package caifu.life.ZHSQ.main; import java.util.ArrayList; import java.util.HashMap; 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.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import caifu.life.ZHSQ.R; import caifu.life.ZHSQ.sqShouYeListView.AutoListView; import caifu.life.ZHSQ.sqShouYeListView.AutoListView.OnLoadListener; import caifu.life.ZHSQ.sqShouYeListView.AutoListView.OnRefreshListener; public class ShouYeActivity extends Activity implements OnRefreshListener, OnLoadListener { // 获取listview private AutoListView syListView; private listViewAdapter adapter; private ArrayList<HashMap<String, Object>> item; // 传递消息处理刷新数据 private Handler handler = new Handler(){ public void handleMessage(Message msg) { @SuppressWarnings("unchecked") ArrayList<HashMap<String, Object>> result = (ArrayList<HashMap<String, Object>>) msg.obj; switch (msg.what) { case AutoListView.REFRESH:// 刷新操作 syListView.onRefreshComplete(); item.clear(); item.addAll(result); break; case AutoListView.LOAD:// 加载 syListView.onLoadComplete(); item.addAll(result); break; } syListView.setResultSize(result.size()); adapter.notifyDataSetChanged(); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sq_message); // 获取listview syListView = (AutoListView) findViewById(R.id.shouyeListView); // 配置适配器 adapter = new listViewAdapter(this, item); // 设置适配 syListView.setAdapter(adapter); // 追加刷新与加载监听 syListView.setOnRefreshListener(this); syListView.setOnLoadListener(this); initData(); // 一个动态数组 getDate(); } // 定义一个得到数据的方法 private static ArrayList<HashMap<String, Object>> getDate() { ArrayList<HashMap<String, Object>> item = new ArrayList<HashMap<String, Object>>(); for (int i = 1; i < 4; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("touXiang", R.drawable.sylvtouxiang); map.put("yongHuMing", "第" + i + "用户"); map.put("neiRong", "第" + i + "内容"); map.put("sylv_image1", R.drawable.sylvimage1); map.put("sylv_image2", R.drawable.sylvimage2); map.put("sylv_image3", R.drawable.sylvimage3); item.add(map); } return item; } private void initData() { loadData(AutoListView.REFRESH); } private void loadData(final int what) { // 起线程获取数据 new Thread(new Runnable() { public void run() { try { Thread.sleep(700); } catch (InterruptedException e) { e.printStackTrace(); Message msg = handler.obtainMessage(); msg.what = what; msg.obj = getDate(); handler.sendMessage(msg); } } }).start(); } public void onLoad() { loadData(AutoListView.LOAD); } public void onRefresh() { loadData(AutoListView.REFRESH); } // 适配器 private class listViewAdapter extends BaseAdapter { private ViewHolder holder; private Context context; private ArrayList<HashMap<String, Object>> item; public listViewAdapter(Context context, ArrayList<HashMap<String, Object>> item) { this.item = item; this.context = context; } public int getCount() { return getDate().size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate( R.layout.activity_sq_message_item, null); // 得到各控件对象 holder.touXiang = (ImageView) convertView .findViewById(R.id.touXiang); holder.yongHuMing = (TextView) convertView .findViewById(R.id.yongHuMing); holder.neiRong = (TextView) convertView .findViewById(R.id.neiRong); holder.sylv_image1 = (ImageView) convertView .findViewById(R.id.sylv_image1); holder.sylv_image2 = (ImageView) convertView .findViewById(R.id.sylv_image2); holder.sylv_image3 = (ImageView) convertView .findViewById(R.id.sylv_image3); // 绑定viewHolder对象 convertView.setTag(holder); } else { // 取出ViewHolder对象 holder = (ViewHolder) convertView.getTag(); } holder.yongHuMing.setText(getDate().get(position).get("yongHuMing") .toString()); holder.neiRong.setText(getDate().get(position).get("neiRong") .toString()); return convertView; } public final class ViewHolder { public ImageView touXiang; public TextView yongHuMing; public TextView neiRong; public ImageView sylv_image1; public ImageView sylv_image2; public ImageView sylv_image3; } } /** 测试数据 public List<String> getData() { List<String> result = new ArrayList<String>(); Random random = new Random(); for (int i = 0; i < 10; i++) { long l = random.nextInt(10000); result.add("当前条目的ID:" + l); } return result; }*/ } ```

关于listview刷新单个item的一个问题

在BaseAdapter中 public void updataView(int position, ListView listView) { int visibleFirstPosi = listView.getFirstVisiblePosition(); int visibleLastPosi = listView.getLastVisiblePosition(); if (position >= visibleFirstPosi && position <= visibleLastPosi) { View view = listView.getChildAt(position - visibleFirstPosi); ViewHolder holder = (ViewHolder) view.getTag(); holder.progressView.setProgress(MainActivity.progress[0]); } } 我想做的是listview的每个item中都有一个进度条 点击item启动下载 刷新单个item用的上面一种方法 点击item记录一个Index = position 然后在接收progress进度值的handler里面调用这个 adapter.updataView(Index, listView); 但是如果我同时点击了多个Item下载多个不同文件,如何能让两个item里的progressbar都同时刷新呢?

android ListView 做下拉刷新 下拉跳到第一项怎么解决

listView.setonRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { Log.e(TAG, "---下拉刷新---"); new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { try { mylineslistlist.clear(); mylinesorderlist.clear(); list.clear(); getMylines(0); } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(Void result) { adapter.notifyDataSetChanged(); listView.onRefreshComplete(); } }.execute(); } }); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(final AbsListView view, int scrollState) { listView.onScrollStateChanged(view, scrollState); // 数据为空--不用继续下面代码了 if (list.size() == 0) return; // 判断是否滚动到底部 boolean scrollEnd = false; try { if (view.getPositionForView(loadingLayout) == view .getLastVisiblePosition()) scrollEnd = true; } catch (Exception e) { scrollEnd = false; } if (scrollEnd) { // 如果是自动加载,可以在这里放置异步加载数据的代码 Log.e("LOADMORE", "loading..."); if (currentPage < pageNum) { // Log.e(TAG, "---currentPage is " + currentPage); currentPage++; // Log.e(TAG, "---currentPage is " + currentPage); handler.postDelayed(new Runnable() { @Override public void run() { // Log.d(TAG, "---loadData page is" + // currentPage); getMylines(currentPage); // listView.setSelection(view // .getLastVisiblePosition() - 1); // 设置选中项 // setLoadView("加载更多"); //恢复按钮文字 } }, 1000); } else { listView.removeFooterView(loadingLayout); } } }

如何在不复制数据的情况下自动刷新(添加/更新)listview项目?

<div class="post-text" itemprop="text"> <p>i made a simple code to retrieve some data from mysql database and put them into android listview everything works fine but the old items stays on the list view and it adds the new items(data is duplicated), below is php code :</p> <pre><code>$sql = "SELECT * FROM persons"; $res = mysqli_query($con,$sql); $result = array(); while($row = mysqli_fetch_array($res)){ array_push($result, array('id'=&gt;$row[0], 'name'=&gt;$row[1], 'address'=&gt;$row[2] )); } echo json_encode(array("result"=&gt;$result)); mysqli_close($con); </code></pre> <p>and here the android code :</p> <pre><code> public class FetchData extends Activity{ String myJSON; private static final String TAG_RESULTS="result"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_ADD ="address"; JSONArray peoples = null; ArrayList&lt;HashMap&lt;String, String&gt;&gt; personList; ListView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); list = (ListView) findViewById(R.id.listView); personList = new ArrayList&lt;HashMap&lt;String,String&gt;&gt;(); getData(); final Handler handler = new Handler(); handler.postDelayed( new Runnable() { @Override public void run() { refreshData(); handler.postDelayed( this, 2 * 100 ); } }, 2 * 100 ); } public void refreshData(){ } public void getData(){ class GetDataJSON extends AsyncTask&lt;String, Void, String&gt;{ @Override protected String doInBackground(String... params) { DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost("http://192.168.1.4/get-data.php"); // Depends on your web service httppost.setHeader("Content-type", "application/json"); InputStream inputStream = null; String result = null; try { HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + " "); } result = sb.toString(); } catch (Exception e) { // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} } return result; } @Override protected void onPostExecute(String result){ myJSON=result; showdata(); } } GetDataJSON g = new GetDataJSON(); g.execute(); } protected void showdata(){ try { JSONObject jsonObj = new JSONObject(myJSON); peoples = jsonObj.getJSONArray(TAG_RESULTS); for(int i=0;i&lt;peoples.length();i++){ JSONObject c = peoples.getJSONObject(i); String id = c.getString(TAG_ID); String name = c.getString(TAG_NAME); String address = c.getString(TAG_ADD); HashMap&lt;String,String&gt; persons = new HashMap&lt;String,String&gt;(); persons.put(TAG_ID,id); persons.put(TAG_NAME,name); persons.put(TAG_ADD,address); personList.add(persons); } ListAdapter adapter = new SimpleAdapter( FetchData.this, personList, R.layout.list_item, new String[]{TAG_ID,TAG_NAME,TAG_ADD}, new int[]{R.id.id, R.id.name, R.id.address} ); list.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } } } </code></pre> <p>i would like to update automatically specific listview item if mysql database data changed for that specific item and add new items without duplicating</p> </div>

新手请教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()方法。求大神指教啊!

Handler里面不能更新界面 包括List和Button的显示 求大神解答

首先设置的是Activity的OnCrate方法 public class CreateActivity extends Activity{ protected static CharSequence text = "Waiting Range"; public static MobilocMaster mobilocMaster = new MobilocMaster(); public static MobilocAnchor mobilocAnchor = new MobilocAnchor(); public static LoopThread lt; Button mButton; static boolean started = false; Handler handler; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.create); ini(!started); mButton = (Button) findViewById(R.id.button); mButton.setText(text); mButton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent1 = new Intent(CreateActivity.this,CoordinateActivity.class); startActivity(intent1); } }); 然后是处理函数和初始化 public void handleMessage(Message msg) { switch (msg.what) { case 1: text = "Waiting Range"; mButton.setEnabled(false); mButton.setText(text); data.clear(); Hashtable<String,myAnchorInfo> temp = (Hashtable<String,myAnchorInfo>)msg.obj; Enumeration t = temp.keys(); while(t.hasMoreElements()) { String t1 = (String)t.nextElement(); myAnchorInfo myi = (myAnchorInfo)temp.get(t1); map = new HashMap<String, String>(); map.clear(); map.put("name", myi.name); map.put("ip", myi.ip); map.put("range", myi.range); data.add(map); } adapter.notifyDataSetChanged(); System.out.println(data.toString()+"Data的数据[test]"); System.out.println("Handler更新界面--->Waiting Range[test]"); break; case 2: text = "Look Position"; mButton.setEnabled(true); mButton.setText(text); data.clear(); Hashtable<String,myAnchorInfo> temp1 = (Hashtable<String,myAnchorInfo>)msg.obj; System.out.println(msg.obj.toString()+"Message的信息[test]"); Enumeration t2 = temp1.keys(); while(t2.hasMoreElements()) { String t3 = (String)t2.nextElement(); myAnchorInfo myi = (myAnchorInfo)temp1.get(t3); map = new HashMap<String, String>(); map.clear(); map.put("name", myi.name); map.put("ip", myi.ip); map.put("range", myi.range); data.add(map); } adapter.notifyDataSetChanged(); System.out.println(data.toString()+"Data的数据[test]"); System.out.println("Handler更新界面--->Look Position[test]"); break; } } }; } void ini(Boolean flag){ if(flag) { Intent intent = getIntent(); String myname = intent.getStringExtra("myName"); rangingSettings(); mobilocAnchor.setAnchorName(myname); mobilocMaster.start(); mobilocAnchor.start(); ListView lv = (ListView) findViewById(R.id.list1); String[] from = new String[]{"name" , "ip", "range"}; int[] to = new int[]{R.id.person_name , R.id.person_ip , R.id.person_range}; adapter = new SimpleAdapter(this, data,R.layout.child_create, from,to); lv.setAdapter(adapter); started = true; lt = new LoopThread(); lt.start(); } } 最后是子线程来更新数据 class LoopThread extends Thread{ Boolean flag = true; public void run() { while(true) { try { Thread.sleep(3000); tempAnchor.clear(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(true){ try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(mobilocAnchor.getMyAddress()!= null){ myAnchor = new AnchorInfo(mobilocAnchor.getMyAddress()); break; } } Enumeration akey = MobilocMaster.anchorTable.keys(); Enumeration rkey = MobilocMaster.rangingTable.keys(); while(akey.hasMoreElements()) { AnchorNetInfo key1 = (AnchorNetInfo)akey.nextElement(); AnchorInfo ai = (AnchorInfo)MobilocMaster.anchorTable.get(key1); if(myAnchor.getHostString().contains(ai.getHostString())) continue; tempInfo.setAnchorInfo(ai.getName(), ai.getIP()); myAnchorPair = new AnchorPair(myAnchor.getHostString(),ai.getHostString()); if(LocationAnchor.readyForRanging){ tempInfo.setRange(MobilocAnchor.rangingTable.get(myAnchorPair).getDistance()); tempAnchor.put(ai.getName(),tempInfo); flag = false; } else{ tempInfo.setRange("Ranging"); tempAnchor.put(ai.getName(),tempInfo); } } if(flag){ Message message = new Message(); message.what = 1; message.obj = tempAnchor; System.out.println(message.obj.toString()+"主线程Message信息[test]"); handler.sendMessage(message); } else { Message message1 = new Message(); message1.what = 2; message1.obj = tempAnchor; handler.sendMessage(message1); System.out.println(message1.obj.toString()+"主线程Message1信息[test]"); flag = true; } } } } class myAnchorInfo{ String name; String range; String ip; public void setAnchorInfo(String name,String ip){ this.name = name; this.ip = ip; } public void setRange(float ft){ this.range = (float)(Math.round(ft*100))/100+""; } public void setRange(String range){ this.range = range; } }

删除后android刷新Listview

在我的item删除后我想要刷新我的listview。但是好像不起作用,我是少了什么东西了么?我用了`listAdapter.notifyDataSetChanged();`也不起作用。有没有人能帮帮我?谢谢。 @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().setContentView(R.layout.dl_listview); View empty = getActivity().findViewById(R.id.empty); DLListView = (ListView) getActivity().findViewById(R.id.DLListView); DLListView.setEmptyView(empty); if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { Toast.makeText(getActivity(), "Error! No SDCARD Found!", Toast.LENGTH_LONG).show(); } else { File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "St"); directory.mkdirs(); } DLListView = (ListView) getActivity().findViewById(R.id.DLListView); myList = new ArrayList<String>(); File sdCard = Environment.getExternalStorageDirectory(); file = new File(sdCard.getAbsolutePath() + "/St/"); File list[] = file.listFiles(); for (int i = 0; i < list.length; i++) { String fileName = list[i].getName(); fileName = fileName.replace(".txt", ""); myList.add(fileName); } listAdapter = new ArrayAdapter<String>(getActivity(), R.layout.simplerow, myList); DLListView.setAdapter(listAdapter); DLListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub String textToPass = myList.get(position); Intent i = new Intent(getActivity(), ViewActivity.class); textToPass = textToPass.replace(textToPass + "", textToPass + ".txt"); i.putExtra("textToPass", textToPass); startActivity(i); } }); DLListView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub registerForContextMenu(DLListView); return false; } }); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; String name = ((TextView) info.targetView).getText().toString(); menu.setHeaderTitle(name); menu.add(0, v.getId(), 0, "Delete"); } @Override public boolean onContextItemSelected(MenuItem item) { deletefunc(item.getItemId()); return true; } public void deletefunc(int id) { String filenamec = fileName1; filenamec = filenamec.replace(filenamec + "", filenamec + ".txt"); File folder = Environment.getExternalStorageDirectory(); String fileName = folder.getPath() + "/St/" + filenamec; File myFile = new File(fileName); if (myFile.exists()) myFile.delete(); Toast.makeText(getActivity(), fileName1+" Deleted", Toast.LENGTH_SHORT) .show(); listAdapter.remove(listAdapter.getItem(id)); } LogCat : 12-26 11:57:27.334: E/AndroidRuntime(5576): FATAL EXCEPTION: main 12-26 11:57:27.334: E/AndroidRuntime(5576): java.lang.IndexOutOfBoundsException: Invalid index 2131034154, size is 1 12-26 11:57:27.334: E/AndroidRuntime(5576): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) 12-26 11:57:27.334: E/AndroidRuntime(5576): at java.util.ArrayList.get(ArrayList.java:304) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:337) 12-26 11:57:27.334: E/AndroidRuntime(5576): at free.st.app.MyDownloads.deletefunc(MyDownloads.java:137) 12-26 11:57:27.334: E/AndroidRuntime(5576): at free.st.app.MyDownloads.onContextItemSelected(MyDownloads.java:118) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.support.v4.app.FragmentManagerImpl.dispatchContextItemSelected(FragmentManager.java:1933) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:360) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.actionbarsherlock.app.SherlockFragmentActivity.onMenuItemSelected(SherlockFragmentActivity.java:200) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3691) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:929) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.widget.AdapterView.performItemClick(AdapterView.java:292) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.widget.AbsListView.performItemClick(AbsListView.java:1185) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2713) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.widget.AbsListView$1.run(AbsListView.java:3468) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.os.Handler.handleCallback(Handler.java:605) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.os.Handler.dispatchMessage(Handler.java:92) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.os.Looper.loop(Looper.java:137) 12-26 11:57:27.334: E/AndroidRuntime(5576): at android.app.ActivityThread.main(ActivityThread.java:4512) 12-26 11:57:27.334: E/AndroidRuntime(5576): at java.lang.reflect.Method.invokeNative(Native Method) 12-26 11:57:27.334: E/AndroidRuntime(5576): at java.lang.reflect.Method.invoke(Method.java:511) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982) 12-26 11:57:27.334: E/AndroidRuntime(5576): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749) 12-26 11:57:27.334: E/AndroidRuntime(5576): at dalvik.system.NativeStart.main(Native Method)

android给listview添加下拉刷新崩溃

logcat: 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi W/dalvikvm﹕ VFY: unable to resolve virtual method 12221: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi W/dalvikvm﹕ VFY: unable to resolve virtual method 9785: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi W/dalvikvm﹕ VFY: unable to resolve virtual method 396: Landroid/content/res/TypedArray;.getChangingConfigurations ()I 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi W/dalvikvm﹕ VFY: unable to resolve virtual method 418: Landroid/content/res/TypedArray;.getType (I)I 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi W/dalvikvm﹕ VFY: unable to resolve virtual method 359: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable; 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi W/dalvikvm﹕ VFY: unable to resolve virtual method 361: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable; 10-09 15:17:36.549 15984-15984/com.example.jkd.fchangshi D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 10-09 15:17:36.599 15984-15984/com.example.jkd.fchangshi I/dalvikvm-heap﹕ Grow heap (frag case) to 26.484MB for 9000016-byte allocation 10-09 15:17:36.629 15984-15984/com.example.jkd.fchangshi D/AndroidRuntime﹕ Shutting down VM 10-09 15:17:36.629 15984-15984/com.example.jkd.fchangshi W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415e8d58) 10-09 15:17:36.629 15984-15984/com.example.jkd.fchangshi E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.jkd.fchangshi, PID: 15984 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jkd.fchangshi/com.example.jkd.fchangshi.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5049) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.example.jkd.fchangshi.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:295) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171) at android.app.Activity.performStart(Activity.java:5303) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)             at android.app.ActivityThread.access$800(ActivityThread.java:139)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)             at android.os.Handler.dispatchMessage(Handler.java:102)             at android.os.Looper.loop(Looper.java:136)             at android.app.ActivityThread.main(ActivityThread.java:5049)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:515)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)             at dalvik.system.NativeStart.main(Native Method) 10-09 15:17:36.759 15984-16013/com.example.jkd.fchangshi I/System.out﹕ 获取成功 10-09 15:17:36.829 15984-16013/com.example.jkd.fchangshi I/System.out﹕ 转字符串成功

关于ListView 刷新的问题

package com.box.page; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.android.volley.RequestQueue; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.box.datamodel.CartGood; import com.box.sjfood_v_1_0.MainActivity; import com.box.sjfood_v_1_0.R; import com.box.tools.UrlString; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.LinearGradient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; 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.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; public class ShoppingCart extends Fragment{ private boolean hasitem = false;//进入界面时,接受服务器数据,表示购物车内是否有物品 private Button goForBuybutton;//去逛逛 private Button calculate;//结算按钮 private RequestQueue mQueue = null; private boolean isLogin;//是否已经登陆 private String phoneString;//用户手机号 private SharedPreferences sp; private Handler mHandler; private ArrayList<CartGood> cartGoods; private RelativeLayout shopping_somethingLayout; private LinearLayout shopping_nothingLayout; private ListView listView;//购物车listview private Button allSelectImageView;//全选图标 private TextView totalPriceTextView;//总价 private ShoppingCartAdapter myAdapter; private float totalPrice = 0;//记录总价 private ArrayList<Boolean> isselected = new ArrayList<Boolean>(); public View onCreateView( final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub //获取用户信息 getUserInfo(); View view = inflater.inflate(R.layout.shoppingcart, container,false); //获取页面 initView(view); //获取用户的订单信息 mQueue = Volley.newRequestQueue(getActivity()); GetOrderList(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(msg.obj.toString().equals("-1")) { isLogin = false; hasitem = false; Log.i("isLogin1", String.valueOf(isLogin)); Log.i("hasitem1", String.valueOf(hasitem)); setAllGone(); shopping_nothingLayout.setVisibility(View.VISIBLE); } else { JSONObject jsonObject= new JSONObject(); jsonObject = (JSONObject) msg.obj; cartGoods = (ArrayList<CartGood>) JSONArray.parseArray(jsonObject.getJSONArray("orderList").toString(), CartGood.class); isLogin = true; hasitem = true; Log.i("isLogin1", String.valueOf(isLogin)); Log.i("hasitem1", String.valueOf(hasitem)); setAllGone(); shopping_somethingLayout.setVisibility(View.VISIBLE); dataToListView(); } } /* * 把cartgoods中的数据传到适配器中 */ private void dataToListView() { // TODO Auto-generated method stub for(int i = 0;i<cartGoods.size();i++) { Log.i("cartGoods",cartGoods.get(i).getName()+ i); isselected.add(false); } myAdapter = new ShoppingCartAdapter(getActivity(), cartGoods,isselected); listView.setAdapter(myAdapter); myAdapter.notifyDataSetChanged(); } private void setAllGone() { // TODO Auto-generated method stub shopping_somethingLayout.setVisibility(View.GONE); shopping_nothingLayout.setVisibility(View.GONE); } }; return view; } private void initView(View view) { // TODO Auto-generated method stub shopping_nothingLayout = (LinearLayout) view.findViewById(R.id.shoppingcart_nothing_layout); shopping_somethingLayout = (RelativeLayout) view.findViewById(R.id.shoppingcart_something_layout); initNothingView(view); initSomethingView(view); } //初始化有item时的界面 private void initSomethingView(View view) { // TODO Auto-generated method stub calculate = (Button) view.findViewById (R.id.shoppingcart_something_calcu);//结算按钮 allSelectImageView = (Button) view.findViewById (R.id.shoppingcart_allselect);//全选 totalPriceTextView = (TextView)view.findViewById (R.id.shoppingcart_totalprice);//总价 listView = (ListView)view.findViewById(R.id.shoppingcart_listview); allSelectImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub isselected.add(true); if (allSelectImageView.isSelected()) { for(int i = 0;i<isselected.size();i++) { isselected.set(i, false); } allSelectImageView.setSelected(false); } else { for(int i = 0;i<isselected.size();i++) { isselected.set(i, true); } allSelectImageView.setSelected(true); } CalculatePrice(); myAdapter.notifyDataSetChanged(); } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub final int mposition = position; final CartGood cartGood = cartGoods.get(position); final Button button = (Button) view.findViewById(R.id.shoppingcart_item_select); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (isselected.get(mposition)) { allSelectImageView.setSelected(false); } isselected.set(mposition, !isselected.get(mposition)); Log.i("isselected", String.valueOf(isselected.get(mposition))); //Log.i("isselectedadapter",String.valueOf(myAdapter.getList().get(mposition))); myAdapter.notifyDataSetChanged(); CalculatePrice(); } }); } }); } /* * 获取用户存储在手机上的ID * 若未登录则Id置为-1,另外处理 */ private void CalculatePrice() { // TODO Auto-generated method stub totalPrice = 0; for(int i = 0;i<isselected.size();i++) { if(isselected.get(i)) { if(cartGoods.get(i).getIsDiscount() == 1) totalPrice = totalPrice+cartGoods.get(i).getDiscountPrice(); else { totalPrice = totalPrice + cartGoods.get(i).getPrice(); } } } totalPriceTextView.setText("¥ "+String.valueOf(totalPrice)); } private void getUserInfo() { // TODO Auto-generated method stub sp = getActivity().getSharedPreferences("login", 0); isLogin = sp.getBoolean("Login", false); phoneString = sp.getString("phone", "-1"); if(!isLogin) { hasitem = false; phoneString = "-1"; } } /* * 获取用户订单信息 */ private void GetOrderList() { // TODO Auto-generated method stub StringRequest stringRequest = new StringRequest(Method.POST, UrlString.GetOrderString, new Response.Listener<String>() { @Override public void onResponse(String response) { // TODO Auto-generated method stub Log.i("用户订单信息", response); JSONObject jsonObject =JSONObject.parseObject(response); String statusString = jsonObject.getString("status"); if(statusString.equals("success")) { Message message = mHandler.obtainMessage(); if(!jsonObject.getString("message").equals("获取购物车订单成功")) { message.obj = -1; } else { message.obj = jsonObject; } mHandler.sendMessage(message); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub } }) { protected Map<String, String> getParams(){ Map<String, String> params = new HashMap<String, String>(); params.put("phoneId", phoneString); return params; } }; mQueue.add(stringRequest); } private void initNothingView(View view) { // TODO Auto-generated method stub goForBuybutton = (Button)view.findViewById(R.id.shoppingcart_goforbuy); goForBuybutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(getActivity(),MainActivity.class); startActivity(intent); getActivity().finish(); } }); } } ``` ``` 为什么listview不会自动刷新? 是不是只要adapter绑定的数据源发生变化了,调用notifydatasetonchanged就会刷新? notifydatasetonchanged()调用有什么条件?

向listview中添加新数据,可是每次添加都会把旧的数据覆盖,我看了好多例子还是没看懂

这是我更新listview的代码 Handler handler = new Handler(){ List<Map<String, Object>> listItemx = new ArrayList<Map<String, Object>>(); public void handleMessage(android.os.Message msg) { if (msg.arg1 == 0X456) { listItemx = (List<Map<String, Object>>) msg.obj; SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), listItemx, R.layout.weather_simple_item, new String[]{"city", "lowtemp", "hightemp", "week", "curTemp", "type", "fengli", "aqi"}, new int[]{R.id.city, R.id.lowtemp, R.id.hightemp, R.id.week, R.id.curTemp, R.id.type, R.id.fengli, R.id.aqi}); ListView list = (ListView) getView().findViewById(R.id.chat_weathers); // 为ListView设置Adapter list.setAdapter(simpleAdapter); simpleAdapter.notifyDataSetChanged(); } } }; 求大神啊

listview无法显示,求大神解决

适配器 class MsgAdapter extends BaseAdapter { private List<Msg> listMsg = new ArrayList<Msg>(); private Context cxt; private LayoutInflater inflater; public MsgAdapter(ChatActivity ChatActivity) { this.cxt = ChatActivity; } @Override public int getCount() { return listMsg.size(); } @Override public Object getItem(int position) { return listMsg.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(listMsg.get(position).from.equals("IN")){ this.inflater = (LayoutInflater) this.cxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = this.inflater.inflate(R.layout.msg_left, null); }else{ convertView = this.inflater.inflate(R.layout.msg_right, null); } TextView useridView = (TextView) convertView.findViewById(R.id.userid); TextView dateView = (TextView) convertView.findViewById(R.id.date); TextView msgView = (TextView) convertView.findViewById(R.id.msg); useridView.setText(listMsg.get(position).userid); dateView.setText(listMsg.get(position).date); msgView.setText(listMsg.get(position).msg); return convertView; } } 消息类 public class Msg { String userid; String msg; String date; String from; public Msg(String userid, String msg, String date, String from) { this.userid = userid; this.msg = msg; this.date = date; this.from = from; } } 主程序 public class ChatActivity extends Activity{ private ListView msgListView; private EditText inputText; private MsgAdapter adapter; private Button send; private List<Msg> listMsg=new ArrayList<Msg>(); private String pUSERID="用户"; String strFirendName = "医生"; String user = "test1"; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.chat); //initMsgs(); inputText=(EditText)findViewById(R.id.chat_edit); send=(Button)findViewById(R.id.send); adapter = new MsgAdapter(this); msgListView=(ListView)findViewById(R.id.listview); msgListView.setAdapter(adapter); ChatManager cm = connect.getConnection().getChatManager(); cm.addChatListener(new ChatManagerListener() { @Override public void chatCreated(Chat chat, boolean able) { chat.addMessageListener(new MessageListener() { @Override public void processMessage(Chat chat2, Message message) { //message from user [test2@hp-pc] String[] args = new String[] {strFirendName , message.getBody(), TimeRender.getDate(), "IN" }; android.os.Message msg = handler.obtainMessage(); msg.obj = args; msg.sendToTarget(); System.out.println(message.getBody()); // orther user / group / admin of the openfire // do work... } }); } }); //发送 final Chat newchat = cm.createChat( user + "@hp-pc", null); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String msg = inputText.getText().toString(); if(msg.length() > 0){ listMsg.add(new Msg(pUSERID, msg, TimeRender.getDate(), "OUT")); Log.e("ChatActivity","addmsg"); adapter.notifyDataSetChanged(); Log.e("ChatActivity","change"); try { newchat.sendMessage(msg); } catch (XMPPException e) { e.printStackTrace(); } } inputText.setText(""); } }); } private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { String[] args = (String[]) msg.obj; listMsg.add(new Msg(args[0], args[1], args[2], args[3])); //动态刷新 adapter.notifyDataSetChanged(); } }; }; 是一个聊天界面的listview,测试的时候用spark收得到消息,但是自己的界面就收发都不显示,不知道为什么,网上查了也不知道问题

求大神,安卓中,如何动态更新ListView?

我在listview中的点击长按事件中删除了一条数据,就是在sqlite里删掉了,怎么能立即刷新listview呢? listview我用cursorAdapter 求大神解答,谢谢了,没有c币了,实在不好意思~ ``` package com.chase.cn.demon; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; /** * Created by Chase on 2016/11/10. */ public class BillActivity extends Activity { private ListView billListView; private MySQLiteOpenHelper sqLiteOpenHelper; private SQLiteDatabase mDataBase; private SimpleCursorAdapter billAdapter; private boolean flag = true; // 存储数据的数组列表 // ArrayList<HashMap<String, Object>> listData; // 适配器 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bill); sqLiteOpenHelper = new MySQLiteOpenHelper(BillActivity.this, "finance.db", null, 1); mDataBase = sqLiteOpenHelper.getReadableDatabase(); final Cursor c = mDataBase.rawQuery("select * from finance", null); Log.i("database", "data" + mDataBase.isOpen()); billListView = (ListView) findViewById(R.id.bill_listView); billAdapter = new SimpleCursorAdapter(BillActivity.this, R.layout.bill_item, c, // ListItem的XML实现 // 动态数组与Item对应的子项 new String[]{"Time", "Fee", "Budget", "Type"}, // ImageItem的XML文件里面的一个ImageView,两个TextView ID new int[]{R.id.billItem_time, R.id.billItem_money, R.id.billItem_budget, R.id.billItem_type}); billListView.setAdapter(billAdapter); //item监听 billListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { String cc = c.getString(c.getColumnIndex("_id")); //用cursor得到对应表中的id Log.i("info", "cc= " + cc); Toast.makeText(BillActivity.this, "删除了", Toast.LENGTH_SHORT).show(); //删除表中的对应id的行 mDataBase.execSQL("delete from finance where _id=" + cc); ```

安卓fragment数据刷新问题

我是几个fragment放在一个activity里面,想要实现从fragmenta每次到fragmentb是,fragmentb刷新数据,怎么实现,谢谢

editView 搜索listview更新

ava.lang.ArrayIndexOutOfBoundsException: length=2; index=2 at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:7374) at android.widget.ListView.layoutChildren(ListView.java:1730) at android.widget.AbsListView.onLayout(AbsListView.java:2348) at android.view.View.layout(View.java:16104) at android.view.ViewGroup.layout(ViewGroup.java:5185) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1959) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1813) at android.widget.LinearLayout.onLayout(LinearLayout.java:1722) at android.view.View.layout(View.java:16104) at android.view.ViewGroup.layout(ViewGroup.java:5185) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639) at android.widget.FrameLayout.onLayout(FrameLayout.java:574) at android.view.View.layout(View.java:16104) at android.view.ViewGroup.layout(ViewGroup.java:5185) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1959) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1813) at android.widget.LinearLayout.onLayout(LinearLayout.java:1722) at android.view.View.layout(View.java:16104) at android.view.ViewGroup.layout(ViewGroup.java:5185) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639) at android.widget.FrameLayout.onLayout(FrameLayout.java:574) at android.view.View.layout(View.java:16104) at android.view.ViewGroup.layout(ViewGroup.java:5185) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1959) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1813) at android.widget.LinearLayout.onLayout(LinearLayout.java:1722) at android.view.View.layout(View.java:16104) at android.view.ViewGroup.layout(ViewGroup.java:5185) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639) at android.widget.FrameLayout.onLayout(FrameLayout.java:574) at android.view.View.layout(View.java:16104) at android.view.ViewGroup.layout(ViewGroup.java:5185) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2606) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2290) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1338) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6799) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:822) at android.view.Choreographer.doCallbacks(Choreographer.java:619) at android.view.Choreographer.doFrame(Choreographer.java:588) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:808) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:194)

超时则清除list中的element,刷新listview?

连续读取人员信息并将其以map形式添加到list当中,如果list中的一条人员信息在30s内未能再一次读到,则将list中的该条信息清除,请问各位前辈有什么实现办法?谢谢!我我采用下面代码并未得到正确结果 ``` //确保list里面放的是不同对象map的堆地址,指向的是不同对象 Map<String, Object> map = new HashMap<String, Object>(); map.put("itemName", name); //注意此处不可将Bitmap对象直接放入hashmap中,而应传入地址 map.put("itemPhoto", photoPath); map.put("addTime",System.currentTimeMillis()); Log.v("map", map.toString()); //根据姓名查看list当中是否存在所有项 boolean exist = false; for(Map<String, Object> tempMap : list){ if(name.equals(tempMap.get("itemName"))){ exist = true; //如果有则更新时间 tempMap.put("addTime", System.currentTimeMillis()); break; } } //如果不存在,则添加到list当中 if(!exist){ list.add(map); } Log.v("removeb2",list.toString()); //遍历list查看有无超时项,有则清空该项 Iterator<Map<String, Object>> it = list.iterator(); while(it.hasNext()){ if(System.currentTimeMillis()-Long.parseLong(it.next().get("addTime").toString())>30000){ it.remove(); } } }; } //将定时任务中获取的List装入ListView中 Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); ``` ``` switch (msg.what) { case 1: /*tv1.setText(null); tv2.setText(null); tv3.setText(null); img.setImageBitmap(null);*/ SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,list,R.layout.activity_item, new String[]{"itemName","itemPhoto"},//查询键值获取map中资源 new int[]{R.id.itemName,R.id.itemPhoto});//将获取的资源填入对应项 adapter.notifyDataSetChanged();//刷新adapter从而达到刷新列表的目的。 lv.setAdapter(adapter); ```

android每次输入新的pid(id)然后刷新listview。 我怎么做的?

<div class="post-text" itemprop="text"> <p>my code . please help me . i'm beginner . php json andriod Mainactivity java please help me . when data change listview update automaticly and real time show my android app please help me </p> <pre><code> package com.example.aaa111; public class MainActivity extends ListActivity { private ProgressDialog pDialog; // URL to get contacts JSON private static String url = "http://test.pokupat.net/get_all_products.php"; // JSON Node names private static final String TAG_PRODUCTS = "products"; private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name"; // contacts JSONArray JSONArray contacts = null; // Hashmap for ListView ArrayList&lt;HashMap&lt;String, String&gt;&gt; contactList; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); ListView lv = getListView(); // refresh function if this true .. Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //do anything new GetContacts().execute(); } }, 10000); // Listview on item click listener lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // getting values from selected ListItem String name = ((TextView) view.findViewById(R.id.name)) .getText().toString(); String pid = ((TextView) view.findViewById(R.id.pid)) .getText().toString(); // Starting single contact activity Intent in = new Intent(getApplicationContext(), SingleContactActivity.class); in.putExtra(TAG_NAME, name); in.putExtra(TAG_PID, pid); startActivity(in); } }); // Calling async task to get json uyffuyfuyfuy fyuf yfuy fuf uyfuy new GetContacts().execute(); } /** * Async task class to get json by making HTTP call * */ private class GetContacts extends AsyncTask&lt;Void, Void, Void&gt; { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); Log.d("Response: ", "&gt; " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node contacts = jsonObj.getJSONArray(TAG_PRODUCTS); // looping through All Contacts for (int i = 0; i &lt; contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String name = c.getString(TAG_NAME); String pid = c.getString(TAG_PID); // tmp hashmap for single contact HashMap&lt;String, String&gt; contact = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value contact.put(TAG_NAME, name); contact.put(TAG_PID, pid); // adding contact to contact list contactList.add(contact); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); ListAdapter adapter = new SimpleAdapter( MainActivity.this, contactList, R.layout.list_item, new String[] { TAG_NAME, TAG_PID }, new int[] { R.id.name, R.id.pid}); setListAdapter(adapter); } } } </code></pre> <p>refresh background please</p> </div>

调用adapter的时候,会执行getcount且返回count>0,但就是不执行getView().

首先放代码: public View onCreateView() { Log.d(TAG, "onCreateView"); if (layout == null) { //add layout = new LinearLayout(activity); layout.setOrientation(LinearLayout.VERTICAL); layout.setBackgroundColor(Color.WHITE); listview = new ListView(activity); // listview.setDividerHeight(0); listview.setVerticalScrollBarEnabled(false); LinearLayout.LayoutParams listParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0); layout.addView(listview, listParams); itemList = Global.toDoSrv.getAllData(false); Log.d(TAG, "itemList"+itemList.get(0).getTitle()); adapter = new ToDoListAdapters(activity,itemList); listview.setAdapter(adapter); updateList(); } if (listview.getCount() <= 0) { listview.setBackgroundColor(Color.WHITE); ImageView image = new ImageView(activity); LayoutParams mParams = new LayoutParams(198, 242); mParams.setMargins(172, 220, 0, 0); image.setLayoutParams(mParams); image.setMaxHeight(198); image.setMaxWidth(242); image.setBackgroundResource(R.drawable.none_todo_bg); layout.addView(image); } if (layout.getParent() != null) { ((ViewGroup) layout.getParent()).removeView(layout); } return layout; } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Log.d(TAG, "handleMessage:"+msg); switch (msg.what) { case MESSAGE_UPDATE_DATA: doUpdate(); break; case MESSAGE_UPDATE_LISTVIEW: updateAdapter(); break; } } }; private void updateList() { itemList = Global.toDoSrv.getAllData(true); adapter.notifyDataSetChanged(); } // 跟新 protected void doUpdate() { new Thread(new Runnable() { @Override public void run() { listNewTodo = Global.toDoSrv.getAllData(false); handler.sendEmptyMessage(MESSAGE_UPDATE_LISTVIEW); } }).start(); } // 刷新适配器 public void updateAdapter() { itemList.clear(); int count = listNewTodo.size(); for (int i = 0; i < count; ++i) { itemList.add(listNewTodo.get(i)); }; adapter.notifyDataSetChanged(); } private class ToDoListAdapters extends BaseAdapter { private NoteListActivity noteactivity; private List<ToDoItem> itemLists = new ArrayList<ToDoItem>(); public ToDoListAdapters(Context c,List<ToDoItem> itemList){ this.noteactivity = (NoteListActivity) c; this.itemLists = itemList; } @Override public int getCount() { if (itemLists == null) { Log.d(TAG, "ToDoListAdapters-->getCount-->itemLists == null"); return 0; } Log.d(TAG, "ToDoListAdapters-->getCount-->itemLists != null count:"+itemLists.size()); return itemLists.size(); } @Override public ToDoItem getItem(int arg0) { if (itemLists == null) { return null; } Log.d(TAG, "ToDoListAdapters-->getCount-->itemLists != null ToDoItem:"+itemLists.get(arg0)); return itemLists.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup root) { Log.d(TAG, "ToDoListAdapters:getView"); ToDoItemView itemView; if (convertView == null) { itemView = new ToDoItemView(noteactivity); } else { itemView = (ToDoItemView) convertView; } ToDoItem item = getItem(position); itemView.setToDoItem(item); return itemView; } } public void update(boolean force) { if (adapter == null) { adapter = new ToDoListAdapters(activity,itemList); listview.setAdapter(adapter); adapter.notifyDataSetChanged(); listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position < adapter.getCount()) { // 从适配器中获取当前点击项的内容 } } }); } if (adapter != null && (adapter.getCount() < 1 || force)) { handler.sendEmptyMessageDelayed(MESSAGE_UPDATE_DATA, 500); } } 在调试的时候getcount会获得count>0,但getView()就是不执行,线程会影响getView()?这个问题郁闷了好久,求解答。。。。。

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

C++11:一些微小的变化(新的数据类型、template表达式内的空格、nullptr、std::nullptr_t)

本文介绍一些C++的两个新特性,它们虽然微小,但对你的编程十分重要 一、Template表达式内的空格 C++11标准之前建议在“在两个template表达式的闭符之间放一个空格”的要求已经过时了 例如: vector&lt;list&lt;int&gt; &gt;; //C++11之前 vector&lt;list&lt;int&gt;&gt;; //C++11 二、nullptr ...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

深入剖析Springboot启动原理的底层源码,再也不怕面试官问了!

大家现在应该都对Springboot很熟悉,但是你对他的启动原理了解吗?

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

【阿里P6面经】二本,curd两年,疯狂复习,拿下阿里offer

二本的读者,在老东家不断学习,最后逆袭

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

微软为一人收购一公司?破解索尼程序、写黑客小说,看他彪悍的程序人生!...

作者 | 伍杏玲出品 | CSDN(ID:CSDNnews)格子衬衫、常掉发、双肩包、修电脑、加班多……这些似乎成了大众给程序员的固定标签。近几年流行的“跨界风”开始刷新人们对程序员的...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

立即提问
相关内容推荐