getView多次返回行

时间:2016-07-17 18:43:16

标签: android

我正在对我的代码进行一些故障排除,我注意到,当我发布新数据而不是一次时,有时会返回listview行多次。我正在从数据库中读取listview行的内容并将其投影到getView的else if语句中(注释掉Bitmap以使用textview进行测试,仍有相同的问题)

getView:

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View row=convertView;
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (request_my_username.equals(arrRequest_UserContact.get(position))) //YOU
            {
                        if (Request_Message.get(position).equals("MESSAGE-FAILED-TO-POST"))
                            {
                                row = inflater.inflate(R.layout.activity_chatprivate_single_right, parent, false);  

                                TextView txtMessage = (TextView) row.findViewById(R.id.textMessage);    
                                txtMessage.setTypeface(null, Typeface.BOLD);
                                txtMessage.setText(Request_Message.get(position));  
                            }
                        else if (Request_Message.get(position).contains("/storage/"))
                            {
                                /***
                                row = inflater.inflate(R.layout.activity_chatprivate_single_right_img, parent, false);

                                Bitmap bmp_ico = BitmapFactory.decodeFile(Request_Message.get(position));                                   
                                ImageButton ib = (ImageButton) row.findViewById(R.id.ib);
                                ib.setImageBitmap(bmp_ico);
                                ***/

                                row = inflater.inflate(R.layout.activity_chatprivate_single_right, parent, false);  

                                TextView txtMessage = (TextView) row.findViewById(R.id.textMessage);
                                txtMessage.setText(Request_Message.get(position));  
                            }
                        else
                            {
                                row = inflater.inflate(R.layout.activity_chatprivate_single_right, parent, false);  

                                TextView txtMessage = (TextView) row.findViewById(R.id.textMessage);
                                txtMessage.setText(Request_Message.get(position));
                            }
            }

阅读MySQL:

         private class JsonReadChatPrivate extends AsyncTask<String, Void, String> {
          @Override
          protected String doInBackground(String... params) {
           HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost(params[0]);
           try {
            HttpResponse response = httpclient.execute(httppost);
            jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
           }
           catch (ClientProtocolException e) {
            e.printStackTrace();
           } catch (IOException e) {
            e.printStackTrace();
           }
           return null;
          }          
          private StringBuilder inputStreamToString(InputStream is) {
           String rLine = "";
           StringBuilder answer = new StringBuilder();
           BufferedReader rd = new BufferedReader(new InputStreamReader(is));            
           try {
            while ((rLine = rd.readLine()) != null) {
             answer.append(rLine);
            }
           }             
           catch (IOException e) {
           }
           return answer;
          }
          @Override
          protected void onPostExecute(String result) {
              adapter.notifyDataSetChanged();
            try{  
           ListDrawer_readPrivateChat(); //has ConnectionException (when it cannot reach server)
            }catch (Exception e){
                }
          }
         }
         public void accessWebService_readChatPrivate() {
          JsonReadChatPrivate task = new JsonReadChatPrivate();
          task.execute(new String[] { "http://website/php/file_to_read_db.php?pcontactSelected="+contactSelected+"&pIMEI="+IMEI+"&pmysql_room_id="+mysql_room_id});
         }
         public void ListDrawer_readPrivateChat() {
          try {
           JSONObject jsonResponse = new JSONObject(jsonResult);
           JSONArray jsonMainNode = jsonResponse.optJSONArray("request_chat_private");

           for (int i = 0; i < jsonMainNode.length(); i++) {
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            String request_message = jsonChildNode.optString("Message");
            String request_time = jsonChildNode.optString("Time");
            mysql_room_id = jsonChildNode.optString("_id");
            request_last_user = jsonChildNode.optString("LastUser");

            arrRequest_UserContact.add(request_last_user);    
            arrRequest_Message.add(request_message);
            arrRequest_Time.add(request_time);

            adapter.notifyDataSetChanged();

           }
          } catch (JSONException e) {
               }
    }   

每隔5秒听一次,看看是否有关于MySQL的新数据,如果有,只返回上一个MySQL ID的内容(这样我就不会重新添加列表视图中存在的项目):

private void DBListern() {
accessWebService_readChatPrivate();
}
private void loop() {
            handler.postDelayed(new Runnable() { 
            public void run() { 

            DBListern(); 
            handler.postDelayed(this, 5000);
        }
    }, 5000); 
}

XML:

         <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:background="@drawable/bg_chat_2"
             >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" 
                android:layout_weight="1"
                >
                <ListView
                    android:id="@+id/listView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:transcriptMode="normal"
                    android:stackFromBottom="true"
                    android:divider="@null"
                    android:dividerHeight="0dp"
                     >
                </ListView>
            </LinearLayout>
            ...

如上所述,当我发布内容为A然后B然后C它应该返回正确的输出为A,B,C然而它执行此A,AA,BBB,CCCC&lt; - 重复具有相同数据的视图

1 个答案:

答案 0 :(得分:0)

好的,我继续使用日志和toast进行故障排除,问题不在于getView,实际上是从图库中选择图像,这样做时调用onPauce()并在选择图像后调用{{ 1}}在已经运行时再次运行onResume调用。我所做的就是取消之前的循环(loop()),因为它将再次使用handler.removeCallbacksAndMessages(null);

进行调用

我承认我的重点更多是关于listView的getView代码,我从没想过选择一个图像调用系统方法。总是善于处理日志。