ListView没有得到更新,我应该在哪里调用notifyDataSetChanged()以及我应该在哪里设置适配器?

时间:2015-12-09 05:58:03

标签: android json listview

我编写了一个程序来发布一些json数据并获取相同的json数据,以便我可以在同一活动的ListView中显示数据。 在volley库的帮助下发布数据并获取数据。

所以我的问题是当我在EditText内输入内容并点击按钮发布一些数据时,数据会被发布但我无法立即在ListView内查看我的ListView内的短数据没有立即刷新。我也尝试使用notifyDataSetChanged(),但都是徒劳的。

我在这里发布我的整个活动,请告诉我我必须在哪里设置我的适配器,我的ArrayListnotifyDataSetChanged()

public class Write_Answers extends ListActivity{
Boolean isInternetPresent = false;
ConnectionDetector cd;
TextView txtQuestions;
String questions;
EditText editAnswers;
Button btnAnswer;
String postAnswerUrl = "";
String getAnswerUrl = "";
public String answers;
SessionManager session;
String userType,deviceId,questionId;
ListView lvAnswers;
public static final String TAG_QUESTION_ID = "QId";
public static final String TAG_TRANSACTION_ID = "TransactionId";
public static final String TAG_ANSWERS = "Answer";
public static final String TAG_DATE= "Date";
public static final String TAG_TIME = "Time";
public static final String TAG_DEVICE_ID = "DeviceId";
public static final String TAG_USER_TYPE = "UserType";
ArrayList<HashMap<String, String>> answersList;
CustomAnswerAdapter customAnswerAdapter;
HashMap<String,String> ans_details_map;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.write_answers);
    cd = new ConnectionDetector(getApplicationContext());
    isInternetPresent = cd.isConnectingToInternet();
    txtQuestions = (TextView) findViewById(R.id.textQuestions);
    editAnswers = (EditText) findViewById(R.id.edtAnswer);
    btnAnswer = (Button) findViewById(R.id.btnAnswer);
    questions = getIntent().getStringExtra("questions");
    txtQuestions.setText(questions);
    answersList = new ArrayList<HashMap<String, String>>();
    customAnswerAdapter = new 
    CustomAnswerAdapter(Write_Answers.this,answersList);
    lvAnswers = getListView();
    lvAnswers.setAdapter(customAnswerAdapter);
    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    questionId = getIntent().getStringExtra("questionsId");
    postAnswerUrl = "http://gps.traxistar.net/PostAnswers.svc/PostAnswers";
    getAnswerUrl =  "http://gps.traxistar.net/GetAnswers.svc/GetAnswers;

//////////////////////////从服务器获取我必须设置到适配器并在Listview中显示的数据///////////////////////

    if (isInternetPresent) {
        JsonArrayRequest jsonArrayRequest = new 
                JsonArrayRequest(getAnswerUrl,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d("Json Array", response.toString());
                        try {
                            for (int i = 0; i < response.length(); i++) {
                                JSONObject json = response.getJSONObject(i);
                                String ques_id = 
                                json.getString(TAG_QUESTION_ID);
                                String trans_id = 
                                json.getString(TAG_TRANSACTION_ID);
                                String device_id = 
                                json.getString(TAG_DEVICE_ID);
                                String ans = json.getString(TAG_ANSWERS);
                                String answerDate = 
                                json.getString(TAG_DATE);
                                String answerTime = 
                                json.getString(TAG_TIME);
                                String userType = 
                                json.getString(TAG_USER_TYPE);
                                ans_details_map = new HashMap<String, 
                                String>();
                                ans_details_map.put(TAG_ANSWERS, ans);
                                ans_details_map.put(TAG_DATE, answerDate);
                                ans_details_map.put(TAG_TIME, answerTime);
                                answersList.add(ans_details_map);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                          customAnswerAdapter.notifyDataSetChanged();
                          lvAnswers.setSelection(answersList.size() - 1);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Volley Error", "Error: " + error.getMessage());
                Log.d("Error", "Error: " + error.getMessage());
            }
    });
    AppController.getInstance().addToRequestQueue(jsonArrayRequest);
    } else {
        showAlertDialog(getApplicationContext(), "No Internet Connection", 
        "You don't have internet connection.",
                false);
    }

    btnAnswer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            answers = editAnswers.getText().toString();
            if (answers.equals("")) {
                Toast.makeText(getBaseContext(), "Please write an answer", 
                Toast.LENGTH_LONG).show();
            } else {
                if (isInternetPresent) {
                    postAnswers();
                    editAnswers.setText("");
                } else {
                    showAlertDialog(getApplicationContext(), "No Internet 
                    Connection", "You don't have internet connection.",
                            false);
                }
            }
        }
    });

}

