php - JSON Android App, Retrieval of data issue

524

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);
?>
920

Answer

Solution:

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();
196

Answer

Solution:

CallnotifyDataSetChanged() on your adapter orinvalidateViews() on your listview.

Further reading: How to refresh Android listview?

People are also looking for solutions to the problem: PHP email click tracker tool

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.