简体   繁体   中英

My Listview is not refresh after update database row

My ListView is not refreshing after i am using notifyDataSetChanged(); but i dont know what is wrong in my code please help me how to update my listview when my database is update.

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;

public class EventsView extends Fragment {
    ListView list4;
    String json_string;
    String JSON_STRING;
    JSONObject JO;
    JSONObject jsonObject;
    JSONArray jsonArray;
    int count = 0;
    HashMap<String, Object> obj;
    String topic,description,event_date,event_id;
    private Context mContext;
    private PopupWindow mPopupWindow;
    private LinearLayout linearLayout;
    private Activity mActivity;
    ProgressDialog pDialog;
    String finalResult ;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    String HttpURL = "http://192.168.1.10:8081/sms/update_event.php";
    String HttpURLDelete = "http://192.168.1.10:8081/sms/delete_event.php";
    SimpleAdapter adapter;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.events_view, container, false);
        mContext = getContext();
        mActivity = getActivity();
        linearLayout = (LinearLayout) view.findViewById(R.id.r2);
        list4=(ListView)view.findViewById(R.id.list4);
        new show_event().execute();

        list4.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                obj = (HashMap<String, Object>) list4.getAdapter().getItem(position);
                new show_list().execute();
            }
        });

        return view;
    }


    class show_event extends AsyncTask<String,String,String> {

        ProgressDialog pdLoading = new ProgressDialog(getActivity());
        String json_url;
        @Override
        protected void onPreExecute() {
            json_url = "http://192.168.1.10:8081/sms/select_event.php";
            pdLoading.setMessage("\tLoading...");
            pdLoading.isIndeterminate();
            pdLoading.setIndeterminate(true);
            pdLoading.setCancelable(false);
            pdLoading.show();
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();

                while ((JSON_STRING = bufferedReader.readLine()).equals("null")) ;
                {
                    stringBuilder.append(JSON_STRING +"\n");
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            List<Map<String, String>> data2 = null;
            data2 = new ArrayList<Map<String, String>>();
            json_string = result;
            try {
                jsonObject = new JSONObject(json_string);
                jsonArray = jsonObject.getJSONArray("server_response");
                if (jsonArray.length() != 0) {

                    for (count = 0; count < jsonArray.length(); count++) {
                        JO = jsonArray.getJSONObject(count);
                        HashMap<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A",JO.getString("Id"));
                        datanum.put("B",JO.getString("Topic"));
                        datanum.put("C",JO.getString("Description"));
                        datanum.put("D",JO.getString("Event_Date"));
                        data2.add(datanum);

                    }

                    adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
                    list4.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

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

            pdLoading.dismiss();

        }

    }

    class show_list extends AsyncTask<String,String,String> {
        private int mYear, mMonth, mDay;
        ProgressDialog pdLoading = new ProgressDialog(getActivity());


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

            event_id=(String)obj.get("A");
            topic = (String) obj.get("B");
            description=(String)obj.get("C");
            event_date=(String)obj.get("D");
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pdLoading.setMessage("\tLoading...");
            pdLoading.isIndeterminate();
            pdLoading.setIndeterminate(true);
            pdLoading.setCancelable(false);
            pdLoading.show();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            final View customView = inflater.inflate(R.layout.edit_event,null);
            mPopupWindow = new PopupWindow(customView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
            mPopupWindow.setOutsideTouchable(true);

            if(Build.VERSION.SDK_INT>=21){
                mPopupWindow.setElevation(5.0f);
            }


            final EditText edit_topic=(EditText)customView.findViewById(R.id.edit_topic);
            final EditText edit_description=(EditText)customView.findViewById(R.id.edit_description);
            final EditText edit_date=(EditText)customView.findViewById(R.id.edit_Date);
            Button delete_btn=(Button)customView.findViewById(R.id.delete);


            Button update_btn=(Button)customView.findViewById(R.id.update);

            edit_topic.setText(topic);
            edit_description.setText(description);
            edit_date.setText(event_date);
            final String id=String.valueOf(event_id);


            edit_date.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Get Current Date
                    final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                    edit_date.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
                                }
                            }, mYear, mMonth, mDay);
                    datePickerDialog.show();
                }

            });

            update_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String topic= edit_topic.getText().toString();
                    String description=  edit_description.getText().toString();
                    String edit_event_date=edit_date.getText().toString();
                    StudentRecordUpdate(id,topic,description,edit_event_date);
                    mPopupWindow.dismiss();


                }
            });
            delete_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    StudentDelete(id);
                }
            });

            mPopupWindow.showAtLocation(linearLayout, Gravity.CENTER,0,0);
            mPopupWindow.setFocusable(true);
            mPopupWindow.update();
            pdLoading.dismiss();

        }

    }
    public void StudentRecordUpdate(final String id, final String topic, final String description, final String  event_date){

        class StudentRecordUpdateClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);
                pDialog.dismiss();

                Toast.makeText(getActivity(),httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            }

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

                hashMap.put("Id",params[0]);
                hashMap.put("Topic",params[1]);
                hashMap.put("Description",params[2]);
                hashMap.put("Event_Date",params[3]);


                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        StudentRecordUpdateClass studentRecordUpdateClass = new StudentRecordUpdateClass();

        studentRecordUpdateClass.execute(id,topic,description,event_date);
    }

    // Method to Delete Student Record
    public void StudentDelete(final String ID) {

        class StudentDeleteClass extends AsyncTask<String, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                pDialog = ProgressDialog.show(getActivity(), "Loading Data", null, true, true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                pDialog.dismiss();

                Toast.makeText(getContext(), httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

               getActivity().finish();


            }

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

                // Sending STUDENT id.
                hashMap.put("Id", params[0]);

                finalResult = httpParse.postRequest(hashMap, HttpURLDelete);

                return finalResult;
            }
        }

        StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

        studentDeleteClass.execute(ID);
    }

}

Try this set Adapter with empty list as soon as you initialize your ListView , then just add data to list and call notifyDataSetChanged() on adapter

Make list global

List<Map<String, String>> data2 = new ArrayList<Map<String, String>>();

Then in onCreateView , add below code under listview initialization

 list4=(ListView)view.findViewById(R.id.list4);
 adapter = new SimpleAdapter(getActivity(),data2, R.layout.listview3, new String[]{"D","B"}, new int[]{R.id.tv1,R.id.tv2});
 list4.setAdapter(adapter);

Then in onPostExecute of your AsyncTask , clear the existing list and new data,then just call notifyDataSetChanged() as in

        @Override
        protected void onPostExecute(String result) {
            data2.clear(); //< --add this
            json_string = result;
            try {
                jsonObject = new JSONObject(json_string);
                jsonArray = jsonObject.getJSONArray("server_response");
                if (jsonArray.length() != 0) {

                    for (count = 0; count < jsonArray.length(); count++) {
                        JO = jsonArray.getJSONObject(count);
                        HashMap<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A",JO.getString("Id"));
                        datanum.put("B",JO.getString("Topic"));
                        datanum.put("C",JO.getString("Description"));
                        datanum.put("D",JO.getString("Event_Date"));
                        data2.add(datanum);

                    }
                   adapter.notifyDataSetChanged(); //< --- call this
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            pdLoading.dismiss();

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM