user6880336 user6880336 - 14 days ago 5
Android Question

How to refresh listview while clicked?

I want to refresh the

listView
when i pressed
OK
Button, In my application I used
AlertBox
for inserting a data to the
database
.

When I pressed
Ok
Button it is inserting into the database properly but when I fetching the records in the same screen it will fetching the data repeatedly.

ex: I Typed "ABC" then I pressed ok at that time I want to fetch record from the database and display it to the same screen.

I tried alot but not working for me. I tried
adapter.notifyDatasetChanged()
also but no working.

Here the complete code for the reference:

Logcat

alertbox E/Json Object:: {"visit":[{"o_id":"126","o_product":"PioneerP5LWhite","o_qty":"9","o_total":"63000"},{"o_id":"125","o_product":"CTRLV5Black","o_qty":"69","o_total":"517500"},{"o_id":"124","o_product":"Please Select Model","o_qty":"","o_total":"0"},{"o_id":"123","o_product":"PioneerP5LWhite","o_qty":"3669","o_total":"25683000"},{"o_id":"122","o_product":"CTRLV5White","o_qty":"32","o_total":"240000"},{"o_id":"121","o_product":"CTRLV5Blue","o_qty":"6","o_total":"45000"},{"o_id":"120","o_product":"CTRLV5White","o_qty":"5","o_total":"37500"},{"o_id":"119","o_product":"PioneerP5LWhite","o_qty":"6","o_total":"42000"},{"o_id":"118","o_product":"CTRLV5Blue","o_qty":"6","o_total":"45000"},{"o_id":"117","o_product":"V6LWhite","o_qty":"6","o_total":"51000"},{"o_id":"116","o_product":"CTRLV5White","o_qty":"665","o_total":"4987500"},{"o_id":"115","o_product":"CTRLV5Black","o_qty":"2","o_total":"15000"}],"success":1,"success4":1}
11-25 17:30:17.224 4468-6660/com.example.sachin.alertbox D/success4: {"visit":[{"o_id":"126","o_product":"PioneerP5LWhite","o_qty":"9","o_total":"63000"},{"o_id":"125","o_product":"CTRLV5Black","o_qty":"69","o_total":"517500"},{"o_id":"124","o_product":"Please Select Model","o_qty":"","o_total":"0"},{"o_id":"123","o_product":"PioneerP5LWhite","o_qty":"3669","o_total":"25683000"},{"o_id":"122","o_product":"CTRLV5White","o_qty":"32","o_total":"240000"},{"o_id":"121","o_product":"CTRLV5Blue","o_qty":"6","o_total":"45000"},{"o_id":"120","o_product":"CTRLV5White","o_qty":"5","o_total":"37500"},{"o_id":"119","o_product":"PioneerP5LWhite","o_qty":"6","o_total":"42000"},{"o_id":"118","o_product":"CTRLV5Blue","o_qty":"6","o_total":"45000"},{"o_id":"117","o_product":"V6LWhite","o_qty":"6","o_total":"51000"},{"o_id":"116","o_product":"CTRLV5White","o_qty":"665","o_total":"4987500"},{"o_id":"115","o_product":"CTRLV5Black","o_qty":"2","o_total":"15000"}],"success":1,"success4":1}


Activity.java

add.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {

LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);


spinner=(Spinner)promptsView.findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(getApplication(), R.layout.spinner_layout, R.id.txt, listItems);
spinner.setAdapter(adapter);
spinner.setSelection(0);

qty=(EditText)promptsView.findViewById(R.id.qty);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
stringqty=qty.getText().toString();
stringspinner=spinner.getSelectedItem().toString();
addvisitor();
new fetchorder().execute();

Toast.makeText(getApplicationContext(), "qty : " + stringqty +stringspinner, Toast.LENGTH_SHORT).show();

}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});

// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
//new fetchorder().execute();

}
});
}

private class fetchorder extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... args) {
// Create an array
try {
arraylist = new ArrayList<HashMap<String, String>>();


List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);


int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());

if (success1 == 0) {
// Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
}
if (success1 == 1) {
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();


// ArrayList<String> o_aid,o_aproduct,o_aqty,o_atotal;
ownerObj = json.getJSONArray("visit");

for (int i = 0; i < ownerObj.length(); i++) {

jsonobject = ownerObj.getJSONObject(i);

o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}

}
catch(Exception e)
{
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter != null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid,o_aproduct,o_aqty,o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}

}
}


