HttpPost request returning bad response - android

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.

Related

How to store jsonarray to string array 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());

Retrieving data from JSON?

I am trying to get all the species result from the first url but sadly, my for loop can only retrieve one species from my first url and I don't know what's the correct logic here. Hope you can help me. I know the problem is my for loop but I don't know how to construct it correctly. Sorry. Newbie here.
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?species_name="
+ search_species;
pDialog.setMessage("Loading data...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("tem");
for(int i = 0; i<array.length(); i++) {
JSONObject o = array.getJSONObject(i);
species_id = o.getString("localname");
common = o.getString("name");
scientific = o.getString("scientificname");
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?speciesid=" + species_id;
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("locationid", c.getString("locationid"));
map.put("brgy", c.getString("brgy"));
map.put("town", c.getString("town"));
map.put("latitude", c.getString("latitude"));
map.put("longitude", c.getString("longitude"));
map.put("speciesid", local);
map.put("flowercolor", c.getString("flowercolor"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
This is my getHttpGet:
public static String getHttpGet(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
and this is the PHP file:
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$species_name = $_GET['species_name'];
$sql = "SELECT * from tbl_species WHERE CONCAT_WS(name, localname,
scientificname, familyname, flowercolor, leafshape) LIKE '%$species_name%'";
$result = $conn->query($sql);
if ($result->num_rows >0) {
$arr['aaData'] = array();
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode(array('tem' => $tem));
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
Specifically, my for loop can only get the first species, after getting that, the for loop stops to get the others. I don't know what's wrong and what I should change. I'm creating a project that can search a species by name, by color, by shape etc.
Just a guess but maybe because you use the same int in both for loops
for(int i = 0; i<array.length(); i++)
for(i = 0; i < data.length(); i++){
You have a NetworkOnMainThreadException and your app crashes when you handle the second url.
You could have told us of the crash.
You should execute all network/internet code in a thread or asynctask.
You must have 2 variables to save the values in PHP file.and use array_push for save all values in an array
search_species = txtSearchMap.getText().toString();
String url =
"http://192.168.1.9/android_login_api/search_species_map.php?type=first&species_name="
+ search_species;
.
.
.
local = o.getString("localname");
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.9/android_login_api/search_location_map.php?type=tow&speciesid=" + species_id;
try {.....
and in PHP file
$type = $_GET['type'];
$response1 = array();
$response2 = array();
.
.
.
while($row[] = $result->fetch_assoc()) {
if (type ==="fist"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}elseif (type ==="tow"){
array_push($response2,array('locationid' => $row['locationid'],'brgy'=>$row['brgy'],'town'=>$row['town'],'latitude'=>$row['latitude'],'flowercolor'=>$row['flowercolor']));
}
}////end while
if (type ==="fist"){
echo $response1;
}elseif(type1 ==="tow"){
echo $response2;
}
.
.
.

How can I store my ArrayList values to MySQL databases?

I have some problem to store arraylist value to mysql database with php. This is some code I have been created.
First, I have some class to store variable its called Constant.java :
public class Constant {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public static final String THIRD_COLUMN = "Third";
public static final String FOURTH_COLUMN = "Fourth";
}
Second, I have been import that class to MainActivity.java like this :
import static com.testing.informationsystem.Constant.FIRST_COLUMN;
import static com.testing.informationsystem.Constant.SECOND_COLUMN;
import static com.testing.informationsystem.Constant.THIRD_COLUMN;
import static com.testing.informationsystem.Constant.FOURTH_COLUMN;
Third, I store my value to arraylist by this way :
btnInsert = (Button) findViewById(R.id.btnInsert);
btnInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
orderValue = txtOrderValue.getText().toString();
price = txtPrice.getText().toString();
valueSpinner = spnProductFocus.getSelectedItem().toString();
HashMap temp = new HashMap();
if(orderValue.equalsIgnoreCase("")){
orderValue = "0";
}
if(price.equalsIgnoreCase("")){
price = "1000";
}
double count = Double.parseDouble(orderValue) + Double.parseDouble(price);
total = String.valueOf(count);
if(count.equalsIgnoreCase("")){
count = "0";
}
temp.put(FIRST_COLUMN, valueSpinner);
temp.put(SECOND_COLUMN, orderValue);
temp.put(THIRD_COLUMN, price);
temp.put(FOURTH_COLUMN, total);
list.add(temp);
}
});
Okay, now I have arraylist contains value I saved from button. And now I will send it through out HTTPOST to PHP and store it to mysql. This is my code to post it to PHP.
void saveOrder(){
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://dcmodular.com/saktisetia/mobile/order.php");
nameValuePairs = new ArrayList<NameValuePair>(2);
--nameValuePairs.add(new BasicNameValuePair(arraylist));--
----this is my problem about how to post it to PHP---
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
Log.d("Value : ", response.toString());
HttpEntity entity=response.getEntity();
String feedback = EntityUtils.toString(entity).trim();
Log.d("Feedback : ", feedback);
}
Finally, this is my own php file to store it to mysql databases :
<?php
include('connection.php');
--receive arraylist from httppost--
$query = "insert into order(value1) values(value1)";
$execute = mysql_query($query) or die(mysql_error());
if($execute){
echo "saved";
}else{
echo "failed";
}
?>
That is my code and my problem how to post that arraylist to PHP. Thank you before for your helping.
Use HttpUrlConnection as Http Default client is no longer supported.
Try this
public JSONObject function(String value_to_post, String value_to_post,....){
try {
HashMap<String, String> params = new HashMap<>();
params.put("your_database_field", value_to_post);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
your_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
call this function from your activity
$_POST variable will hold your posted data.
//You have to something similar.
//This is just an idean as i dont know how you declared temp and arraylist
for (int i = 0; i < type.length; i++) {
nameValuePairs.add(new BasicNameValuePair(list.get(i).getkey,list.get(i).getValue));
}
In Android:
postParameters.add(new Pair<>("value1", value1.toString()));
In Php
$str = str_replace(array('[',']'),'',$_POST['value1']);
$str = preg_replace('/\s+/', '', $str);
$value1 = preg_split("/[,]+/", $str);
$i=0;
while($i<count($value1){
$query = "insert into order(value1) values(value1)";
}
You can use List<NameValuePair> to send POST request to server.
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1", "data1"));
nameValuePairs.add(new BasicNameValuePair("param2", "data2"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

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);
?>

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.

Categories

Resources