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();
Related
I am working on an android app. I want the app to select randomly a name from json.
Here is the json :
{
"user": [
{
"id": "001",
"name": "Raj Amal",
"email": "raj.amalw#gmail.com"
},
{
"id": "002",
"name": "Raj",
"email": "amalw#gmail.com"
}
]
}
And here is my android code :
public class MainActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://weblink/json/index.php";
//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();
}
}
}`
I would that when I presse the button a random name shows and loops.
Please help
Thank you
Change JSONObject c = user.getJSONObject(0); by this line ->
JSONObject c = user.getJSONObject(new Random().nextInt(user.length()));
you need to generate Random number from your array
first try this to add items in temp Arraylist. i am just only adding characters you need to replace name instead of characters
String json="{'abridged_cast':
[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},
{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},
{'name':'JessicaLange','id':'162653068','characters':['Dwan']},
{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},
{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
JSONObject jsonResponse;
try {
temp = new ArrayList<String>();
jsonResponse = new JSONObject(json);
JSONArray movies = jsonResponse.getJSONArray("abridged_cast"); // add
//user here instead of abridged_cas
for(int i=0;i<movies.length();i++){
JSONObject movie = movies.getJSONObject(i);
JSONArray characters = movie.getJSONArray("characters"); // replace
//name instead of characters
for(int j=0;j<characters.length();j++){
temp.add(characters.getString(j));
}
}
Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here is you get names randomly using onclick or whatever you want.
Random randomizer = new Random();
String RandomName = temp.get(randomizer.nextInt(temp.size()));
Loop through the JSON input. You can use java function int random = Random.nextInt(n). This returns a random int in range[0, n-1].
ArrayList<String> names = new ArrayList<>();
JSONArray socialArray = response.getJSONArray(data);
for (int i = 0; i < socialArray.length(); i++) {
JSONObject currentJSON = socialArray.getJSONObject(i);
names.add(currentJSON.getString("name");
}
final int random = Random.nextInt(names.size() + 1);
Toast.makeText(this, "Random Name: " + names.get(random), LENGTH.SHORT).show();
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
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,
I am getting an error regarding the Main UI Thread, I am not sure where I should place the AsyncTask class within this code.
Should it be in the LoginActivity class, UserFunction Class or the JSONParser class
and I also need help figuring out how to structure the AsyncTask. I have been trying man y variations but I cant figure it out
Thank you
LoginActivity Class
ALL OTHER IMPORTS
import com.example.login.DatabaseHandler;
import com.example.login.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
UserFunction Class
ALL IMPORTS
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://10.0.2.2/loginform/reg_login/index.php/";
private static String registerURL = "http://10.0.2.2/loginform/reg_login/index.php/";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("tag", login_tag));
params1.add(new BasicNameValuePair("email", email));
params1.add(new BasicNameValuePair("password", password));
// return json
// Log.e("JSON", json.toString());
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params1);
return json;
}
JSONParser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
As you cannot perform network operations in main UI thread so use asynctask where you have performed the network operations.
If I am not wrong your getJSONFromUrl is only doing network operations. So call it using an Asynctask
try this
public class Login extends AsyncTask<Void, Void, Boolean> {
private String email;
private String password;
private JSONObject json;
public Login(String email, String password) {
this.email = email;
this.password = password;
}
#Override
protected Boolean doInBackground(Void... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return true;
}
#Override
protected void onPostExecute(Boolean status) {
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
basically just put your network process in doinBackground and the other process after get data in onPostExecute
and in onClick method just call this class using
new Login(email,password).execute();
hope it's help
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