I read data from a database (only the last row, I do it in my php file) what I want to do is to use the data of each field separately but the problem is that the JSONArray is empty I tried a lot of ways to do it looking for it in different posts but it´s always empty.
This is my code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
JSONArray jArray = null;
String result = null;
InputStream is = null;
StringBuilder sb=null;
String ct_id;
String ct_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost= new HttpPost("http://xxx.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();
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());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("fecha");
ct_name=json_data.getString("dia");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "JSON is empty" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
It always catchs JSONException e1.
Thank you everibody in advance
Check returned string in result. Probably there are not only json structure(errors, warning, etc..). JSON spellchecker: http://jsonlint.com/
after checking the json response; better to try using GSON, much more convenient;
JsonParser jsonParser = new JsonParser();
JsonArray jArray;
if ( jsonParser.parse(result).isJsonArray() ) {
jArray = jsonParser.parse(result).getAsJsonArray();
}
else { jArray = new JsonArray(); }
The problem was in PHP file, JSON couldn´t understand the data and that is why it was empty, I changed it and now works properly.
Related
I'm trying to receive a JSON format file throw HTTP in Android. But while i do that i guess the file comes bad formatted. The code is the following:
#Override
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
URI website = new URI(params[0]);
HttpGet request = new HttpGet();
request.setHeader("Content-type", "application/json");
request.setURI(website);
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
builder.append(line);
}
}
catch(Exception e){
Log.e("http", e.toString());
}
return builder.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
txt.setText((String) jObject.get("shortName"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//txt.setText(result);
}
The JSON file is like this:
{"lectiveSemesters":[{"lectiveSemesterId":1,"shortName":"0910i","startYear":2009,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/1","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":2,"shortName":"0910v","startYear":2009,"term":2,"termName":"Spring","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/2","root":"http://thoth.cc.e.ipl.pt/api/v1"}},{"lectiveSemesterId":3,"shortName":"1011i","startYear":2010,"term":1,"termName":"Fall","_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters/3","root":"http://thoth.cc.e.ipl.pt/api/v1"}},
...
...
"_links":{"self":"http://thoth.cc.e.ipl.pt/api/v1/lectivesemesters"}}
This is just a part of the file.
Am I doing something wrong? I included the header in order to receive in JSON format.
Here you are.
try{
JSONObject jObject = new JSONObject(result);
JSONArray jarray = jObject.getJSONArray("lectiveSemesters");
for(int i = 0; jarray != null & i < jarray.length(); i++){
JSONObject jitem = (JSONObject) jarray.get(i);
}
} catch (Exception e){
}
I am working with webservice in an android app. I could not parse the following response in app. it always gives the
org.json.JSONException: Value
[{"METER_READING":"15","UTILITY_PLAN":"1","uname":"vinayak#triffort.com","kwh_usage":"3","meter_reading_date":"02-13-2014","ESID":"abc","METER_ID":"abc100"}]
at data of type java.lang.String cannot be converted to JSONArray.
Below is my code:
StringEntity entity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response from webservice
{"data":"[{\"METER_READING\":\"25\",\"UTILITY_PLAN\":\"1\",\"uname\":\"vinayak#triffort.com\",\"kwh_usage\":\"9\",\"meter_reading_date\":\"02-13-2014\",\"ESID\":\"abc\",\"METER_ID\":\"abc100\"}]"}
try using something like:
jsonResultStr = jsonResultStr.replace( "\\", "" ).replaceAll( "\"\\[", "[" ).replaceAll( "\\]\"", "]" );
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response
{
"data":"[{\"METER_READING\":\"25...}]"
}
The value of data is not an array; it is a string. That string is valid JSON which you could parse but why the service would do this is unclear.
So this should work:
JSONObject jObject = new JSONObject(jsonResultStr);
String parseMeAgain = jObject.optString("data");
try this simple code:
JSONObject o = new JSONObject(new JSONTokener(postResponse));
JSONArray ja = o.getJSONArray("data");
EDIT
Thanks #McDowell for observation
new JSONArray(new JSONTokener(jObject.optString("data")));
You can do this way :
JSONArray jsonArray = new JSONArray(result); // Pass your result here..
JSONObject jsonObject = jsonArray.getJSONObject(0);
String meterReading = jsonObject.getString("METER_READING");
String plan = jsonObject.getInt("UTILITY_PLAN");
String uname= jsonObject.getString("uname");
String meter_reading_date= jsonObject.getString("meter_reading_date");
String ESID= jsonObject.getString("ESID");
String METER_ID= jsonObject.getString("METER_ID");
Your json should be like this
{
"myarray": [
{
"METER_READING": "15",
"UTILITY_PLAN": "1",
"uname": "vinayak#triffort.com",
"kwh_usage": "3",
"meter_reading_date": "02-13-2014",
"ESID": "abc",
"METER_ID": "abc100"
}
]
}
for network call
public String initializeConnection(String url) {
String result = null;
JSONObject jObj;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if(client==null){Log.i("Clinet **************** ", "Client is null");}
//post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse res = client.execute(post);
result = inputStreamToString(res.getEntity().getContent()).toString();
Log.d("Result from server:", result);
jObj = new JSONObject(result.trim());
} catch (JSONException e1) {
Log.e("Json Exception", e1.toString());
} catch (ClientProtocolException e2) {
Log.e("Client Protocol", e2.toString());
} catch (IOException e3) {
Log.e("Io exception", e3.toString());
}
return result;
}
private StringBuilder inputStreamToString(InputStream is) throws UnsupportedEncodingException {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
to retrive from the json
ArrayList<String> params = new ArrayList<String>();
String result = networkCall.initializeConnection(url);
jObj = new JSONObject(result);
JSONArray jArray = jObj.optJSONArray("myarray");
params.add(jArray.optString(1));
params.add(jArray.optString(2));
params.add(jArray.optString(3));
params.add(jArray.optString(4));
params.add(jArray.optString(5));
params.add(jArray.optString(6));
now the data is stored in the params you can differentiate & store it as you want
I am working on an Android application that executes an http POST request, and the tutorial I followed was resulting in an android.os.NetworkOnMainThreadException
The original code was something like this.
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;
}
}
And this class was invoked with this line.
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
After changing this to an AsyncTask class, the code looks like this.
class JSONParser extends AsyncTask<String, Void, JSONObject>{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// variables passed in:
String url;
List<NameValuePair> params;
// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}
#Override
protected JSONObject doInBackground(String... args) {
// 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 (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;
}
#Override
protected void onPostExecute(JSONObject jObj) {
return;
}
}
My question is, how do I return a JSONObject from this new AsyncTask class?I can see that jObj is being returned in doInBackground(), but I am not sure where it is being returned to.
What do I need to modify or how do I need to call my new JSONParser class so that it is returning a JSONObject?
Have a look at this code, it may give you an insight as to how to deal with the parsing of JSON objects. I am just posting the onPostExecute function for now because you seemed to have all the rest figured correctly.
As for your doubt as to where the data object from the doInBackground is returned, it is automatically sent to the onPostExecute where you can further on parse it.
#Override
protected void onPostExecute(JSONObject result)
{
try
{
JSONObject data = result.getJSONObject("data");
// whatever your JSON tag may be, in this case its data.
if (data.isNull("data"))
{
// action to handle null JSON object.
}
else
{
JSONArray jarray = data.getJSONArray("data");
int len=jarray.length();
for (int i = 0; i < jarray.length(); i++)
{
JSONObject obj = (JSONObject) jarray.get(i);
String instanceName = obj.getString("instanceName");
//extract data by whatever tag names you require, in this case instanceName.
}
}
}
catch (JSONException je)
{
je.printStackTrace();
Log.d(TAG, "Error: " + je.getMessage());
}
}
}
from your doInBackground Method
#Override
protected JSONObject doInBackground(String... args) {
return jObj;
}
your return your JsonObject to
#Override
protected void onPostExecute(JSONObject jObj) {
// Here you get your return JsonObject
}
An Async Task has 3 attribures
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
The point you need to understand is that you are creating a object of Async Task Class While calling new JSONParser(loginURL, params);
The solution is that create a public result variable in your Async class and the call execute() on the object of class and then access the public object from the object.
I can see that jObj is being returned in doInBackground() but I am not
sure where it is being returned to.
The result of doinBackground() is received as a parameter in onPostExecute(). You are returning a json object in doinBackground() which is a parameter to onPostExecute().
#Override
protected void onPostExecute(JSONObject jObj) {
return;
}
Usage
new JSONParser().execute("url);
class JSONParser extends AsyncTask<String, Void, JSONObject>{
//string parameter to doInBackground()
//JSONObject - result returned in doInBackground() received as a param in onPostExecute()
}
You can also pass paramters to the constructor of your asynctask
new JSONParser("url",params).execute();
In your asynctask;
String url;
List<NameValuePair> params;
// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}
I am doing an HttpPost to get data from a php server using async task. Basically the php script will either return a JSON array or null. It works fine when the json array is returned, however if the script returns null my if statement is not being picked up on and I am being returned this error:
Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is a snippet of my script:
#Override
protected Void doInBackground(String... params) {
String url_select = "http://localhost/test.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
if(result == "null"){
this.progressDialog.dismiss();
startActivity(new Intent(viewRandom.this, allDone.class));
}else{
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++){
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String id = Jasonobject.getString("id");
}
this.progressDialog.dismiss();
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Change if(result == "null") to if(result == null).
If you want to check for the string "null" do it with .equals(): if ("null".equals(result))
I am not sure if you really send a "null" string back from your server but anyway. As you might end returning null (not the string!), you should check for that, too.
Edit: Why is "null".equals(result) better than result.equals("null")? The answer is: the first one is null-safe which means it will not throw a NullPointerException when result is null. The second one will result in an exception in that case.
Instead of returning null Your Should try to return an Integer value to onPostExecute something like this
#Override
public Integer doInBackground(String...params){
.......
.......
return 1;
}
protected void onPostExecute(Integer v) {
if(v==1) {
}
}
I am trying to connect to MySQL DB using php script. But I don't get any output only exception code. I can't figure it out where is the problem. I used a tutorial code.
private EditText outputStream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream input = null;
StringBuilder sbuilder = null;
outputStream = (EditText)findViewById(R.id.output);
ArrayList <NameValuePair> nameValuePairs = new ArrayList <NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/Bandymas/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
input = entity.getContent();
}
catch(Exception e){
Log.e("log_tag","Error in internet connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(input,"iso-8859-1"),8);
sbuilder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sbuilder.append(line + "\n");
System.out.println(line);
}
input.close();
result = sbuilder.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
int fd_id;
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id = json_data.getInt("FOOD_ID");
fd_name = json_data.getString("FOOD_NAME");
outputStream.append(fd_id +" " + fd_name + "\n");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No food found", Toast.LENGTH_LONG).show();
}
catch(ParseException e1){
e1.printStackTrace();
}
}
PHP script:
<?php
mysql_connect("localhost","**********","******");
mysql_select_db("test");
$sql = mysql_query("select FOOD_NAME as 'Maistas' from FOOD where FOOD_NAME like 'A%'");
while($row = mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close;
?>
Any ideas how to fix it?
First, dont use Exception.toString(), use Exception.printStackTrace():
catch (Exception e) {
e.printStackTrace();
}
Second, in your PHP code, your not checking for any errors. If any errors occur, I suggest you issue a different HTTP status code (like 400), then, in your Android code:
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error.);
}
This way you will know if something happened on the server.
Hope this helps