How to store jsonarray to string array android - android

How to store jsonarray to arraylist string? please any help is much appreciated.
this is my jsonarray
{
"ids":[
{
"noid":"2"
},
{
"noid":"3"
}
],
"success":1
}
I want to store the values of identity "noid" in arraylist.
here is my code in android.
protected String doInBackground(String... args) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("qid", qsid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jParser.makeHttpRequest(
main_url, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt("success");
if (success == 1) {
// successfully received product details
JSONArray idSet = json
.getJSONArray("ids"); // JSON Array
for(int i = 0; i < idSet.length(); i++) {
JSONObject outputId = idSet.getJSONObject(i);
arrayList.add(outputId.getString("noid").toString());
}
}else{
Toast.makeText(getApplicationContext(), json.getString("result"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
and here is my php file.
<?php
require_once 'mobile_question_query.php';
$j = array();
if(isset($_GET["qid"])){
$id = $_GET['qid'];
$fetchallqObject = new Questions();
if(!empty($id)){
$json_array = $fetchallqObject->fetchAllQuestionsID($id);
echo json_encode($json_array);
}else{
$j['result'] = "No id!";
echo json_encode($j);
}
}else{
echo "no id found";
}
?>
if i check the array if arraylist is empty, it return always true.

Use Gson library.
List<String> list= new Gson().fromJson(idSet, new TypeToken<ArrayList<String>>(){}.getType());

Related

How I can update two different Mysql tables from android with one async task?

I want to update two Mysql tables with one async task and different params, when save button is clicked. It's working properly when its about one table.. How do I implement such a thing?
The code on doInBackground() is:
// getting updated data
Log.d("aa for save", String.valueOf(aa));
Log.d("bb for save", String.valueOf(bb));
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, p_id));
params.add(new BasicNameValuePair(TAG_aa, String.valueOf(aa)));
params.add(new BasicNameValuePair(TAG_bb, String.valueOf(bb)));
JSONObject json = jsonParser.makeHttpRequest(url_update_product,"POST", params);
// getting updated data
// Building Parameters
List<NameValuePair> params_user = new ArrayList<NameValuePair>();
params_user.add(new BasicNameValuePair(TAG_UNAME, uname));
params_user.add(new BasicNameValuePair(TAG_aa, String.valueOf(aa)));
params_user.add(new BasicNameValuePair(TAG_bb, String.valueOf(bb)));
JSONObject json_user = jsonParser.makeHttpRequest(url_update_user_votes,"POST", params_user);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
int success2 = json_user.getInt(TAG_SUCCESS);
if (success == 1 && success2 ==1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about update
setResult(100, i);
finish();
} else {
// failed to update
}
} catch (JSONException e) {
e.printStackTrace();
}
The error I get is :
"java.lang.IllegalArgumentException: View not attached to window manager"
on the activity that has the onActivityResult()
Change two mysql tables in one php script and send success and succes2 in one json from servera
// getting updated data
Log.d("aa for save", String.valueOf(aa));
Log.d("bb for save", String.valueOf(bb));
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_PID, p_id));
params.add(new BasicNameValuePair(TAG_UNAME, uname));
params.add(new BasicNameValuePair(TAG_aa, String.valueOf(aa)));
params.add(new BasicNameValuePair(TAG_bb, String.valueOf(bb)));
JSONObject json = jsonParser.makeHttpRequest(url_update_all,"POST", params);
// check json success tag
try {
int success = json.getInt(TAG_SUCCESS);
int success2 = json.getInt(TAG_SUCCESS2);
if (success == 1 && success2 ==1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about update
setResult(100, i);
finish();
} else {
// failed to update
}
} catch (JSONException e) {
e.printStackTrace();
}
example php script
<?php
$aa = $_REQUEST['aa'];
$bb = $_REQUEST['bb'];
$p_id = $_REQUEST['p_id'];
$uname = $_REQUEST['uname'];
//db connect.......
$success=0;
$resttt = "UPDATE table1 SET aa='$aa' ";
$result = mysql_query("$resttt");
if($result) { $success=1; }
$success2=0;
$resttt2 = "UPDATE table2 SET bb='$bb' ";
$result2 = mysql_query("$resttt2");
if($result2) { $success2=1; }
// array for JSON response
$response = array();
// success
$response["success"] = $success;
$response["success2"] = $success2;
// echoing JSON response
echo json_encode($response);
?>

