1

hello guys i am working an app where i want to update my listview but everything is working perfect only list view is not updated i don't understand where i am doing wrong help me

code is

    public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
    private Spinner spinner;
    private ArrayList<String> students;
    private JSONArray result;
    CallbackManager callbackManager;
    ShareDialog shareDialog;

    //  listveiw data
    private static final String TAG = MainActivity.class.getSimpleName();
    String url = "http://www.example.com/json/json.php";
    private ProgressDialog pDialog;
    private List<Model> movieList = new ArrayList<Model>();
    private ListView listView;
    private CustomListAdapter adapter;
    final Model model = new Model();
    final Json_Data j_data = new Json_Data();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        callbackManager = CallbackManager.Factory.create();
        students = new ArrayList<String>();
        spinner = (Spinner) findViewById(R.id.txtSpinner);
        listView = (ListView) findViewById(R.id.list);
        spinner.setOnItemSelectedListener(this);
        getData();
        listdata();
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final TextView tv_id = (TextView) view.findViewById(R.id.title);
                String txt = tv_id.getText().toString();
                model.setItemText(txt);
                Log.e(TAG, "====>" + txt);
                _Dialog_Custom();
            }
        });
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");
        pDialog.show();
    }
    public void listdata(){
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        hidePDialog();
                        Log.e(TAG, response.toString());
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject obj = response.getJSONObject(i);
                                Model model = new Model();
                                String status = obj.getString("txt");
                                String cate = obj.getString("category");
                                model.setList_category(cate);
                                model.setTitle(status);
                                movieList.add(model);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });
        AppController.getInstance().addToRequestQueue(movieReq);
    }
    private void getData() {
        StringRequest stringRequest = new StringRequest(Config.DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        JSONObject j_obj = null;
                        try {
                            j_obj = new JSONObject(response);
                            result = j_obj.getJSONArray(Config.JSON_ARRAY);
                            //Calling method getStudents to get the students from the JSON Array
                            getStudents(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    private void getStudents(JSONArray j) {
        for (int i = 0; i < j.length(); i++) {
            try {
                JSONObject json = j.getJSONObject(i);
                students.add(json.getString(Config.TAG_USERNAME));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //Setting adapter to show the items in the spinner
        spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
    }
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String text_spinner = spinner.getSelectedItem().toString();
        //Log.e("Selected value in","==>"+text_spinner);
        j_data.setSpintext(text_spinner);
        makeJsonArrayRequest();
        Toast.makeText(MainActivity.this, "Get Value from spinner"    +text_spinner, Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    private void _Dialog_Custom() {
        final Dialog dialog = new Dialog(this);
        final String txt1 = model.getItemText().toString();
        Log.e("Hello Dialog", ":=>" + txt1);
        dialog.setContentView(R.layout.dialogbox);
        dialog.setTitle("Share via");
        dialog.setCanceledOnTouchOutside(true);
        ImageButton _Fb_Sharebtn = (ImageButton) dialog.findViewById(R.id.share_facebook);
        _Fb_Sharebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ShareDialog.canShow(ShareLinkContent.class)) {
                    // https://developers.facebook.com/docs/sharing/android
                    ShareLinkContent linkContent = new ShareLinkContent.Builder()
                            .setContentTitle("Hello Facebook")
                            .setContentDescription(
                                    "The 'Hello Facebook' sample  showcases simple Facebook integration")
                            .setContentUrl(Uri.parse("http://developers.facebook.com/android"))
                            .build();
                      shareDialog.show(linkContent);
                }
            }
        });

        ImageButton _Sharebtn_google = (ImageButton) dialog.findViewById(R.id.share_btn_google);
        _Sharebtn_google.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent shareIntent = new PlusShare.Builder(MainActivity.this)
                        .setType("text/plain")
                        .setText(txt1)
                        .getIntent();
                try {
                    startActivity(shareIntent);
                } catch (ActivityNotFoundException ex) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.plus&hl=en")));
                }
            }
        });

        ImageButton whtsapp_sahre = (ImageButton) dialog.findViewById(R.id.whatsapp_btn);
        whtsapp_sahre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
                whatsappIntent.setType("text/plain");
                whatsappIntent.setPackage("com.whatsapp");
                String result = txt1;
                whatsappIntent.putExtra(Intent.EXTRA_TEXT, result);
                try {
                    startActivity(whatsappIntent);
                } catch (ActivityNotFoundException ex) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.whatsapp")));
                }
            }
        });
        ImageButton _Twwiterbtn = (ImageButton) dialog.findViewById(R.id.twwiter_btn);
        _Twwiterbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                String result = txt1;
                intent.setType("text/plain")
                        .setPackage("com.twitter.android");
                intent.putExtra(Intent.EXTRA_TEXT, result);

                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException ex) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.twitter.android&hl=en")));
                }
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });
        dialog.show();
    }

    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent backintent = new Intent(getApplicationContext(), Main_Selected_Activity.class);
        startActivity(backintent);
        finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    private void makeJsonArrayRequest() {
        String spinner_data =j_data.getSpintext().toString().trim();
        Log.e(TAG, spinner_data.toString());
        String arrayurl = "http://www.example.com/jsoncategory.php?category="+spinner_data;
        Log.e("Link is here","==>"+arrayurl);
        ArrayList<String> newdata = new ArrayList<String>();
        movieList = new ArrayList<Model>();
        JsonArrayRequest movieReq = new JsonArrayRequest(arrayurl,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.e(TAG, "link response=>" + response);
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject obj = response.getJSONObject(i);
                                String name = obj.getString("txt");
                                model.setList_category(name);
                                movieList.add(model);
                            }catch (JSONException e) {
                                e.printStackTrace();
                                Log.e("Hello error","==>"+e);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });
        AppController.getInstance().addToRequestQueue(movieReq);

    }
  }

Screen shot

please help me

3 Answers3

1

Follow The Below approach

Create a public method in your adapter class:

private List<Model> adapterInitialMovieList = null;

 public void setDataOnSpinnerSelected(List<Model> movieList){
 adapterInitialMovieList  = movieList;
notifyDataSetChanged();
}

In Your Activity Class Inside Spinner onClick method:

if(adapter  != null){
adapter.setDataOnSpinnerSelected(yourChangedArrayListOfModelClass);
}
Naveen Shriyan
  • 1,266
  • 1
  • 9
  • 15
0

Remove this line from makeJsonArrayRequest() :

movieList = new ArrayList<Model>();

You are assigning a new object(ArrayList) to the movieList and adding values in the new object instead of the one which you passed to the list adapter. Hence the reference of the object which is being used by the list adapter is lost and when you call adapter.notifyDataSetChanged(); there is no updation as the object which is used by the list adapter is unchanged.

Monish Kamble
  • 1,478
  • 1
  • 15
  • 28
0

use movieList.clear();

instead of

movieList = new ArrayList<Model>();

The problem is about the creation of a new arraylist. So, the ArrayAdapter do not 'know' you when you want to create a new one ArrayList (with the different address). In line adapter = new CustomListAdapter(this, movieList); you push a some address of arraylist. In a new line later you generates a new arraylist with the different one and work with it. But the adapter works with the 'old variant' of arraylist.

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194