android listview刷新数据来自服务器问题

时间:2016-05-25 04:32:43

标签: android

我有一个活动,其listview数据来自server.its工作正常,但问题是它不会自动刷新列表我希望listview更新数据来自服务器我尝试但不是为我工作。请帮助我如何做到这里是我的活动代码,我从服务器发送和接收数据。

  public class DataSendActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button button;
    private Button btnLinkToLogin;
    private EditText editText;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    String rremail = null;

    String myJSON;

    private static final String TAG_RESULTS = "result";
    private static final String TAG_DATA = "data";
    private static final String TAG_CREATED_AT = "created_at";
    private static final String TAG_SENDER_EMAIL = "sender_email";
    private static final String TAG_RECIVER_EMAIL = "reciver_email";
    private ListAdapter adapter;
    JSONArray peoples = null;
    int number_count = 1;
    ArrayList<HashMap<String, String>> personList;
    String Semail, Remail, rec, rcvemail,dataa,sender_name;
    private ListView list;
    private TextView e1, e2;
    private TextView rcdata;
    private Thread t;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_data_send);

        final ListAdapter adapter = new SimpleAdapter(
                DataSendActivity.this, personList, R.layout.layout_chat,
                new String[]{TAG_DATA,TAG_CREATED_AT},
                new int[]{R.id.data,R.id.created}

        );

        list.setAdapter(adapter);
        ((BaseAdapter)adapter).notifyDataSetChanged();
      /* final Handler handler = new Handler();
        handler.postDelayed( new Runnable() {

            @Override
            public void run() {
                    showList();
                ((BaseAdapter)adapter).notifyDataSetChanged();
                handler.postDelayed( this, 5000 );
            }
        }, 5000 );

 */
        db = new SQLiteHandler(getApplicationContext());
        e1 = (TextView) findViewById(R.id.textView);
        e2 = (TextView) findViewById(R.id.textView2);
        e2.setVisibility(View.GONE);

        rcdata = (TextView)findViewById(R.id.texdata);
        rcdata.setVisibility(View.GONE);
        final Bundle extras = getIntent().getExtras();
        if (extras != null) {

            Remail = extras.getString("email");
            e1.setText(extras.getString("email"));
            rremail = extras.getString("email");
            rcvemail = extras.getString("rcvemail");
            //  e1.setText(extras.getString("rcvemail"));
            dataa = extras.getString("dataaa");
        }


        personList = new ArrayList<HashMap<String, String>>();
        getData();
       // getData2();
        //getData3();
        //  SendData("hiiiiii","fasial","malik");
        list = (ListView) findViewById(R.id.listView);
        //textView = (TextView)findViewById(R.id.textView);
        db = new SQLiteHandler(getApplicationContext());
        editText = (EditText) findViewById(R.id.data);
        //inputEmail = (EditText) findViewById(R.id.email);
        //inputPassword = (EditText) findViewById(R.id.password);
        button = (Button) findViewById(R.id.btns);
        //btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // Session manager
        session = new SessionManager(getApplicationContext());

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
        }

        HashMap<String, String> user = db.getUserDetails();

        //String name = user.get("name");
        Semail = user.get("email");
        sender_name = user.get("name");

        // Displaying the user details on the screen

        e2.setText(Semail);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String data = editText.getText().toString().trim();
                final String reciver_email = e1.getText().toString().trim();
                final String sender_email = e2.getText().toString().trim();

                //editText.setText(sender_email);
                if (editText.getText().toString().matches("")) {
                    editText.setError("please enter some text");
                    return;
                }

               else{
                SendData(sender_name+" "+":"+" "+data, sender_email, reciver_email);
                HashMap<String, String> user_data = db.getDataDetails();
            }

            }
        });
    }

    private void SendData(final String data, final String sender_email, final String reciver_email) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        //   pDialog.setMessage("Sending...");
        //  showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_SEND_DATA, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.i(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {

                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("sender_email", sender_email);
                params.put("reciver_email", reciver_email);
                params.put("data", data);
                // Toast.makeText(getApplicationContext(), "message successfully sent!", Toast.LENGTH_LONG).show();
                return params;

            }

        };
        // Intent intent = new Intent(this,DataSendActivity.class);
        // startActivity(intent);
        // Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_SHORT).show();
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
        //  Intent intent = new Intent(this,DataSendActivity.class);
        //startActivity(intent);
        // else{
        final String reciver_email = e1.getText().toString().trim();
        ////  Intent intent = new Intent(this,DataSendActivity.class);

        //   startActivity(intent);
        //   this.finish();
        Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_SHORT).show();
        //}
    }



    protected void showList() {
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray(TAG_RESULTS);

            for (int i = 0; i < peoples.length(); i++) {
                JSONObject c = peoples.getJSONObject(i);
                String data = c.getString(TAG_DATA);
                String created_at = c.getString(TAG_CREATED_AT);
               // final String dataaaa = rcdata.getText().toString().trim();
                HashMap<String, String> user_data = new HashMap<String, String>();
                user_data.put(TAG_DATA, data);
                user_data.put(TAG_CREATED_AT, created_at);
                personList.add(user_data);
            }
        /*    final ListAdapter adapter = new SimpleAdapter(
                    DataSendActivity.this, personList, R.layout.layout_chat,
                    new String[]{TAG_DATA,TAG_CREATED_AT},
                    new int[]{R.id.data,R.id.created}

            );

            list.setAdapter(adapter);

*/
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public void getData() {
        class GetDataJSON extends AsyncTask<String, Void, String> {
            //String recID = ;
            //String userID = email;
            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HashMap<String, String> user = db.getUserDetails();

                //String name = user.get("name");
               // Semail = user.get("email");

                String semail  = user.get("email");
                final String remail = rremail;

                HttpPost httppost = new HttpPost("http://samplechatapp.gear.host/myphpfile.php?sender_email="+semail+"&reciver_email="+remail+"&fatch_server_data=true");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                Log.i("","processing entity");
                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 + "\n");
                        Log.i("",line);
                    }
                    result = sb.toString();
                    Log.i("",result);
                } catch (Exception e) {
                    // Oops
                } finally {
                    try {
                        if (inputStream != null) inputStream.close();
                    } catch (Exception squish) {
                    }
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                myJSON = result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }

我试过这个方法,但应用程序崩溃。

final Handler handler = new Handler();
    handler.postDelayed( new Runnable() {

        @Override
        public void run() {
                showList();
            ((BaseAdapter)adapter).notifyDataSetChanged();
            handler.postDelayed( this, 5000 );
        }
    }, 5000 );

这里是logcat。 enter image description here

1 个答案:

答案 0 :(得分:1)

尝试在OnCreate方法

中实现此行代码
 adapter = new SimpleAdapter(
                DataSendActivity.this, personList, R.layout.layout_chat,
                new String[]{TAG_DATA,TAG_CREATED_AT},
                new int[]{R.id.data,R.id.created}

        );

        list.setAdapter(adapter);

从服务器获取结果后,您只需编写此

adapter.notifyDataSetChanged();

并注意此notifyDataSetChanged不需要handler

您将在适配器声明

之前进行delcare list = (ListView) findViewById(R.id.listView);