-1

My problem is this, i have a list view that contains all the records, when there is only 1 record left, and i try to delete it, the record is deleted in the PHP file, BUT in the list view, it is still there, can anyone check my code?

here is the code where i populate the ListView

public class MainActivity extends AppCompatActivity {

    String id,name,course;
    JSONArray students = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new JSONParse().execute();
    }

    @Override
    protected void onResume() {
        super.onResume();
        new JSONParse().execute();
    }

    private class JSONParse extends AsyncTask<String,String,JSONObject>{
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected JSONObject doInBackground(String... params) {
            JSONParser jParser = new JSONParser();
            JSONObject json = null;
            try {
                json = jParser.getJSONFromUrl("http://192.168.8.102/mymobile/getstudentlist.php");
            }
            catch(Exception e){
                e.printStackTrace();
            }
            return json;
        }
        @Override
        protected void onPostExecute(JSONObject json) {
            super.onPostExecute(json);
            pDialog.dismiss();
            final ArrayList<String> ids = new ArrayList<String>();
            final ArrayList<String> names = new ArrayList<String>();
            final ArrayList<String> courses = new ArrayList<String>();
            try{
                if(!(json.getJSONArray("students").isNull(0))) {
                    students = json.getJSONArray("students");
                    for (int i = 0; i < students.length(); i++) {
                        JSONObject student = students.getJSONObject(i);
                        ids.add(student.getString("id"));
                        names.add(student.getString("name"));
                        courses.add(student.getString("course"));
                    }
                    final ListView listView = (ListView) findViewById(R.id.list);
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>
                            (MainActivity.this, android.R.layout.simple_list_item_1,
                                    android.R.id.text1, names);

                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            String stud_id = ids.get(position);
                            String stud_name = names.get(position);
                            String stud_course = courses.get(position);

                            Intent i = new Intent(MainActivity.this, ActivityEditDel.class);
                            i.putExtra("stud_id", stud_id);
                            i.putExtra("stud_name", stud_name);
                            i.putExtra("stud_course", stud_course);
                            i.putExtra("stud_course", stud_course);
                            startActivity(i);
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (NullPointerException e){
                e.printStackTrace();
            }
        }
    }

and this is the php file where that i am using to retrieve the data and parse it into a json object.

<?php

$database_name = 'dbstudrec';
$con = mysqli_connect('localhost', 'root', '',$database_name);
$query = "SELECT * FROM tblstudent";
$result = mysqli_query($con,$query);
$rec = array();
while($row = mysqli_fetch_assoc($result)){
    $rec['students'][] = $row;
}
echo json_encode($rec);
mysqli_close($con);
?>

i added a try and catch on the code block where i am trying to get the jsonarray because when the jsonobject is empty, the app crashes. [EDIT]

edit and delete activity:

public class ActivityEditDel extends Activity{
    TextView tvId;
    EditText etName, etCourse;
    String strId, strName, strCourse;
    boolean isDeleteAction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.updatendeleteview);
        tvId = (TextView) findViewById(R.id.tvId);
        etName = (EditText) findViewById(R.id.etName);
        etCourse = (EditText) findViewById(R.id.etCourse);

        Intent i = getIntent();

        strId = i.getStringExtra("stud_id");
        strName = i.getStringExtra("stud_name");
        strCourse = i.getStringExtra("stud_course");

        tvId.setText(strId);
        etName.setText(strName);
        etCourse.setText(strCourse);

        isDeleteAction = false;
    }
    public void doUpdate(View v){
        isDeleteAction=false;
        new JSONParse().execute();
    }
    public void doDelete(View v){
        isDeleteAction = true;
        new JSONParse().execute();
    }
    private class JSONParse  extends AsyncTask<String,String,JSONObject>{
        private ProgressDialog pDialog;
        private Dialog aDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ActivityEditDel.this);
            if(isDeleteAction){
                pDialog.setMessage("Deleting Record...");
            }
            else{
                pDialog.setMessage("Updating Record...");
            }
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected JSONObject doInBackground(String... params) {
            JSONParser jParser = new JSONParser();
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id",strId));
            nameValuePairs.add(new BasicNameValuePair("name", etName.getText().toString()));
            nameValuePairs.add(new BasicNameValuePair("course", etCourse.getText().toString()));
            if(isDeleteAction){
                jParser.runQuery("http://192.168.1.101/mymobile/deleterec.php", nameValuePairs);
            }
            else{
                jParser.runQuery("http://192.168.1.101/mymobile/updaterec.php", nameValuePairs);
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            pDialog.dismiss();
            if (isDeleteAction){
                aDialog = new Dialog(ActivityEditDel.this);
                aDialog.setTitle("Message");
                TextView tv = new TextView(ActivityEditDel.this);
                tv.setText("Delete Successful!");
                tv.setPadding(30, 30, 30, 30);
                aDialog.setContentView(tv);
                aDialog.show();
                aDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        finish();
                    }
                });

            }
            else{
                aDialog = new Dialog(ActivityEditDel.this);
                aDialog.setTitle("Message");
                TextView tv = new TextView(ActivityEditDel.this);
                tv.setText("Update Successful!");
                tv.setPadding(30,30,30,30);
                aDialog.setContentView(tv);
                aDialog.show();
                aDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        finish();
                    }
                });

            }
        }
    }
    public void doBack(View v){
        finish();
    }
}

