superJen
superJen

Reputation: 63

Populating listview from database (localhost phpmyadmin)

I tried searching for similar questions but I cant find anything that fits in to what I am doing.. I'm trying to populate a listview from a database and whenever I run it, it doesn't display anything in the listview..

here is the logcat..

JSONException: Value {"message":"Patient Available","success":1,"post":[{"lname":"miradora doringo","address":"navotas, pilipinas","email":"tam.muqu23","age":"20","gender":"babae","remarks":"mabuting estudyante","patient_id":"6","contact":"361008762","fname":"jenelien"},{"lname":"andres","address":"manila","email":"[email protected]","age":"20","gender":"female","remarks":"trial","patient_id":"7","contact":"926644895","fname":"julie"}]} of type org.json.JSONObject cannot be converted to JSONArray

this is my Viewpatient.java:

public class Viewpatient extends ListActivity {

    private Button create;

    private ProgressDialog pDialog;

    private static final String READ_PATIENT_URL = "http://192.168.43.15:8080/DoctorScheduler/activities/viewpatient.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_POST    = "post";
    private static final String TAG_PATIENT = "patient_id";
    private static final String TAG_FNAME   = "fname";
    private static final String TAG_LNAME   = "lname";
    private static final String TAG_AGE     = "age";
    private static final String TAG_GENDER  = "gender";
    private static final String TAG_CONTACT = "contact";
    private static final String TAG_EMAIL   = "email";
    private static final String TAG_ADDRESS = "address";    
    private static final String TAG_REMARKS = "remarks";

    JSONParser jsonParser = new JSONParser();

    //array of all patient information by patient
    JSONArray Apatient = null;
    //manages all patient in a list
    ArrayList<HashMap<String, String>> ApatientList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewpatient);

        ApatientList = new ArrayList<HashMap<String, String>>();
        new LoadInformation().execute();

        ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                // TODO Auto-generated method stub
                // INSERT ALL PREVIOUS CONSULTATIONS OF THE PATIENT HERE
            }
        });

        create = (Button) findViewById(R.id.BtnAdd);
        create.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent createInfo = new Intent(Viewpatient.this, Viewupdate.class);
                startActivity(createInfo);
            }
        });

    };

    public class LoadInformation extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pDialog = new ProgressDialog(Viewpatient.this);
            pDialog.setMessage("Loading all patient information....");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);

        }

        @Override
        protected Void doInBackground(Void... args) {
            // TODO Auto-generated method stub
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // Making a request to url and getting response
            String json = jsonParser.getJSONFromURL(READ_PATIENT_URL, "POST", params);

            Log.d("Response: ", "> " + json);

            try {
                    Apatient = new JSONArray(json);
                    if (Apatient != null) {

                    // looping
                    for (int i = 0; i < Apatient.length(); i++) {
                        JSONObject c = Apatient.getJSONObject(i);

                        String patient_id = c.getString(TAG_PATIENT);
                        String fname = c.getString(TAG_FNAME);
                        String lname = c.getString(TAG_LNAME);
                        String age = c.getString(TAG_AGE);
                        String gender = c.getString(TAG_GENDER);
                        String contact = c.getString(TAG_CONTACT);
                        String email = c.getString(TAG_EMAIL);
                        String address = c.getString(TAG_ADDRESS);
                        String remarks = c.getString(TAG_REMARKS);

                        // tmp hashmap for single contact
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PATIENT, patient_id);
                        map.put(TAG_FNAME, fname);
                        map.put(TAG_LNAME, lname);
                        map.put(TAG_AGE, age);
                        map.put(TAG_GENDER, gender);
                        map.put(TAG_CONTACT, contact);
                        map.put(TAG_EMAIL, email);
                        map.put(TAG_ADDRESS, address);
                        map.put(TAG_REMARKS, remarks);

                        // adding contact to contact list
                        ApatientList.add(map);
                    }
                    } else {
                        Log.e("Error", "Couldn't get any data from the url");
                    }

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

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            //super.onPostExecute(result);
            pDialog.dismiss();

            runOnUiThread(new Runnable(){
            public void run(){
            ListAdapter adapter = new SimpleAdapter(
                    Viewpatient.this, ApatientList, R.layout.main,
                    new String[] { TAG_PATIENT, TAG_FNAME, TAG_LNAME, TAG_AGE,
                                   TAG_GENDER, TAG_CONTACT, TAG_EMAIL, TAG_ADDRESS, TAG_REMARKS },
                    new int[] { R.id.txtID, R.id.txtFName, R.id.txtLName, R.id.txtAge, R.id.txtGender,
                                R.id.txtContact, R.id.txtEmail, R.id.txtAddress, R.id.txtRemarks});

            setListAdapter(adapter);
            }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.viewpatient, menu);
        return true;
    }

}

this my JSONParser.java:

public class JSONParser {

    //new
    static String response = null;

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    //constructor

    public JSONParser(){

    }

    public String getJSONFromURL(String url, String method,
            List<NameValuePair> params){

        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == "POST") {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == "GET") {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }
}

and this is my viewpatient.php:

    <?php

require ("../config.inc.php");

    $query = "Select * From patientinfo";

    try{
        $stmt = $dbname->prepare($query);
        $result = $stmt->execute(); 

    }catch(PDOException $ex){
            $response["success"] = 0;
            $response["message"] = "Database Error!";

            die(json_encode($response));
        }

    //retrieve all the rows
    $rows = $stmt->fetchAll();

    if($rows){
        $response["success"] = 1;
        $response["message"] = "Patient Available";
        $response["post"] = array();

        foreach($rows as $row){
            $post               = array();
            $post["patient_id"] = $row["patient_id"];
            $post["fname"]      = $row["fname"];
            $post["lname"]      = $row["lname"];
            $post["age"]        = $row["age"];
            $post["gender"]     = $row["gender"];
            $post["contact"]    = $row["contact"];
            $post["email"]      = $row["email"];
            $post["address"]    = $row["address"];
            $post["remarks"]    = $row["remarks"];

            //update json response
            array_push($response["post"], $post);
            }

        echo json_encode($response);
    }
    else{
        $response["success"] = 0;
        $response["message"] = "No available patient information";

        die(json_encode($response));

    }
?>

Upvotes: 1

Views: 766

Answers (1)

Hbibna
Hbibna

Reputation: 568

You should change this part Apatient = new JSONArray(json);
Create a JSONObject JSONObject ApatientObject = new JSONObject(json);
Then get your JSONArray from there like this :
Apatient = new JSONArray(ApatientObject.getJSONArray("post"))

The problem is that the response you receive from the server is a JSONObject, not a JSONArray. The JSONObject contains 2 Strings, "message" and "success", and also contains a JSONArray "post" which holds the data you are looking for.

EDIT:
If you're only retreiving data from the server then it can be useful to think in terms of using GET for retrieving / viewing information and POST for creating / editing information as mentioned here:
When do you use POST and when do you use GET?

Upvotes: 1

Related Questions