0

I have been searching for a way to get the "values" from the database and insert them in JSON Response to an android application that receives ID ,Name and Email from PHP file ID , Name , Email needs to be taken from database then sent as JSON response to Android Application here is my code and PHP file if you please tell me how to edit the PHP file so that it sends JSON with variables taken from database

MainActivity

package learn2crack.asynctask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import learn2crack.asynctask.library.JSONParser;

public class MainActivity extends Activity {
    TextView uid;
    TextView name1;
    TextView email1;
    Button Btngetdata;

    //URL to get JSON Array
    private static String url = "http://10.0.2.2/JSON/";

    //JSON Node Names 
    private static final String TAG_USER = "user";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";

    JSONArray user = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                 new JSONParse().execute();

            }
        });

    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
         private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
             uid = (TextView)findViewById(R.id.uid);
             name1 = (TextView)findViewById(R.id.name);
             email1 = (TextView)findViewById(R.id.email);
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }
         @Override
         protected void onPostExecute(JSONObject json) {
             pDialog.dismiss();
             try {
                    // Getting JSON Array
                    user = json.getJSONArray(TAG_USER);
                    JSONObject c = user.getJSONObject(0);

                    // Storing  JSON item in a Variable
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String email = c.getString(TAG_EMAIL);

                    //Set JSON Data in TextView
                    uid.setText(id);
                    name1.setText(name);
                    email1.setText(email);

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

         }
    }

}

And PHP File

{
"user": [
{
"id": "001",
"name": "Raj Amal",
"email": "[email protected]"
}
]
}

I Want it to be like this taking everything and assigning them to variable that i will call them later in android application

 <?php

    $con=mysqli_connect("localhost","root","123","pet_home");
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

   $result = mysqli_query($con,"SELECT * FROM users WHERE username='test' AND password='123'");
    $row_cnt = mysqli_num_rows($result);

     if($row_cnt>0){     
         $row = mysqli_fetch_array($result); 
         $data = array('success'=>true, 'user'=>array("TAG_ID" => $row['id'], "TAG_NAME"=> $row['name'], "TAG_EMAIL" =>$row['email'])); 
     }else{
         $data = array('success'=>false);
     }

header('Content-Type: application/json');
   echo json_encode($data);



    mysqli_close($con);


    ?>

After doing this no response comes back to android app Here is stacktrace seems like there is an exception

11-30 13:02:20.066: W/System.err(2854): org.json.JSONException: Value {"id":"OFF","TAG_EMAIL":"OFF","name":"OFF"} at user of type org.json.JSONObject cannot be converted to JSONArray
11-30 13:02:20.066: W/System.err(2854):     at org.json.JSON.typeMismatch(JSON.java:100)
1
  • You might need to set content type header to 'application/json' before php output, something like header(....) and you can just use echo json_encode($user) Commented Nov 30, 2013 at 12:14

1 Answer 1

1

Can you try this, based on the success true or false you have check like user exist or not

    $result = mysqli_query($con,"SELECT * FROM users WHERE username='test' AND password='123'");
    $row_cnt = mysqli_num_rows($result);

     if($row_cnt>0){     
         $row = mysqli_fetch_array($result); 
         $data = array('success'=>true, 'user'=>array("TAG_ID" => $row['id'], "TAG_NAME"=> $row['name'], "TAG_EMAIL" =>$row['email'])); 
     }else{
         $data = array('success'=>false);
     }
   echo json_encode($data);
Sign up to request clarification or add additional context in comments.

9 Comments

and set the HTTP header
thanks in advance i tried it but no response comes back and please hRoved tell what to do you mean by setting the HTTP header ?
Can you run this PHP file in browser and check what is the response you get from browser
there is no data in users table, can you in your table w
just checked username exist and password matches
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.