php file for delete:

<?php
$database_name = 'dbstudrec';
$con = mysqli_connect('localhost', 'root', '',$database_name);
$id = $_POST['id'];
$query = "DELETE FROM tblstudent WHERE id = $id";
mysqli_query($con,$query);
mysqli_close($con);
?>
Ralph Macalino
  • 121
  • 1
  • 4
  • 13
  • after deleting it in PHP you have to parse the data again. list view data is not updated automatically. It will show the previous data only. – Sharad Chauhan May 18 '16 at 11:20
  • after deleting are you calling `notifyDataSetChanged();` in listview – Iamat8 May 18 '16 at 11:21
  • @sharadchauhan but why is it that when i add after deleting the last entry, the last entry is replaced with the one i added? – Ralph Macalino May 18 '16 at 11:21
  • try doing what Mohit has written. – Sharad Chauhan May 18 '16 at 11:25
  • @Mohit is that the same with deferNotifyDataSetChanged(); ? because i can't see that one and regarding on that one, the editing part is on a new activity so maybe i should put that function in the onResume part? – Ralph Macalino May 18 '16 at 11:27
  • @RalphMacalino it also sounds like you have two separate questions here. First, the one regarding the listview updating, which we answered & the second regarding the JSON object being empty. When it is empty? Are you making a second call to this file? If you are and then the JSON object is empty, you may want to add a null check. – Daniel May 18 '16 at 11:31
  • sorry i didnt get you...what do you mean by *i can't see that one and regarding on that one* – Iamat8 May 18 '16 at 11:31
  • @Mohit was talking about the function you said, i have found it in the adapter but i don't know how i could apply it. – Ralph Macalino May 18 '16 at 11:33
  • can you show from where you are deleting the row/data...? – Iamat8 May 18 '16 at 11:35
  • your listview is in `MainActivity` and you are deleting data from `ActivityEditDel` right ? if yes then you need to fetch data again when you are coming back to your `MainActivity` i.e I would suggest to call `new JSONParse().execute();` when your activity popup back... – Iamat8 May 18 '16 at 11:55
  • You mean on the onresume part? i have already done that one. @Mohit – Ralph Macalino May 18 '16 at 11:58
  • Are you asking why the app crashes when you re-execute the `ASyncTask`? If the data is empty at that point then the `JSON` would return `null` & you would get a `NullPointerException`. If you want to prevent that crash, just add a `null` check. – Daniel May 18 '16 at 12:01
  • @RalphMacalino have to check whether `onResume` your `new JSONParse().execute();` is called or not ? – Iamat8 May 18 '16 at 12:03
  • @Daniel resolved that one with if(!(json.getJSONArray("students").isNull(0))) – Ralph Macalino May 18 '16 at 12:05
  • @RalphMacalino just put a breakpoint at onResume method and check if it stop at `.execute()`....and yes you can try calling `.execute()` method at `onStart()` also incase of try..by the way does it produce some error or warning at LOGCAT – Iamat8 May 18 '16 at 12:11

2 Answers2

1

Call notifyDataSetChanged() on your adapter or invalidateViews() on your listview.

Further reading: How to refresh Android listview?

Community
  • 1
  • 1
Daniel
  • 2,355
  • 9
  • 23
  • 30
1

try to use

final ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,android.R.id.text1, names);
listView.setAdapter(adapter);
((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();

or

adapter.notifyDataSetChanged();
maxhb
  • 8,554
  • 9
  • 29
  • 53
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62