4 Replies - 3951 Views - Last Post: 12 November 2012 - 01:04 PM

#1 androidfan  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 12-November 12

Problem with retrieving data from Mysql database to android

Posted 12 November 2012 - 06:10 AM

Hi,
i'm having a problem trying to retrieve data from mysql database. when i run the application i get a message that I've created in the php code saying "student not found".

Here is the java code:
public class StudentEditAccount extends Activity {
    EditText txtsid;
    EditText txtfirstname;
    EditText txtlastname;
    EditText txtcoursecode;
    EditText txtphonenumber;
    EditText txtemail;

    Button btnSave;
    Button btnDelete;

    String sid;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    // single student url
    private static final String url_product_detials = "http://10.0.2.2/example/get_product_details.php";

    // url to update student
    private static final String url_update_product = "http://10.0.2.2/example/update_product.php";

    // url to delete student
    private static final String url_delete_product = "http://10.0.2.2/example/delete_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_STUDENTS = "students";
    private static final String TAG_SID = "sid";
    private static final String TAG_FIRSTNAME = "firstname";
    private static final String TAG_LASTNAME = "lastname";
    private static final String TAG_COURSECODE = "coursecode";
    private static final String TAG_PHONENUMBER = "phonenumber";
    private static final String TAG_EMAIL = "email";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.studenteditaccount);

        // save button
        btnSave = (Button) findViewById(R.id.btnSave);
        btnDelete = (Button) findViewById(R.id.btnDelete);

        // getting student details from intent
        Intent i = getIntent();

        // getting student id (id) from intent
        sid = i.getStringExtra(TAG_SID);

        // Getting complete student details in background thread
        new GetStudentAccountDetails().execute();


        // save button click event
        btnSave.setonclickListener(new View.onclickListener() {

            public void onclick(View v) {
                // starting background task to update student
                    new SaveStudentAccountDetails().execute();

            }
        });

        // Delete button click event
        btnDelete.setonclickListener(new View.onclickListener() {

            public void onclick(View v) {
                // deleting student in background thread
                    new DeleteStudentAccount().execute();

            }
        });
    }

    /**
     * Background Async Task to Get complete student details
     * */
    class GetStudentAccountDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(StudentEditAccount.this);
            pDialog.setMessage("Loading account details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting student details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("sid", sid));

                        // getting student details by making HTTP request
                        // Note that student details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_product_detials, "GET", params);

                        // check your log for json response
                        Log.d("Single student Details", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received student details
                            JSONArray studentsObj = json
                                    .getJSONArray(TAG_STUDENTS); // JSON Array

                            // get first student object from JSON Array
                            JSONObject students = studentsObj.getJSONObject(0);

                            // student with this sid found
                            // Edit Text
                            txtfirstname = (EditText) findViewById(R.id.inputfname);
                            txtlastname = (EditText) findViewById(R.id.inputlname);
                            txtcoursecode = (EditText) findViewById(R.id.inputcoursecode);
                            txtphonenumber = (EditText) findViewById(R.id.inputphonenumber);
                            txtemail = (EditText) findViewById(R.id.inputemail);



                            // display student data in EditText
                            txtfirstname.setText(students.getString(TAG_FIRSTNAME));
                            txtlastname.setText(students.getString(TAG_LASTNAME));
                            txtcoursecode.setText(students.getString(TAG_COURSECODE));
                            txtphonenumber.setText(students.getString(TAG_PHONENUMBER));
                            txtemail.setText(students.getString(TAG_EMAIL));


                        }else{
                            // student with sid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }

    /**
     * Background Async Task to  Save student Details
     * */
    class SaveStudentAccountDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(StudentEditAccount.this);
            pDialog.setMessage("Saving account ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Saving student
         * */
        protected String doInBackground(String... args) {

            // getting updated data from EditTexts
            String sid = txtsid.getText().toString();
            String firstname = txtfirstname.getText().toString();
            String lastname = txtlastname.getText().toString();
            String coursecode = txtcoursecode.getText().toString();
            String phonenumber = txtphonenumber.getText().toString();
            String email = txtemail.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_SID, sid));
            params.add(new BasicNameValuePair(TAG_FIRSTNAME, firstname));
            params.add(new BasicNameValuePair(TAG_LASTNAME, lastname));
            params.add(new BasicNameValuePair(TAG_COURSECODE, coursecode));
            params.add(new BasicNameValuePair(TAG_PHONENUMBER, phonenumber));
            params.add(new BasicNameValuePair(TAG_EMAIL, email));

            // sending modified data through http request
            // Notice that update student url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                    "POST", params);

            // check json success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about student update
                    setResult(100, i);
                    finish();
                } else {
                    // failed to update student
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once student updated
            pDialog.dismiss();
        }
    }

    /*****************************************************************
     * Background Async Task to Delete Product
     * */
    class DeleteStudentAccount extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(StudentEditAccount.this);
            pDialog.setMessage("Deleting Account...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Deleting student
         * */
        protected String doInBackground(String... args) {

            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("sid", sid));

                // getting student details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_product, "POST", params);

                // check your log for json response
                Log.d("Delete student", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // student successfully deleted
                    // notify previous activity by sending code 100
                    Intent i = getIntent();
                    // send result code 100 to notify about student deletion
                    setResult(100, i);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once student deleted
            pDialog.dismiss();

        }

    }
}


