retrieve data using json in android - android

I need to display the result in android text view that I obtained by json result. I only get the success message when I run the app. I want to get the textview displayed.
Java Code:
JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} 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 product deleted
pDialog.dismiss();
try {
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP Code:
<?php
require('config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
// $user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="test.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>

sorry can't comment but what you getting at post execute from background task is file_url as string which is your param at on post execute......i think if you are getting result all params like first name ,lastName etc then you needed to pass jsonObject at onpost Execute
so you can parse at onPostExecute...your jsonResult and display it in textbox
Problem is in you current code is
txtFname.setText("Firstname: " + firstname);
in which firstName is from
String firstname = jb.getString("firstname");
JSONObject jb= user.getJSONObject(0);
JSONArray user = hay.getJSONArray("user");
JSONObject hay = new JSONObject ((Map) json);
JSONObject json = null;
i have reversed it so you can find problem here json is null so here is problem and pls try logging at each point and let we know so we and you can have exact idea....or give us json format...

the problem is with your this code segment:
JSONObject json = null;
JSONObject hay = new JSONObject((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
here what you are doing is: making another JSONObject as
JSONObject json = null;
that is creating a variable with local scope, the local variable will have more priority than global, that you understood. actually you need the json which is created from doInBackgrounnd(). so pass the json from doInBackground to onPostExecute: it is simple,
change the statements:
return json.getString(TAG_MESSAGE); => return json;
return json.getString(TAG_MESSAGE); => return json;
also change the type of doInBackground to JSONObject and avoid making a new local JSONObject and trying to get datafrom that (bcz it is null you initialized with).
JSONObject json = null; //remove this
JSONObject hay = new JSONObject((Map) json); //remove this
JSONArray user = hay.getJSONArray("user"); // change hay to json
also change the
protected void onPostExecute(String file_url)// to protected void onPostExecute(JSONObject json)
EDIT 2
here is your changed code, let me know what you are getting if some errors.
//edited1
public static JSONObject json = null;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "////////////////////// "; // change to the webhost
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER = "user";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setup input fields
user = (EditText) findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
//setup buttons
get = (Button) findViewById(R.id.get);
//register listeners
get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", username));
Log.d("request!", "starting");
// getting product details by making HTTP request
// edited2
json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//
//Intent i = new Intent(Login.this, MainActivity.class);
//finish();
//startActivity(i);
//finish();
//edited3
return json.getString(TAG_MESSAGE);
//return json;
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
//edited4
return json.getString(TAG_MESSAGE);
//return json;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String message) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
//JSONObject json = null;
//JSONObject hay = new JSONObject((Map) json);
JSONArray user = json.getJSONArray("user");
JSONObject jb = user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (Exception e) {
e.printStackTrace();
}
if (file_url != null) {
Toast.makeText(MainActivity.this, json.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}
}
did four changes in total: mentioned as edited# wherever I did. please fins them and make it in your file,

Related

How to Insert data in a remote mysql database using in android which has a Spinner control

Please am having a "failed to insert" error sending data from my android app to a remote mysql database. It has a Spinner control. I'm calling an api on the remote server to to the insert, but it fails to insert.
Below is My Main Activity code
public class RCrimeActivity extends AppCompatActivity implements View.OnClickListener{
private EditText nop, wh;
private Button bReport;
private Spinner ct;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://www.nigeriacrimewatch.com/ncwrcapi.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rcrime);
nop = (EditText) findViewById(R.id.nop);
wh = (EditText) findViewById(R.id.wh);
ct = (Spinner) findViewById(R.id.ct);
bReport = (Button) findViewById(R.id.btnReport);
bReport.setOnClickListener(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homescr = new Intent(RCrimeActivity.this, MainActivity.class);
startActivity(homescr);
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnReport:
new AttemptReport().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case. default:
default:
break;
}
}
class AttemptReport extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog *
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RCrimeActivity.this);
pDialog.setMessage("Reporting crime...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// here check for success tag
int success;
String name = nop.getText().toString();
String address = wh.getText().toString();
String type = ct.getSelectedItem().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nop", name));
params.add(new BasicNameValuePair("wh", address));
params.add(new BasicNameValuePair("ct", type));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Report attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Crime Reported!", json.toString());
Intent ii = new Intent(RCrimeActivity.this, MapActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap *
**/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null) {
Toast.makeText(RCrimeActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}
API Code
<?php
error_reporting(E_ALL);
ini_set('display_errors',TRUE);
include_once "conn/nconn.php";
$username=$_POST["username"]; $email=$_POST["email"];
$password=$_POST["password"];
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0; $response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also //display the parameter, that is the json data which our android application will parse to be //shown to the users
die(json_encode($response));
}
$query = " INSERT INTO gmusers (username, email, password, created) values ('$username','$email','$password', now())";
$sql1=mysql_query($query); if (!empty($sql1)) { $response["success"] = 1;
$response["message"] = "Registered sucessfully"; die(json_encode($response));
} else{
$response["success"] = 0; $response["message"] = "Failed to register";
die(json_encode($response));
}
} else{
$response["success"] = 0; $response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
?>

Detail view of listview

Here is my async task.i want display the detailview of a listview click.there is some error in displaying data in text view.i know we cant access UI inside doInBackground.i dont know how to do in OnpostExecute.help me
class Enquiryview extends AsyncTask<String, Void, JSONObject> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EnquiryDetail.this);
// pDialog.setMessage("Loding...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected JSONObject doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_address_detail.php?user_id="+ userid1+"";
final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_enq_detail.php?ser_enq_id="+ enq_id+"";
System.out.println(URL_LIST);
JSONParser jsonParser = new JSONParser();
final JSONObject json = jsonParser.getJSONFromUrl(URL_LIST, get, params);
System.out.println("enq----do in ---"+json);
try {
String res = json.getString(KEY_SUCCESS);
System.out.println("enq---------------is"+enq_id);
int res1 = Integer.parseInt(res);
if (res1 == 1) {
// String res = json.getString(KEY_SUCCESS);
//System.out.println(res);
JSONObject jsonObject = json.getJSONObject("detail");
// setListAdapter(mAdapter);
// JSONArray json1=new JSONArray("data");
//Log.d("Address JSON: ", "> " + albums);
// Storing each json item values in variable
final String enqid = jsonObject.getString(ENQID);
String enqdate = jsonObject.getString(ENQ_DATE);
String status = jsonObject.getString(STATUS);
String usc = jsonObject.getString(USC);
String amount = jsonObject.getString(AMOUNT);
String address = jsonObject.getString(ENQ_ADDRESS);
String city = jsonObject.getString(CITY);
String state = jsonObject.getString(STATE);
System.out.println(enqid);
System.out.println(enqdate);
System.out.println(usc);
System.out.println(address);
System.out.println(city);
System.out.println(state);
// service.setText();
amounttext.setText(amount);
//exname.setText();
statustext.setText(status);
addresstext.setText(address);
citytext.setText(city);
statetext.setText(state);
//billno.setText();
usctext.setText(usc);
date.setText(enqdate);
enqidtext.setText(enqid);
}
else
{
Log.d("Addressssssssssssssssssssssssssssssssss: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
protected void onPostExecute(final JSONObject json1) {
// check for login response
/// System.out.println("enq----on post ---"+json);
pDialog.dismiss();
// Check your log cat for JSON reponse
}
class Enquiryview extends AsyncTask<String, Void, JSONObject> {
final JSONObject json;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EnquiryDetail.this);
// pDialog.setMessage("Loding...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected JSONObject doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_address_detail.php?user_id="+ userid1+"";
final String URL_LIST = "http://staging.homeneedsonline.com/ws/ws_enq_detail.php?ser_enq_id="+ enq_id+"";
System.out.println(URL_LIST);
JSONParser jsonParser = new JSONParser();
json = jsonParser.getJSONFromUrl(URL_LIST, get, params);
return null;
}
protected void onPostExecute(final JSONObject json1) {
// check for login response
/// System.out.println("enq----on post ---"+json);
System.out.println("enq----do in ---"+json);
try {
String res = json.getString(KEY_SUCCESS);
System.out.println("enq---------------is"+enq_id);
int res1 = Integer.parseInt(res);
if (res1 == 1) {
// String res = json.getString(KEY_SUCCESS);
//System.out.println(res);
JSONObject jsonObject = json.getJSONObject("detail");
// setListAdapter(mAdapter);
// JSONArray json1=new JSONArray("data");
//Log.d("Address JSON: ", "> " + albums);
// Storing each json item values in variable
final String enqid = jsonObject.getString(ENQID);
String enqdate = jsonObject.getString(ENQ_DATE);
String status = jsonObject.getString(STATUS);
String usc = jsonObject.getString(USC);
String amount = jsonObject.getString(AMOUNT);
String address = jsonObject.getString(ENQ_ADDRESS);
String city = jsonObject.getString(CITY);
String state = jsonObject.getString(STATE);
System.out.println(enqid);
System.out.println(enqdate);
System.out.println(usc);
System.out.println(address);
System.out.println(city);
System.out.println(state);
// service.setText();
amounttext.setText(amount);
//exname.setText();
statustext.setText(status);
addresstext.setText(address);
citytext.setText(city);
statetext.setText(state);
//billno.setText();
usctext.setText(usc);
date.setText(enqdate);
enqidtext.setText(enqid);
}
else
{
Log.d("Addressssssssssssssssssssssssssssssssss: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ;
}
pDialog.dismiss();
// Check your log cat for JSON reponse
}
Try this
You need to return JsonObject from doInBackground method and whatever json parsing you are doing the doInBackground you need to move it to the onPostExecute() method.
Let me know if it helps you

Displaying data in textview through json

I want to display user details from mysql database through php and display it in android textview. The scenario is like this: When the user logged in to his account he will be redirected to the dashboard which contains of 4 buttons namely: newsfeed, profile, calendar and about. When the user clicks the profile button the user details like his lastname, firstname, middleinitial etc will be displayed in the textview. When i run my app, it doesnt display anything but in my php script it returns the user details. What seems to be the problem here?
Here is my java code:
package sscr.stag;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;
public class AdProfile extends Activity {
// All xml labels
TextView txtFname;
TextView txtMname;
TextView txtLname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject hay;
// Profile JSON url
private static final String PROFILE_URL ="http://www.stagconnect.com/StagConnect/admin/TestProfile.php";
// ALL JSON node names
private static final String TAG_PROFILE = "user";
// private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_FIRSTNAME = "first_name";
private static final String TAG_MIDDLENAME = "middle_initial";
private static final String TAG_LASTNAME = "last_name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adminprofile);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.mname);
txtLname = (TextView) findViewById(R.id.lname);
// Loading Profile in Background Thread
new LoadProfile().execute();
}
class LoadProfile extends AsyncTask<String, String, String> {
public void test(){
hay = new JSONObject();
// Storing each json item in variable
try {
String firstname = hay.getString(TAG_FIRSTNAME);
String middlename = hay.getString(TAG_MIDDLENAME);
String lastname = hay.getString(TAG_LASTNAME);
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AdProfile.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.this);
String post_username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
params);
// Check your log cat for JSON reponse
Log.d("Profile JSON: ", json.toString());
try {
// profile json object
user = json.getJSONArray(TAG_PROFILE);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
test();
}
}
}
And here is my php script:
<?php
require('admin.config.inc.php');
if (!empty($_POST)) {
//initial query
$query = "Select last_name, first_name, middle_initial, designation FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();
foreach($rows as $row) {
$user = array();
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["user"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
<form action="TestProfile.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
Here the output of my php script(JSON Response):
{"success":1,"message":"Post Available!","user":[{"designation":"Student Affairs Office in charge","middlename":"","firstname":"test","lastname":"test"}]}
This is the json object
JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
params);
You need to return json in doInbackground. The result returned is param to onPostExecute
Then
test(json);
And then in test you can parse the json
Edit:
You would also need to change
AsyncTask<String, String, String>
to
AsyncTask<String, String, JSONObject>
Then
protected JSONObject doInBackground(String... args) {
JSONObject json=null;
// Building Parameters
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(AdProfile.this);
String post_username = sp.getString("username", "anon");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
// getting JSON string from URL
json = jsonParser.makeHttpRequest(PROFILE_URL, "POST",
params);
// Check your log cat for JSON reponse
Log.d("Profile JSON: ", json.toString());
try {
// profile json object
user = json.getJSONArray(TAG_PROFILE);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
Then in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPOstExecute(result);
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
test(result);
}
In test
public void test(JSONObject response){
{
// parse response here and set text to textview
}
Or
Do you parsing in doInbackgrond update textview in onPostExecute
Edit:
Code:
public class AddProfile extends Activity {
// All xml labels
TextView txtFname;
TextView txtMname;
TextView txtLname;
// Progress Dialog
private ProgressDialog pDialog;
// Profile json object
JSONArray user;
JSONObject hay;
// Profile JSON url
private static final String PROFILE_URL = "http://www.stagconnect.com/StagConnect/admin/TestProfile.php";
// ALL JSON node names
private static final String TAG_PROFILE = "user";
// private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_FIRSTNAME = "first_name";
private static final String TAG_MIDDLENAME = "middle_initial";
private static final String TAG_LASTNAME = "last_name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adminprofile);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);
// Loading Profile in Background Thread
new LoadProfile().execute();
}
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddProfile.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "admin"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try
{
hay = new JSONObject(json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");
// displaying all data in textview
txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
The json
{ // json object node
"success": 1,
"message": "Post Available!",
"user": [ // json array user
{ // json object node
"designation": "Student Affairs Office in-charge",
"middlename": "",
"firstname": "Jose Patrick",
"lastname": "Ocampo"
}
]
}
Browser snap shot
First of all the method that will do the parsing should have a parameter with the string
Let s say parseFromPhp (String response)
Your json object also contain an inner Json Object that is "user":[{"designation":"Student Affairs Office in- charge","middlename":"","firstname":"test","lastname":"test"}]}
For parse this you will do
JSONObject jsonRespone = new JSONObject(response);
JSONObject user= jsonRespone.getJSONObject("user");
String lastName = user.optString ("lastName");
If you want to get the message you will do like this :
String message= jsonResponse.optString ("message");
DO THIS In
doInBackground() method
try {
// profile json object
user = json.getJSONArray(TAG_PROFILE);
for (int i = 0; i < user.length(); i++)
{
JSONObject FObject = json.getJSONObject(i);
hay = FObject.getJSONObject("user");
}
} catch (JSONException e) {
e.printStackTrace();
}
And then remove this in test()
hay = new JSONObject();

Android & WAMP: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

Hi I'm reading a lot at the moment about connecting my Android Device to a WAMP Server but whit this tutorial I'm getting an annoying error regarding JSON. I use Json to tranfers messages between the server and the device.
It says : Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
Basically I have 2 methods in my main activity. In one I show my databse and in the other one I insert items in the database.
Here are some parts of the code that could be interesting.
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.36/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
Insert Item
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.1.36/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
}
PHP
$response = array();
include db connect class
require_once __DIR__ . '/db_connect.php';
connecting to db
$db = new DB_CONNECT();
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM products WHERE pid = $pid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["name"] = $result["name"];
$product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product 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);
}
?>
Edit: Insert Product
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
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);
}
?>
As I said, the thing is that Value <br is quite strange
Thanks in advance and for your time.
I had this problem too. in my case its related to the JSONObject. you read data from the database and store them in json object. but you have to pass it as a string. consider that i have a JSONObject named json and i am using it to store strings red from table.then i use json.tostring to convert it to string and pass it to other object to use at the return statement so when i return the object a string is returned not an object. this worked for me.
jObj = new JSONObject(json.toString());

I can't retrieve data from Mysql database to Android application

i'm having a problem with my application 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 this is the PHP code:
<?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 when i try to retrieve the data from Mysql database?
Thank you.
There is a missing space in your SQL query. It should be SELECT * FROM student WHERE sid = $sid

Categories

Resources