I am trying to connect to my online database with android. After following a tutorial I came up with this piece of code:
package com.example.helloandroid;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class HelloAndroid extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.4/~jasptack/Software%20engineering/connector.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","x-co: "+json_data.getInt("x-coordinaat")+
", straat: "+json_data.getString("straat")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
When I execute this, I get the following error:
12-04 23:25:07.711: E/log_tag(353): Error parsing data org.json.JSONException: Value
Can anybody help with this? Thanks!
This happens if the JSON string is malformed. Make sure that the String result is a valid JSONArray (Should start with '['). Also, you can try mapping result to a JSONObject instead. If these are fine, one of the elements inside the JSONArray is malformed.
I once tried parsing a JSON String returned by my web service. Here is what I did:
The response I got from the web service was:
{"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}
In order to parse I did the following:
JSONObject jsonobject = new JSONObject(result);
JSONArray array = jsonobject.getJSONArray("checkrecord");
int max = array.length();
for (int j = 0; j < max; j++)
{
JSONObject obj = array.getJSONObject(j);
JSONArray names = obj.names();
for (int k = 0; k < names.length(); k++)
{
String name = names.getString(k);
String value= obj.getString(name);
}
My JSONObject looks like this:
{"Table1":[],"checkrecord":[{"missed":34,"attended":12,"percentage":40,"rollno":"abc2"}]}
This is what the #500865 was trying to suggest. I just gave a code sample to you. Check your result first and determine whether it is valid. Also check JSONArray result.
If possible post it over here.
Hope it helps
Cheers
Related
I am making an app using the Kitsu API. Here in this moment I have a fragment that allows me to search different anime using the api to get information such as name, synopsis, etc. After parsing the information I proceed to go back to my main activity to pass it to my new fragment, but it crashes the moment I initialize the method to go back to my main activity. My question is how do I use a fragment to read a JSON with a background class using ASYNCTASK and display it in a new fragment?
I have noticed that it jumps around a lot from my fragment, in an activity different from my main, to a class running in the background, to my main, to my fragment. Below are images of my code. Thank you very much.
Search fragment code, Main Activity search related methods, Search results background tasks, Search Results Fragment. To clarify It stops before I get to the string I labeled crashpoint and doesn't make it to the search results fragment. I felt like it would be handy to have that bit of code in there. Here is the error I get with my code when I run it.
You don't need to create a new fragment after reading JSON. Just to post an simple code that read JSON with async task:
package com.example.compsci_734t;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class People extends Activity{
ArrayList<String> items = new ArrayList<String>();
static InputStream is = null;
//private static String url = "";
//private static String url = "http:...";
private static String url = "http....";
//URL requestUrl = new URL(url);
JSONArray people = null;
private static final String TAG_COURSES = "Courses";
static JSONObject jObj = null;
static String json = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.people);
new MyTasks().execute();
}
private class MyTasks extends AsyncTask<URL, Void, JSONObject> {
#Override
protected JSONObject doInBackground(URL... urls) {
// return loadJSON(url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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, "UTF-8"), 8);*/
InputStream inputStream = is;
GZIPInputStream input = new GZIPInputStream(inputStream);
InputStreamReader reader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
//System.out.println(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray people = new JSONArray(json);
//JSONArray people = new JSONArray(json);
for (int i = 0; i < people.length(); i++) {
//System.out.println(courses.getJSONObject(i).toString());
JSONObject p = people.getJSONObject(i);
// Storing each json item in variable
String person_id = p.getString("someString1");
items.add(person_id);
/*Log.v("--", "People: \n" + "\n UPI: " + person_id);*/
}
//jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
protected void onPostExecute(JSONObject json) {
ListView myListView = (ListView)findViewById(R.id.peopleList);
myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
}
}
The sample code was taken from this answer.
I am newbie in java programming. I am trying to get Instagram users full name. and below is my code
package gibs.smith.testapp;
import android.os.AsyncTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
private String name = "";
private String link ="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url= new URL("https://instagram.com/priya.p.varrier/?__a=1");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line !=null){
line =bufferedReader.readLine();
JSONObject jo= new JSONObject(line);
JSONObject user=jo.getJSONObject("user");
name=user.getString("full_name");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.name);
}
}
but it is not working. it dose not extracts the string value "full_name".
It is retrieving the JSON file but not the desired value.
The URL is https://instagram.com/priya.p.varrier/?__a=1
any help would be great.
----Edit-----
adding graphql object causes app crash and below is catlog output
here is the log
https://justpaste.it/1itsa
First the bug. It must be NullPointerException.
while (line !=null)
it will run until line = null. Then this line will give you the exception.
new JSONObject(line);
and you shoud get the graphql first.
so the solution should look like this.
if(line != null) {
JSONObject jo = new JSONObject(line);
JSONObject graphql = jo.getJSONObject("graphql");
JSONObject user = graphql.getJSONObject("user");
name = user.getString("full_name");
}
As per your JSON
your full_name key is inside user JSONObject which is inside graphql JSONObject.
So to get the full_name value you have to first retrieve graphql JSONObject.
JSONObject jo = new JSONObject(line);
JSONObject graphqlObj = jo.getJSONObject("graphql");
JSONObject user = jographqlObj.getJSONObject("user");
name=user.getString("full_name");
You can use http://jsonviewer.stack.hu/ to check JSON structure of your file.
i'm trying to make android food order for my thesis and because this error i'm running out of time :(
error on logcat :
Error parsing dataorg.json.JSONException: Value cannot be converted to JSONObject
org.json.JSONException: Value to JSONObject
here's my JSONParser :
package com.makanan.restotradisional;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// fungsi abil json url lewat method HTTP POST atau GET
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if (method == "POST") {
// jika request method adalah POST
// 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();
} else if (method == "GET") {
// jika request method adalah GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} catch (Exception e) {
Log.e("Buffer Error", "Error Converting result" + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data" + e.toString());
e.printStackTrace();
}
return jObj;
}
}
this my PHP & Java : http://www.4shared.com/rar/1lGplX19ba/Java_and_PHP.html
and this is my database on phpmyadmin :http://www.4shared.com/rar/y_UMtL7_ce/rumah_makan.html
please help me
Remove any of the <br> statements or echo statements from your php file except the one that you are using to pass json..
Check the output of your file in browser, remove all the unwanted things other than json..
Please print and check if your string json is in right format as expected by the JSONObject constructor. Per documentation, valid json string to construct JSONObject should be -- A string beginning with { (left brace) and ending with } (right brace).
Please refer this.
Go inside JSONParser and do this so u see in logcat whats comming from php. Probably its a php error.
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
//This line is what u need to add
Log.d("Whats wrong?", json.toString());
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
I am getting this error in my LogCat:
Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
Below are every file I could show you! Please let me know the problem and its solution ASAP. What I guess is:
1. Maybe the is problem is with parsing data in JSON array.
2. Maybe the problem is with my php api, I think I am not properly encoding the json_encode because it gives me RAW JSON, like every thing in one line.
as below
[{"uid":"120","name":"MyFirstName MyLastName"}]
Please also let me know, their is some difference in working of both format, 1. Raw JSON and 2. Intented Json
below is the intented json format
[
{
"uid":"120",
"name":"MyFirstName MyLastName"
}
]
Here is the JSONUseActivity.java
package com.example.oncemore;
import java.util.ArrayList;
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.os.Bundle;
import android.os.StrictMode;
import com.example.oncemore.CustomHttpClient;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class JSONUseActivity extends Activity {
EditText email,password;
Button submit;
TextView tv; // TextView to show the result of MySQL query
String returnString; // to store the result of MySQL query after decoding
// JSON
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is
// most commonly
// used to catch
// accidental
// disk or
// network
// access on the
// application's
// main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsonuse);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submitbutton);
tv = (TextView) findViewById(R.id.showresult);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// declare parameters that are passed to PHP script i.e. the
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("email",email.getText().toString()));
postParameters.add(new BasicNameValuePair("password",password.getText().toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://mywebsite.com/android/api.php",
postParameters);
// store the result returned by PHP script that runs MySQL
// query
String result = response.toString();
// parse json data
try {
returnString = "";
//I think the line below is creating some problem
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag",
"id: " + json_data.getInt("uid")+", name: " + json_data.getString("name"));
// Get an output to the screen
returnString += "\n" + json_data.getString("name")
+ " -> " + json_data.getInt("uid");
}
}catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
tv.setText(returnString);
}
catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
;
}
}
catch (Exception e) {
Log.e("log_tag",
"Error in http connection!!" + e.toString());
}
}
});
}
}
Here is the CustomHttpClient.java
package com.example.oncemore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.util.Log;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the specified
* parameters.
*
* #param url
* The web address to post the request to
* #param postParameters
* The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url
* The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
}
Here is the api.php
<?php
require_once("../contactdb.php");
$myusername=$_REQUEST["email"];
$mypassword=$_REQUEST["password"];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT uid,name FROM u_info WHERE email='".$myusername."' AND password ='".$mypassword."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
while($row=mysql_fetch_assoc($result))
$output[]=$row;
echo json_encode($output);
mysql_close();
}else{
echo "Error Occured!";
}
?>
Finally, When I goto browser and write like this
http://mywebsite.com/android/api.php?email=myname#yahoo.com&password=1234
I got this json array!
[{"uid":"120","name":"MyFirstName MyLastName"}]
So Far I google, I have found different formats of json array! I found everywhere Intented Json. My json array is currently in Raw Json format. I don't find anywhere how to convert Raw Json format into Intented Json format.
Thanks in advance guys!
Any help would be appreciated! If possible, please provide the correct code!
That is NOT valid JSON syntax:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Is Valid.
Note: This is also valid:
{"employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }
The syntax structure is the important part, not the formatting in terms of indentation.
As otherwise said, to use the fomat you're returning, you need to cut the substring from the response, i.e get rid of the square brackets surrounding the braces.
In PHP I create a proper json response as follows:
// array for JSON response
$response = array();
$response["apps"] = array();
$apps = array();
$apps["name"] = $row["name"];
$apps["package"] = $row["package"];
$apps["version"] = $row["version"];
$apps["dateversion"] = $row["dateversion"];
array_push($response["apps"], $apps);
$response["success"] = 1;
echo json_encode($response);
This basically gives
{ "success":"1", "apps":{["name":"NAME", "package":"PACKAGE", "version":"VERSION", "dateversion":"DATEVERSION"]}}
which can be parsed correctly by any of the abundant examples of JSON classes which you can make use of. Hacking and using substring to manually remove the first N characters is NOT good practice...
I've made a part of a code that makes a query on a remote server. but I have a problem when I'm Parsing data when there are no results of the query, does anyone nows how to handle this?
the code of the constructor that parse the data into an JSONArray is:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JsonParser {
static InputStream is = null;
static JSONObject json_data = null;
static String result = "";
// constructor
public JsonParser() {
}
public JSONArray getJSONFromUrl(ArrayList<NameValuePair> nameValuePairs, String url) {
//http post this will keep the same way as it was (it's important to do not forget to add Internet access to androidmanifest.xml
InputStream is = null;
String result ="";
JSONArray jArray = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response that we receive from the php file into a String()
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();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
// try parse the string to a Json object
try {
//json_data = new JSONObject(result);
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return Json String
return jArray;
}
}
on url, namevaluepair if someone want to try I used this:
String url = "http://trialsols.webege.com/mobil.php";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("precio",data));
that is a example MySQL with PHP database, where data is an int for the field "precio" in English cost"
solution: before parsing data of the jArray, that is returned from this constructor I added an if(jArray!= null) so I can create a message in case of no results instead of parsing data