如何在更新数据时更新listview?

时间:2015-10-02 14:52:53

标签: android android-listview android-arrayadapter android-adapter

我是android的新手,我希望在数据插入mysql数据库时更新我的​​列表视图。我在互联网上搜索过,我使用过adapter.notifyDataSetChanged();但我一直收到错误"方法notifyDataSetChanged()未定义类型ListAdapter"

代码:

public class Messages extends BaseActivity{

    private String[] navMenuTitles;
    private TypedArray navMenuIcons;
    private EditText editTextName;
    SharedPreferences sp;
    private String jsonResult;
    private ListView listView;
    private Button b;
    EditText etname, et;
    TextView tv;
    String myJSON;
    private static final String TAG = "MainActivity.java"; 
    private static final String TAG_RESULTS="result";
    private static final String TAG_USERNAME = "username";
    private static final String TAG_NAME = "message_recd";
    private static final String TAG_ADD ="message_sent";

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list;

    public static final String USER_NAME = "USERNAME";

    @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);



        SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
        String session_id= myprefs.getString("session_id", null);


        TextView textView = (TextView) findViewById(R.id.fname);
        textView.setText("Welcome "+session_id);





        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); 

        navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
        // load icons from
                                                            // strings.xml

        set(navMenuTitles, navMenuIcons);
        editTextName = (EditText) findViewById(R.id.editTextName);
        b=(Button)findViewById(R.id.button1);
        list = (ListView) findViewById(R.id.listView);
        personList = new ArrayList<HashMap<String,String>>();

        getData();


        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                etname=(EditText)findViewById(R.id.editTextName);
                if( etname.getText().toString().trim().equals("")){
                    etname.setError( "Cannot be left empty!" );    
                }
                // TODO Auto-generated method stub
                else{

                    Intent intent = getIntent();
                    String fName = intent.getStringExtra("fname");
                    String message = etname.getText().toString();
                    insertToDatabase(message, fName);

            }

                etname.setText("");
            }
        });

    }


         //send messages start
        private void insertToDatabase(String message, String fName1){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                String paramUsername = params[0];
                String fname = params[1];

                //InputStream is = null;

                String message = editTextName.getText().toString();


                Intent intent1 = getIntent();
                String fName = intent1.getStringExtra("fname");
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("message", message));
                nameValuePairs.add(new BasicNameValuePair("username", fName));
                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("http://10.0.2.2/test/test.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();

                    //is = entity.getContent();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "success";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();

            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(message, fName1);
    }
         //send messages stop

        //get json data start
        protected void showList(){
            try {
                JSONArray peoples = new JSONArray(myJSON);
                    for(int i=0;i<peoples.length();i++){
                    JSONObject c = peoples.getJSONObject(i);
                    String name=null, address=null;

                    if(c.has("message_recd"))
                        name = c.getString("message_recd");
                     else 
                    address = c.getString("message_sent");
                    HashMap<String,String> persons = new HashMap<String,String>();
                    persons.put(TAG_NAME,name);
                    persons.put(TAG_ADD,address);
                    personList.add(persons);

                    }
                /*ListAdapter adapter = new SimpleAdapter(
                        Messages.this, personList, R.layout.list_item,
                        new String[]{TAG_NAME,TAG_ADD},
                        new int[]{R.id.name, R.id.address}
                );*/




                    ListAdapter adapter = new SimpleAdapter(
                            Messages.this, personList, R.layout.list_item,
                            new String[]{TAG_NAME,TAG_ADD},
                            new int[]{R.id.name, R.id.address}
                    );

//                    http://www.vogella.com/tutorials/AndroidListView/article.html
//                    http://stackoverflow.com/questions/8166497/custom-adapter-for-list-view

                list.setAdapter(adapter);
            } catch (JSONException e) {
                Log.i("tagconvertstr", "["+myJSON+"]");

            }
        }




        public void getData(){
            class GetDataJSON extends AsyncTask<String, Void, String>{

                 @Override
                protected String doInBackground(String... params) {

                    SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
                    String session_id= myprefs.getString("session_id", null);

                    InputStream inputStream = null;
                    String result = null;
                    try {

                        String postReceiverUrl = "http://10.0.2.2/progress_card/messages/get_messages.php";

                        // HttpClient
                        HttpClient httpClient = new DefaultHttpClient();

                        // post header
                        HttpPost httpPost = new HttpPost(postReceiverUrl);

                        // add your data
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                        nameValuePairs.add(new BasicNameValuePair("username", session_id));

                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpClient.execute(httpPost);
                        HttpEntity resEntity = response.getEntity();

                        inputStream = resEntity.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");
                        }
                        result = sb.toString();
                    } catch (Exception e) {
                        Log.i("tagconvertstr", "["+result+"]");
                        System.out.println(e);
                    }
                    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();
        }
        //get json data stop

        }

2 个答案:

答案 0 :(得分:2)

notifyDataSetChanged方法是在BaseAdapter中定义和实现的,SimpleAdapter的超类型。所以只需添加一个转换为BaseAdapterSimpleAdapter

答案 1 :(得分:-1)

当您将任何add()remove()操作执行到您的个人列表时, 调用adpater.notifyDataSetChanged();方法更新ListView

参考:notifyDataSetChanged example