retrieve data using json in 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,

Sending ArrayList from Android to PHP script using JSON

What is the Scenario
I want to send multiple ArrayList (usally 5) from android to the server and want to insert it into mysql database.
What I Have Done Successfully
I have Successfully send single value and Multiple Values from Android to PHP script using JSON
i have Received single and Multiple Records from mysql database to android using JSON
Here is the Code for inserting and getting value from server
class TeacherLogin1 extends AsyncTask<Void, Void, Void> {
String name,pass;
Context contextt;
int idofteach = 0;
int codee = 0;
TeacherLogin1(String pass1,String name1,Context context)
{
name = name1;
pass = pass1;
contextt = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
codee = Authenticate(name,pass);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(codee!=0)
{
Intent teachers = new Intent(context,TeachersView.class);
teachers.putExtra("TID", codee);
teachers.putExtra("TNAME", TeachName);
teachers.putExtra("sub1", subj1);
teachers.putExtra("sub2", subj2);
teachers.putExtra("sub3", subj3);
teachers.putExtra("sub4", subj4);
startActivity(teachers);
}
else
Toast.makeText(context, "Wrong Details", Toast.LENGTH_SHORT).show();
codee = 0;
}
}
public int Authenticate(String name,String Pass)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("name",name));
nameValuePairs.add(new BasicNameValuePair("pass",Pass));
try
{
HttpClient httpclient = new DefaultHttpClient();
ScriptsFilePath a = new ScriptsFilePath();
HttpPost httppost = new HttpPost(a.TeacherAuthen);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try {
JSONObject jsonResponse = new JSONObject(result);
if(jsonResponse != null)
{
JSONArray jsonMainNode = jsonResponse.optJSONArray("GetTeacher");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
code = jsonChildNode.optInt("ID");
TeachName= jsonChildNode.optString("Name");
subj1= jsonChildNode.optString("subject1");
subj2= jsonChildNode.optString("subject2");
subj3= jsonChildNode.optString("subject3");
subj4= jsonChildNode.optString("subject4");
}
}
} catch (JSONException e) {
// Toast.makeText(getApplicationContext(), "Error" + e.toString(),
// Toast.LENGTH_SHORT).show();
}
return code;
}
and the TeacherAuthen.php script
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host="localhost";
$uname="root";
$pwd='';
$db="examsystem";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
if(isset($_REQUEST)){
$name=$_REQUEST['name'];
$pass=$_REQUEST['pass'];}
$flag['code']=0;
$name1['code1'] = "sdf";
$sql = "SELECT * FROM teachers WHERE Username ='$name' and Pass='$pass'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['GetTeacher'][]=$row;
}
}
echo json_encode($json);
mysql_close($con);
?>
where i am stuck
I dont no how to send ArrayList from android to PHP Script.
For Example I want to send these arraylists to php script =
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
and then in the PHP script i want to insert like this
"INSERT INTO `Question` (`ID` ,`Question` ,`A1` ,`A2` ,`A3` , `A4` ) VALUES (NULL, '$Question', '$A1', '$A2', '$A3' ,'$A4'); "
if i am able to send even a single arrayList then i think i can make a way to do the above
and Thanks for you Time
This is your Array: you can create more as required in your example.
ArrayList<String> contact = new ArrayList<String>();
Then, create a JSONcontacts variable of type JSONObject to store this array in this object
JSONObject JSONcontacts = new JSONObject();
Now, loop through all elements in that contact array and store it in the JSONcontacts
//Loop through array of contacts and put them to a JSONcontact object
for (int i = 0; i < contact.size(); i++) {
try {
JSONcontacts.put("Count:" + String.valueOf(i + 1), contact.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Lets say you created many Arrays, which you probably have done, now you hvave to put them all into 1 JSON. So create a EverythingJSON variable of type JSONObject()
JSONObject EverythingJSON = new JSONObject();
and now put all your contact array and other arrays into it, right you loop through them as described above:
EverythingJSON.put("contact", JSONcontacts);
EverythingJSON.put("something", JSONsoemthing);
EverythingJSON.put("else", JSONelse);
now this is your AsynchTask to send them to your PHP server:
new AsyncTask() {
//String responseBody = "";
#SuppressWarnings("unused")
protected void onPostExecute(String msg) {
//Not Needed
}
protected Object doInBackground(Object... params) {
//Create Array of Post Variabels
ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
//Add a 1st Post Value called JSON with String value of JSON inside
//This is first and last post value sent because server side will decode the JSON and get other vars from it.
postVars.add(new BasicNameValuePair("JSON", EverythingJSON.toString());
//Declare and Initialize Http Clients and Http Posts
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.OnlineAPI);
//Format it to be sent
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/* Send request and Get the Response Back */
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
}.execute(null, null, null);
Now on the PHP server side, you can loop through this JSON as such:
FIrst of all, get that JSON from POST and store it in a var:
//Receive JSON
$JSON_Received = $_POST["JSON"];
Now decode it from JSON:
//Decode Json
$obj = json_decode($JSON_Received, true);
And this is the loop to go through the array of contacts and get he Key and Value from it:
foreach ($obj['contact'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
}
you can repeat this loop for other Arrays you have sent :) Good Luck!
You cant send Arraylist to server,its an object. The best way to solve your problem is
user JSON , you need to do something like that -
ArrayList<String> Questions= new ArrayList<String>();
ArrayList<String> A1= new ArrayList<String>();
ArrayList<String> A2= new ArrayList<String>();
ArrayList<String> A3= new ArrayList<String>();
ArrayList<String> A4= new ArrayList<String>();
JsonArray jArr1= new JsonArray();
for(String data:A1)
{
jArr1.add(data);
}
JsonArray jArr2= new JsonArray();
for(String data:A2)
{
jArr2.add(data);
}
//convert each array list to jsonarray
JsonArray jArraySet = new JsonArray();
jArraySet.add(jArr1);
jArraySet.add(jArr2);
//add each json array to jArraySet
// then send the data via
HttpClient httpclient = new DefaultHttpClient();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// put the values of id and name in that variable
nameValuePairs.add(new BasicNameValuePair("all_arraylist",jArraySet.toString()));
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
note: dont forget to do it in asynctask
in php section ,do the following
<?php
$all_arraylist = $_POST['all_arraylist'];
$all_arraylist= json_decode($all_arraylist,TRUE); //this will give you an decoded array
print_r($all_arraylist); // display the array
// after seeing the array , i hope you will understand how to process it.
?>
Very simple. you should parse your JSON in php and get array of objects that you have sent. Here is solution
$JSON_Received = $_POST["json"];
$obj = json_decode($JSON_Received, true);
$array_1st_name = $obj[0];
$array_2nd_name = $obj[1];
and so on you will get all array of object.

jParser.makeHttpRequest wont catch error when I'm not connected to internet

I'm developing an application that connects to a PHP and get data from database.
My problem is when I get data by jParser.makeHttpRequest with internet connection and close my internet and do that again jParser.makeHttpRequest returns the last thing that it returned. It won't give No Internet Error or sοmething like that. How can I correct this?
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(url_get_login_infos, "GET", _params);
int success = json.getInt(TAG_SUCCESS);
String message = json.getString(TAG_MESSAGE);
Object are destroy by garbage collector. Your object still exists when you call data for the second time.
Reset your parser with null for example before you call data and test the result. Post your some code for more answers
here some of code with Json wich works fine
protected String doInBackground(String... args) {
//affectation des valeurs pour passage à PHP
String email = getEmail();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
// getting JSON Object
String url = SingletonParametres.getUrlConnexion() + "get_selectuser.php";
JSONObject json = null;
try {
json = jsonParser.makeHttpRequest(url, "GET", params);
} catch (HttpException e) {
e.printStackTrace();
}
// check for success tag
try {
String Variablepourvoir = json.getString(TAG_SUCCESS);
success = json.getInt(TAG_SUCCESS);
switch (success) {
case 1: { /* user retrouvé avec succes */
// successfully select user
setCodeRetour(1);
setMsgRetour("user existe MyApplication ok");
// sauvegarde des données User dans la classApplication
// successfully received product details
JSONArray JsonUserArray = json.getJSONArray("user"); // JSON Array
// get first user object from JSON Array
JSONObject JsonUserObject = JsonUserArray.getJSONObject(0);
// user with this email found
//save data in MyApplication
MyApplication.setIdUser(JsonUserObject.getInt("iduser"));
MyApplication.setEmail(JsonUserObject.getString("email"));
MyApplication.setPseudo(JsonUserObject.getString("pseudo"));
if ( JsonUserObject.getInt("autorisation_upload") ==1 ) {
MyApplication.setAutorisationUpload(true);
} else {
MyApplication.setAutorisationUpload(false);
}
break;
}
case 0: { /* oops ! ... un probleme est survenu */
setCodeRetour(ECHEC);
setMsgRetour("user non trouvé MyApplication echec");
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
try this, you have that add this condition:
if(json != null){
//excecute code
}else{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "conection error", Toast.LENGTH_SHORT).show();
}
});
}
This way of writing the Toast, is if you work in a Fragment.
in your code, make this:
String url = SingletonParametres.getUrlConnexion() + "get_selectuser.php";
JSONObject json = null;
json = jsonParser.makeHttpRequest(url, "GET", params);
if(json != null) {
try {
String Variablepourvoir = json.getString(TAG_SUCCESS);
success = json.getInt(TAG_SUCCESS);
switch (success) {
case 1: {
.....
.....
}else{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "conection error", Toast.LENGTH_SHORT).show();
}
});
}

HttpPost request returning bad response

I am trying to send a HttpRequest to a php script located on a web server. I would like to retrieve all the dishes with of a particular category. The dishes are returned in JSON format where my JSONParser class parses the data.
Below is my doInBackground method where I make the request for the file:
#Override
protected Boolean doInBackground(String... params) {
// location of file to retrieve
String url = "http://www.jdiadt.com/getAllDishes.php";
JSONObject json = jParser.makeHttpRequest(url, "POST", cat);
// For testing purposes - Ensure all data was received.
Log.d("SINGLE DISH DETAILS: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
dishes = json.getJSONArray(TAG_DISHES);
for (int i = 0; i < dishes.length(); i++) {
JSONObject d = dishes.getJSONObject(i);
MenuItem m = new MenuItem();
m.setName(d.getString(TAG_NAME));
m.setPrice(Double.parseDouble(d.getString(TAG_PRICE)));
Log.d("MENUITEM " + i + ":", " NAME:" + m.getName()
+ " PRICE:" + m.getPrice());
starters.add(m);
}
} else {
return false;
}
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
This is the makeHttpRequest() method of the JSONParser class:
public JSONObject makeHttpRequest(String url, String method, String cat) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("cat", cat));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
This is the script I am attempting to retrieve:
$response = array();
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "xxx.xxx.xxx.xxx";
$username = "xxxxxx";
$dbname = "xxxxxxx";
//These variable values need to be changed by you before deploying
$password = "xxxxxxxxxxx";
$usertable = "dishes";
$yourfield = "dish_name";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
$cat = $_POST['cat'];
// get all dishes from dishes table
$result = mysql_query("SELECT * FROM $usertable where dish_cat = '$cat' ") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// dishes node
$response["dishes"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$dishes = array();
$dishes["dish_id"] = $row["dish_id"];
$dishes["dish_name"] = $row["dish_name"];
$dishes["dish_desc"] = $row["dish_desc"];
$dishes["dish_price"] = $row["dish_price"];
// push single dish into final response array
array_push($response["dishes"], $dishes);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no dishes found
$response["success"] = 0;
$response["message"] = "No dishes found";
// echo no users JSON
echo json_encode($response);
}
Notice the line:
$cat = $_POST['cat']
That should be retrieving the dish category and the sql statement should be executing successfully....currently I get a message back saying "No Dishes Found".
Any help would be much appreciated. I don't know what I am doing wrong.
I think problem is your condition:
if (method == "POST") {
// execute request
}
Here you are comparing Strings with == and this will always return false(and body never be performed) because it compares references not values. You have to use equals() method.
if (method.equals("POST") {
// do your work
}
hey try printing $cat to make sure you are receiving it properly first.

Categories

Resources