And the following is PHP code for database:

<?php

 // array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_GET["sid"])) {
    $sid = $_GET['sid'];

    // get a students from student table
    $result = mysql_query("SELECT * FROM student WHERE sid = $sid");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);

            $students = array();
            $students["sid"] = $result["sid"];
            $students["firstname"] = $result["firstname"];
            $students["lastname"] = $result["lastname"];
            $students["coursecode"] = $result["coursecode"];
            $students["phonenumber"] = $result["phonenumber"];
            $students["email"] = $result["email"];
            // success
            $response["success"] = 1;

            // user node
            $response["students"] = array();

            array_push($response["students"], $students);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no student found
            $response["success"] = 0;
            $response["message"] = "No student found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no student found
        $response["success"] = 0;
        $response["message"] = "No student found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>



my question is: what is the problem that cause the application to display the message "Student not found" every time i try to retrieve the data from Mysql database?
Thank you.

Is This A Good Question/Topic? 0
  • +

Replies To: Problem with retrieving data from Mysql database to android

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10440
  • View blog
  • Posts: 38,668
  • Joined: 27-December 08

Re: Problem with retrieving data from Mysql database to android

Posted 12 November 2012 - 06:16 AM

Moved to Android.

What ID are you receiving on the PHP end? Are you sure that it is in the database? Also, you should consider using Prepared Statements like PDO over the (practically) deprecated mysql_*() family of functions. Prepared Statements sanitize against SQL Injection attacks.
Was This Post Helpful? 0
  • +
  • -

#3 androidfan  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 12-November 12

Re: Problem with retrieving data from Mysql database to android

Posted 12 November 2012 - 06:43 AM

@macosxnerd101 thank you for your reply, the primary key for the table is 'sid' and i'm sure it's in the database.
may i know what is PDO statement? sorry i'm still new to the development :)
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10440
  • View blog
  • Posts: 38,668
  • Joined: 27-December 08

Re: Problem with retrieving data from Mysql database to android

Posted 12 November 2012 - 07:01 AM

http://www.dreaminco...duction-to-pdo/
Was This Post Helpful? 0
  • +
  • -

#5 TheGDeveloper  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 93
  • Joined: 22-September 09

Re: Problem with retrieving data from Mysql database to android

Posted 12 November 2012 - 01:04 PM

jsut debug and see what is the value of sid before the execution of the query.

ps it is not an android problem
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1