im am currently creating a CMS applicationa and i am trying to create a JSON object that i can post to my API but i have no idea on how to do this because im new to android. does anyone have an Idea?
My code:
String URL = "http://test.soundwave.drieo.nl/api/content/" + uid + "?apikey=aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
try {
APIClientJSONObject api = new APIClientJSONObject();
JSONObject result = null;
try {
result = api.execute(URL).get();
} catch (Exception e) {
e.printStackTrace();
}
try {
String content = result.optString("FormattedName");
String content2 = result.optString("Title");
String content3 = result.optString("Subtitle");
String content4 = result.optString("Text");
EditText name = (EditText) findViewById(R.id.etInternNaam);
name.setText(content);
EditText titel = (EditText) findViewById(R.id.etName);
titel.setText(content2);
EditText ondertitel = (EditText) findViewById(R.id.etOndertitel);
ondertitel.setText(content3);
EditText EditText = (EditText) findViewById(R.id.etTekst);
EditText.setText(Html.fromHtml(content4));
if("null" == content) {
name.setText("");
}
if("null" == content2) {
titel.setText("");
}
if("null" == content3) {
ondertitel.setText("");
}
if("null" == content4) {
EditText.setText("");
}
} catch (Exception e) {
e.printStackTrace();
}
API code:
package nl.drieo.soundwave.test.cms;
import android.os.AsyncTask;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
/**
* Created by r.devries on 14-3-2016.
*/
public class APIClientJSONObject extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = new JSONObject(builder.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
you can create JSONObject like this and put your data into that:
JSONObject json = new JSONObject();
json.put("user", "example");
after putting your data to json, you can pass the json to the 'APIClientJSONObject' class by this way:
EDIT: use this code in to OnClickListener for your Button
try {
result = api.execute(URL,json.toString()).get();
} catch (Exception e) {
e.printStackTrace();
}
and you can get Json in 'APIClientJSONObject' class like this:
JSONObject jsonObject = new JSONObject(params[1])
or if you want 'POST' this json to the webservice, you can use: EDIT: use this in to the APIClientJSONObject class in doInBackground method:
HttpPost httpost = new HttpPost(params[0]);
StringEntity stringentity = new StringEntity(params[1]);
httpost.setEntity(stringentity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
httpclient.execute(httpost, responseHandler);
I hope these code are useful for you.
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 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
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();
}