//////////////////////////////按钮点击////////将数据发布到服务器////////////////////

private void postAnswers() {
    Calendar in = Calendar.getInstance();
    Date dt1 = new Date();
    in.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    SimpleDateFormat sdf1 = new SimpleDateFormat("E, MMM d, yyyy");
    String dateval = sdf1.format(dt1);
    SimpleDateFormat stf1 = new SimpleDateFormat("h:mm a");
    String timeval = stf1.format(dt1);
    final String date1 = dateval.toString();
    final String time1 = timeval.toString();
    final String datetime = dateval.toString() + "T"
            + timeval.toString();
    final String transId = deviceId + "" + datetime;
    answers = editAnswers.getText().toString();
    List<Map<String, String>> listMap = 
    new ArrayList<Map<String, String>>();
    Map<String, String> answersMap = new HashMap<String, String>();
    answersMap.put("TransactionId", transId);
    answersMap.put("DeviceId", deviceId);
    answersMap.put("Answer", answers);
    answersMap.put("QId", questionId);
    answersMap.put("Date", date1);
    answersMap.put("Time", time1);
    answersMap.put("UserType", userType);
    listMap.add(answersMap);

    JsonObjectRequest jsObjRequest = new 
    JsonObjectRequest(Request.Method.POST, postAnswerUrl,
            String.valueOf(new JSONArray(listMap)), new 
            Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                Write_Answers.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Answer 
                        posted", Toast.LENGTH_LONG).show();
                    }
                });
                Log.d("Json Response ",response.toString());

            }catch(Exception e){
                //Log.d("JSON Array", response.toString());
                e.printStackTrace();
            }

            //editAnswers.setText("");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Volley Error", error.toString());
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-type", "application/json; charset=utf-8");
            return headers;
        }

        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse 
        response) {
            try {
                String jsonString = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers));
                if (response.data == null || response.data.length == 0) {
                    return Response.success(new JSONObject(), 
                    HttpHeaderParser.parseCacheHeaders(response));
                } else {
                    return Response.success(new JSONObject(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                }
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }
    };
    AppController.getInstance().addToRequestQueue(jsObjRequest);
}

3 个答案:

答案 0 :(得分:0)

ArrayAdapternotifyDataSetChanged仅在您使用add(), insert(), remove(), and clear()上的Adapter时有效。

构造ArrayAdapter时,它保存传入的List的引用。如果要传入属于Activity成员的List,并更改Activity 1}}成员之后,ArrayAdapter仍然保留对原始列表的引用。 Adapter不知道您更改了Activity中的列表。

我建议使用ArrayAdapter的功能来修改基础列表(add(), insert(), remove(), clear()等)。

答案 1 :(得分:0)

您想要执行的任何类型的更新(删除/编辑/添加) (在发布按钮上点击后执行这些步骤)  1.首先更新您的ArrayList  2.使用以前的ArrayList数据从ListView中删除所有视图  3.再次使用更新的ArrayList再次调用适配器

希望这会对你有所帮助。

答案 2 :(得分:0)

尝试调用notifyDatasetChanged(),如下所示:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    customAnswerAdapter.notifyDataSetChanged();
  }
}, 3000);

并检查这是否有效