When I type "abc" & then pressed ok button first time it will displaying the record. When I insert another record like "xyz" it will displaying the data perfectly but the problem is when I insert third record like "xxx" then output like "abc","xyz","abc","xyz","xxx". But I want output like "abc","xyz","xxx".

Answer

Initialize o_aid, o_aproduct, o_aqty, o_aqty inside if (success1 == 1)

// Should be in your onCreate();
listview = (ListView)findViewById(R.id.listview);

private class fetchorder extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(Void... args) {
        // Create an array
        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
            int success1 = Integer.parseInt(json.getString("success4"));
            Log.d("success4", json.toString());

            if (success1 == 1) {
                //TODO Initialize o_aid, o_aproduct, o_aqty, o_aqty
                ownerObj = json.getJSONArray("visit");
                for (int i = 0; i < ownerObj.length(); i++) {

                    jsonobject = ownerObj.getJSONObject(i);

                    o_aid.add(jsonobject.getString("o_id"));
                    o_aproduct.add(jsonobject.getString("o_product"));
                    o_aqty.add(jsonobject.getString("o_qty"));
                    o_aqty.add(jsonobject.getString("o_total"));
                }
            }

        }
        catch(Exception e)
        {
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml
        if (listadapter == null) {
            listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid,o_aproduct,o_aqty,o_atotal);
            listview.setAdapter(listadapter);
        } else {
            listadapter.notifyDataSetChanged()
        }
    }
}

Update your code in the below TODO comment:

//TODO o_aid, o_aproduct, o_aqty, o_aqty

The problem with your code is you have initialised above array-list globally and you are just adding elements so they are getting added multiple times. Instead initialise everytime or clear your list as list.clear() then add elements.

After Question Update

if (success1 == 1) {
                    ArrayList<String> o_aid= new ArrayList<String>();
                    ArrayList<String> o_aproduct= new ArrayList<String>();
                    ArrayList<String> o_aqty= new ArrayList<String>();
                    ArrayList<String> o_atotal= new ArrayList<String>();


                    //  ArrayList<String> o_aid,o_aproduct,o_aqty,o_atotal;
                    ownerObj = json.getJSONArray("visit");

                    for (int i = 0; i < ownerObj.length(); i++) {

                        jsonobject = ownerObj.getJSONObject(i);

                        o_aid.add(jsonobject.getString("o_id"));
                        o_aproduct.add(jsonobject.getString("o_product"));
                        o_aqty.add(jsonobject.getString("o_qty"));
                        o_atotal.add(jsonobject.getString("o_total"));
                    }
                }

Here see the below code

ArrayList o_aid= new ArrayList(); ArrayList o_aproduct= new ArrayList(); ArrayList o_aqty= new ArrayList(); ArrayList o_atotal= new ArrayList();

The arrays should be declared globally and initialised inside if condition. Or you can declare and initialize globally and use these inside if and keep adding your values;

o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();

Try this

ArrayList<String> o_aid= new ArrayList<String>();
    ArrayList<String> o_aproduct= new ArrayList<String>();
    ArrayList<String> o_aqty= new ArrayList<String>();
    ArrayList<String> o_atotal= new ArrayList<String>();



  private class fetchorder extends AsyncTask<Void, Void, Void> {



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected Void doInBackground(Void... args) {
        // Create an array
        try {
            arraylist = new ArrayList<HashMap<String, String>>();


            List<NameValuePair> params = new ArrayList<NameValuePair>();
//              params.add(new BasicNameValuePair("v_username", uid));
                JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);


            int success1 = Integer.parseInt(json.getString("success4"));
            Log.d("success4", json.toString());

            if (success1 == 0) {
                //  Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
            }
            if (success1 == 1) {

                ownerObj = json.getJSONArray("visit");

                for (int i = 0; i < ownerObj.length(); i++) {

                    jsonobject = ownerObj.getJSONObject(i);

                    o_aid.add(jsonobject.getString("o_id"));
                    o_aproduct.add(jsonobject.getString("o_product"));
                    o_aqty.add(jsonobject.getString("o_qty"));
                    o_atotal.add(jsonobject.getString("o_total"));
                }
            }

        }
        catch(Exception e)
        {
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml
        if (listadapter == null) {
            listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid,o_aproduct,o_aqty,o_atotal);
            listview.setAdapter(listadapter);
        } else {
            listadapter.notifyDataSetChanged();
        }

        // Close the progressdialog

        //          mProgressDialog.dismiss();
    }
}