I am currently learning how to create apps on Android Studio and have been trying to make a JSON connection with a server and bring back the information from the server and display it in my app. I have been able to make the connection as logical shows however I am unclear of the error that faces me and how to solve it. I will show here my two classes I have constructed to make the JSON connection and the error I am shown. When I run the emulator it just says, Unfotunatley, JSONconnection app has stopped working.
Thanks for the help
Error on logcat with exception
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection E/JSON Parser﹕ Error parsing data org.json.JSONException: Value [{"id":"170656","RatingValue":"5","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Cheeky Coffee Co","Longitude":"-2.240435","RatingDate":"2014-02-06","AddressLine1":"Unit 10, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"171710","RatingValue":"3","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Nando's","Longitude":"-2.240435","RatingDate":"2013-01-17","AddressLine1":"Unit 3, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"172780","RatingValue":"4","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Zouk Tea Bar & Grill","Longitude":"-2.240435","RatingDate":"2010-06-11","AddressLine1":"Unit 5 The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"170593","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Caffe Nero","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"8A Oxford Road","AddressLine3":"Manchester"},{"id":"171089","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Greggs","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"10 Oxford Road","AddressLine3":"Manchester"},{"id":"171185","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Holiday Inn Express","Longitude":"-2.23997","RatingDate":"2011-03-17","AddressLine1":"","AddressLine2":"2-4 Oxford Road","AddressLine3":"Manchester"},{"id":"171382","RatingValue":"1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Kukoos","Longitude":"-2.23997","RatingDate":"2013-11-18","AddressLine1":"","AddressLine2":"12a Oxford Road","AddressLine3":"Manchester"},{"id":"171404","RatingValue":"-1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Ladbrokes","Longitude":"-2.23997","RatingDate":"2010-11-09","AddressLine1":"","AddressLine2":"10B Oxford Road","AddressLine3":"Manchester"},{"id":"172281","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Subway","Longitude":"-2.23997","RatingDate":"2013-10-09","AddressLine1":"","AddressLine2":"12 Oxford Road","AddressLine3":"Manchester"},{"id":"171119","RatingValue":"5","DistanceKM":"0.100210503082758","PostCode":"M1 5GE","Latitude":"53.47208","BusinessName":"H & M Convenience Store","Longitude":"-2.241442","RatingDate":"2010-09-16","AddressLine1":"Student Village","AddressLine2":"Lower Chatham Street","AddressLine3":"Manchester"}] of type org.json.JSONArray cannot be converted to JSONObject
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection D/AndroidRuntime﹕ Shutting down VM
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb2cbdb20)
04-08 08:10:23.860 1656-1656/com.example.adam.jsonconnection E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.adam.jsonconnection, PID: 1656
JSONParser Class
package com.example.adam.jsonconnection;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}
MainActivity Class
package com.example.adam.jsonconnection;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
//URL to get JSON Array
private static String url = "";
//JSON Node Names
private static final String TAG_NEAREST = "nearest";
private static final String TAG_BusinessName = "BusinessName";
JSONArray nearest = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
nearest = json.getJSONArray(TAG_NEAREST);
JSONObject c = nearest.getJSONObject(0);
// Storing JSON item in a Variable
String businessName = c.getString(TAG_BusinessName);
//Importing TextView
final TextView BusinessNameText = (TextView)findViewById(R.id.BusinessName);
//Set JSON Data in TextView
BusinessNameText.setText(businessName);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You have a JSONArray and you're attempting to create a JSONObject object with it.
Simple change your code to:
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Or edit your response so that it is a json object.
Your JSON is an Array from root, so you must change from:
JSONObject json = jParser.getJSONFromUrl(url);
to
JSONArray json = jParser.getJSONFromUrl(url);
and return a JSONArray from getJSONFromUrl
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
I suggest you to use:
jsonObject.optString("your_key");
instead of:
jsonObject.getString("your_key");
this will automatically handle possible "null" values
Related
I tried to parse some strings from this JSON-site:
I wrote this code with asynctask:
package com.example.nortti.jsonexample;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
TextView txView;
//URL to get JSON Array
private static String url = "http://localhost:10101/api/stats/1";
//JSON Node Names
private static final String TAG_USER = "";
private static final String TAG_NAME = "PersonName";
private static final String TAG_EMAIL = "Rank";
JSONArray user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
user = null;
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
txView = (TextView)findViewById(R.id.txView);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray("ArrayOfCommonStatViewModel");
Toast.makeText(getApplication(),user.toString(),Toast.LENGTH_SHORT).show();
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
txView.setText(name+" " +email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And I have another class like:
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
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();
} 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;
}
}
But it says that I have a NullPointerException
I want to get a JSONArray to get information and put it into a ListView.
UPD: Here is JSON screenshot
UPD2: full log
12-17 14:17:03.712 20308-20308/com.example.nortti.politrange E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nortti.politrange, PID: 20308
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:102)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:373)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:225)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:178)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at com.example.nortti.politrange.utils.WebApiAdapter.select(WebApiAdapter.java:33)
at com.example.nortti.politrange.intefaces.impls.PersonCatalog.populateData(PersonCatalog.java:37)
at com.example.nortti.politrange.views.GeneralFragment.listData(GeneralFragment.java:65)
at com.example.nortti.politrange.views.GeneralFragment.onClick(GeneralFragment.java:88)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5253)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
you are getting a NetworkOnMainThread exception because you are implementing a network operation in a UI thread so for loading the json data from your localhost you need to implement a seperate thread for it
You are getting NetworkOrMainThreadException.
Put below code on onCreate():
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Hope this will help you.
You are trying to parse an XML document with a JSON Parser, it won't work. Let's take a look on this link , it will show you how to parse an XML document (in Android environment) on a proper way:
The content that you are trying to parse is actually xml not JSON. If you need to do network requests, parse the JSON, you can use Retrofit library. It is very simple and hassle-free. Here is a nice tutorial for the same. Hope it helps.
instead of developping the whole parsing code, try to use the Volley library of Google, it's an asynchrone library for parsing JSON.
here is a good tutorial.
enter code here
////In android studio add http client and http core libs/////
class mytask extends AsyncTask {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "http://192.168.1.13/mywebservice/getbook.php";
json = getJSONFromUrl(url);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(ctx, json, Toast.LENGTH_LONG).show();
parser_01();
}
}
// from url to json object starts.......................................
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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");
sb.append(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
// from url to json object Ends.......................................
public void parser_01() {
try {
String jstring = json;
JSONObject jobject = new JSONObject(jstring);
JSONArray bookarray = jobject.getJSONArray("data");
for (int i = 0; i < bookarray.length(); i++) {
String isdn = bookarray.getJSONObject(i).getString("isdn") + "";
String title = bookarray.getJSONObject(i).getString("title") + "";
String author = bookarray.getJSONObject(i).getString("author") + "";
String price = bookarray.getJSONObject(i).getString("price") + "";
}
} catch (Exception e) {
// TODO: handle exception
}
}
I am getting a exception while working in json . My JSONPresr class is as follow
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println(" value in json sting"+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());
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
System.out.println(" error is here");
}
// return JSON String
return jObj;
}
}
I am getting my data by these code
String TAG_user_detail = "user_details";
String TAG_user_id = "user_id";
String TAG_user_name = "user_name";
String TAG_user_phone = "user_phone";
String TAG_ref_id = "ref_id";
JSONArray user_detail_jsonarray = null;
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
user_detail_jsonarray = json.getJSONArray(TAG_user_detail);
// looping through All Contacts
for(int i = 0; i < user_detail_jsonarray.length(); i++){
JSONObject c = user_detail_jsonarray.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt(TAG_user_id);
System.out.println("user id from json"+id);
String name_fromjson = c.getString(TAG_user_name);
System.out.println("user name from json"+name_fromjson);
int phone_no_fromjson = c.getInt(TAG_user_phone);
System.out.println("user phone from json"+phone_no_fromjson);
int ref_id_fromjson = c.getInt(TAG_ref_id);
System.out.println("user ref id from json"+ref_id_fromjson);
}
} catch (JSONException e) {
e.printStackTrace();
}
But i am countiniously getting Exception in this line
user_detail_jsonarray = json.getJSONArray(TAG_user_detail);
My Stake Trace message is as
{"ref_id":1295,"user_name":"chand","user_phone":"9620085675","user_id":"1"} at user_details of type org.json.JSONObject cannot be converted to JSONArray
I tried many link but unfortunately i am not able to get my result. Please any body just help me to solve this issue. Thanks in advance to all
Its clear from error that you are trying to convert Json Object into Json array. That should not.
Here is the code to read your JSON response.
String json = "Assuming that here is your JSON response";
try {
JSONObject parentObject = new JSONObject(json);
JSONObject userDetails = parentObject.getJSONObject("user_details");
//And then read attributes like
String name = userDetails.getString("user_name");
String phone = userDetails.getString("user_phone");
String id = userDetails.getString("ref_id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above code is for {"user_details":{"user_id":"1","user_name":"chand","user_phone":"9620085675","ref_id":6386}} JSON.
Learn from exception
org.json.JSONObject cannot be converted to JSONArray
You are getting this exception org.json.JSONObject cannot be converted to JSONArray
because you are trying to convert JSONObject to JSONArray which is not possible.
{ represents json object node
[ represents json array node
your jsondata is json object format. change this line
JsonObject user_detail_jsonobj = json.getJSONObject(TAG_user_detail);
I can't figure out whats wrong with this code , it's supposed to get data from php page that i created.
I'm using Eclipse with android SDK.
package com.myproject.myproject2;
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.ParseException;
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.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class EntList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entlist);
JSONArray jsonArray = null;
String jsonString = null;
StringBuilder stringBuilder = null;
InputStream inStream = null;
TextView tv = (TextView) findViewById(R.id.listtitle);
ArrayList<NameValuePair> nVPArray = new ArrayList<NameValuePair>(); //This is empty because you're asking for data
try{
//Connect to your script, and save get an object to read the data (inStream)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sawtaljabal.com/ar/android_connect/test.php"); // Be sure to replace with your actual script
post.setEntity(new UrlEncodedFormEntity(nVPArray));
HttpResponse postResponse = client.execute(post);
HttpEntity responseEntity = postResponse.getEntity();
inStream = responseEntity.getContent();
}catch(Exception e){
Log.e("Error connecting", e.getLocalizedMessage());
}
try{
//read the stream to a single JSON string
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"iso-8859-1"), 10); // iso-8859-1 is the character converter
stringBuilder = new StringBuilder();
stringBuilder.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inStream.close();
jsonString = stringBuilder.toString();
}catch(Exception e){
Log.e("Error creating JSON string", e.getLocalizedMessage());
}
try{
//Turn the JSON string into an array of JSON objects
jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = null;
for(int i=0;i< jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
//do something with the object, like String data = jsonObject.getString("KEY");
String data = jsonObject.getString("n_t");
tv.setText(data);
}
}
catch(JSONException e){
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I don't even know what to try , can u help me please, this is my first Application.
To connect php using Android
first your have to call a web service (which may be a php page returning json), call to this page should be in AsynTask class.
Then you need to parse json in right way.
You can try any good tutorial for this. Try this
If this is your first android app you may want to try cloning this project and learn with code there:
https://github.com/jgilfelt/android-jsonarrayadapter?files=1
Hope it helps.
Are you sure, the String you are getting in the response is a JSON Array. I think it should be a JSON object by which you can get the further JSON Array .
which means
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonString);
} catch (JSONException e) {
}
and then parse the JSON array from JSON Object.
Check Out this link, it might be helpful.
Also do all networking call in AsynTask or in a different thread.
I've been working on an open source code of a Twitter reader (read only) (oauth 2.0) that pulls JSON from a user timeline. It successfully pulls the JSON from Twitter API 1.1. The challenge I'm facing is converting that JSON into something user friendly. I've implemented sections of another source code that focused on parsing the JSON, but I'm not very familiar with parsing JSON. It's patchwork so I know I might be overlooking something. Possibly a redundancy or missing part.
UPDATED:
When I run the app, it doesn't crash, it's just stuck at "Got Token!". What I'm hoping to display is a list of tweets somewhat formatted to look like one. I believe it's the MainActivity, but I could be wrong. You will need a Consumer Key and Secret to test. I'll put up what I have at the moment, but if anyone knows how I can get out of that loop, I'd appreciate your input.
Thanks!
MainActivity.java
package com.example.readtwitterfeed;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
import com.example.readtwitterfeed.R;
public class MainActivity extends Activity {
// CONSUMER API KEY - 21 characters (go here to get one: https://dev.twitter.com/apps/)
// **** CHANGE THIS ****
static final String twitterAPIKEY = "################";
// CONSUMER SECRET - 41 characters (go here to get one: https://dev.twitter.com/apps/)
// **** CHANGE THIS ****
static final String twitterAPISECRET = "###############################";
static final String twitterAPIurl = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
// Twitter 'Screen Name'
// **** CHANGE THIS ****
static final String screenName = "Insert_Username_Here";
// Tweets to return
// **** CHANGE THIS, if needed ****
static final int tweets2Return = 1;
// Final URL will look like this (# is your sreen name/return tweets):
// https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=###&include_rts=1&count=#
static String tweeterURL = twitterAPIurl + screenName
+ "&include_rts=1&count=" + tweets2Return;
static String twitterToken = null;
static String jsonTokenStream = null;
static String jsonFeed = null;
static String tweetJSON = null;
TextView twitterText;
// ////////////////////////////////////
// onCreate - Let's get the GUI going
// ////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twitterText = (TextView) findViewById(R.id.tweetFeed);
// Call first AsyncTask
new loadTwitterToken().execute();
}
// ////////////////////////////////////////////////////////////////////
// AsyncTask - First, let's get our Token for oAuth (from Twitter)
// If you need oAuth help: https://dev.twitter.com/docs/auth/oauth/faq/
// ////////////////////////////////////////////////////////////////////
protected class loadTwitterToken extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
//As of this writing, Twitter says, "We do not currently expire access tokens."
try {
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(
"https://api.twitter.com/oauth2/token");
String apiString = twitterAPIKEY + ":" + twitterAPISECRET;
String authorization = "Basic "
+ Base64.encodeToString(apiString.getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization", authorization);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
httppost.setEntity(new StringEntity(
"grant_type=client_credentials"));
InputStream inputStream = null;
// Let's send to web
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Our response
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
// Will look like this:
// {"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAABiQTgAAAAAACGie2o%2Bm7jNnxw8txVG99c1wAU8%3DmZq7qrX8JZpDFrgYyh5gLtOkJhQ7BvPD6bZ0ssitjg"}
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
jsonTokenStream = sb.toString();
// onPostExecute likes to get a parameter passed to work right.
// Just passing something.
return 1;
} catch (Exception e) {
Log.e("loadTwitterToken",
"doInBackground Error:" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(Integer result) {
// Extract Token from JSON stream
try {
JSONObject root = new JSONObject(jsonTokenStream);
twitterToken = root.getString("access_token");
} catch (Exception e) {
Log.e("loadTwitterToken", "onPost Error:" + e.getMessage());
}
twitterText.setText("Got Token!");
// Now that we have a oAuth Token, lets get our JSON feed from twitter.
// We call it from here to make sure the Token has been received already.
new loadTwitterFeed().execute();
}
}
// ///////////////////////////////////////////////////////////
// AsyncTask - Download Twitter Feed w/Token as authorization
// //////////////////////////////////////////////////////////
protected class loadTwitterFeed extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
BufferedReader reader =null;
try{
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpGet httpget = new HttpGet(tweeterURL);
httpget.setHeader("Authorization", "Bearer " + twitterToken);
httpget.setHeader("Content-type", "application/json");
InputStream inputStream = null;
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
return null;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (reader != null)
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result) {
StringBuilder sb = new StringBuilder();
try{
JSONObject resultObject = new JSONObject(result);
org.json.JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
JSONObject tweetObject = tweetArray.getJSONObject(t);
sb.append(tweetObject.getString("from_user")+": ");
sb.append(tweetObject.get("text")+"\n\n");
}
}
catch (Exception e) {
Log.e("Tweet", "Error retrieving JSON stream" + e.getMessage());
jsonFeed = sb.toString();
e.printStackTrace();
}
}
}
/*String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}*/
protected void onPostExecute(Integer result) {
// Update GUI
if (jsonFeed.length() > 0) {
twitterText.setText(jsonFeed);
} else {
//I'd assume wrong Consumer Key/Secret if this happens.
twitterText.setText("Nothing Returned");
}
}
}
Activity_Main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tweetFeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading..." />
</ScrollView>
You forgot to close the ProgressDialog in onPostExecute method.
just do this pd.dismiss(); in onPostExecute like this.
#Override
protected void onPostExecute(Integer result) {
pd.dismiss();
// Extract Token from JSON stream
try {
JSONObject root = new JSONObject(jsonTokenStream);
twitterToken = root.getString("access_token");
} catch (Exception e) {
Log.e("loadTwitterToken", "onPost Error:" + e.getMessage());
}
twitterText.setText("Got Token!");
// Now that we have a oAuth Token, lets get our JSON feed from twitter.
// We call it from here to make sure the Token has been received already.
new loadTwitterFeed().execute();
}
I am having issues with my attempt to connect via JSON to a PHP file to access MySQL in android. I cannot for the life of me figure out why this is causing my app to crash. Any ideas?
It is throwing the following error:
AndroidRuntime
FATAL EXCEPTION: main
I am attemping to call this from my main activity:
new getData().getMovie();
Which calls this:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.*;
import org.json.*;
import android.util.Log;
import android.widget.Toast;
public class getData extends FullscreenActivity{
public void getMovie() {
String result = "";
String rID="1";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ids",rID));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/myphp.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch(Exception e){
Toast.makeText(this, "Error in http connection "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
InputStream is = null;
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){
Toast.makeText(this, "Error converting result "+e.toString(), Toast.LENGTH_LONG).show();
//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","id: "+json_data.getString("id")+
", 1: "+json_data.getString("1")+
", 2: "+json_data.getString("2")+
", 3: "+json_data.getString("3")+
", 4: "+json_data.getString("4")+
", 5: "+json_data.getString("5")
);
}
} catch (JSONException e) {
Toast.makeText(this, "Error parsing data "+e.toString(), Toast.LENGTH_LONG).show();
//Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
First, make sure your app requests the INTERNET permission. More on that here. Second, you can significantly declutter your code using the droidQuery library:
public void getMovie() {
$.ajax(new AjaxOptions().url("http://website.com/myphp.php")
.type("POST")
.dataType("JSON")
.data("{ids: 1}")
.context(this)
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
JSONArray json = (JSONArray) params[0];
Object[] datas = $.makeArray(json);
for (Object data : datas) {
JSONObject obj = (JSONObject) data;
Map<String, ?> map = $.map(obj);
Log.i("log_tag", map.toString());//will print all JSON Objects in a Key-Value format, such as "{1, 'text'}"
}
}
})
.error(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
String reason = (String) params[2];
droidQuery.toast("Error in Ajax Request: " + reason, Toast.LENGTH_LONG);
}
}));
}
Thirdly, if you are still getting error, surround your call to getMovie() in a try-catch block, catching a Throwable instead of an Exception:
try {
new getData().getMovie();
}
catch (Throwable t) {
t.printStackTrace();
}