Getting JSONException with Retrofit 2 on Android - android

I am using Fabric.io Twitter Kit. Created a custom service class and used Retrofit to convert the interface within that class. Code at the bottom (CustomTwitterApiClient Class).
I either get NullPointerException and if I catch that, I get JSONException. As can be seen in the log, I can get trends response but I cant read it. If I try to readLine() it and append it to a StringBuilder, I get null.
I wrote the code with the guidance of this SO answer.
What I am doing wrong ?
Thanks in advance.
PS: Those extra exception handlers just to get a clean log.
D/LOG-DEBUG: Line 86 : [{"trends":[{"name":"#Worlds","url":"http:\/\/twitter.com\/search?q=%23Worlds","promoted_content":null,"query":"%23Worlds","tweet_volume":99974},{"name":"#LaNocheDeML","url":"http:\/\/twitter.com\/search?q=%23LaNocheDeML","promoted_content":null,"query":"%23LaNocheDeML","tweet_volume":56697},{"name":"#CLEMVSFSU","url":"http:\/\/twitter.com\/search?q=%23CLEMVSFSU","promoted_content":null,"query":"%23CLEMVSFSU","tweet_volume":10016},{"name":"#\u0634\u064A_\u062A\u062D\u0628_\u062A\u0634\u0645\u0647","url":"http:\/\/twitter.com\/search?q=%23%D8%B4%D9%8A_%D8%AA%D8%AD%D8%A8_%D8%AA%D8%B4%D9%85%D9%87","promoted_content":null,"query":"%23%D8%B4%D9%8A_%D8%AA%D8%AD%D8%A8_%D8%AA%D8%B4%D9%85%D9%87","tweet_volume":52441},{"name":"#DiosdadoEsPueblo","url":"http:\/\/twitter.com\/search?q=%23DiosdadoEsPueblo","promoted_content":null,"query":"%23DiosdadoEsPueblo","tweet_volume":44538},{"name":"Juanma","url":"http:\/\/twitter.com\/search?q=Juanma","promoted_content":null,"query":"Juanma","tweet_volume":13642},{"name":"Vince Vaughn","url":"http:\/\/twitter.com\/search?q=%22Vince+Vaughn%22","promoted_content":null,"query":"%22Vince+Vaughn%22","tweet_volume":10409},{"name":"Florida State","url":"http:\/\/twitter.com\/search?q=%22Florida+State%22","promoted_content":null,"query":"%22Florida+State%22","tweet_volume":10936},{"name":"Francois","url":"http:\/\/twitter.com\/search?q=Francois","promoted_content":null,"query":"Francois","tweet_volume":24324},{"name":"HOJE TEM TWD","url":"http:\/\/twitter.com\/search?q=%22HOJE+TEM+TWD%22","promoted_content":null,"query":"%22HOJE+TEM+TWD%22","tweet_volume":null},{"name":"Atividade Paranormal 4","url":"http:\/\/twitter.com\/search?q=%22Atividade+Paranormal+4%22","promoted_content":null,"query":"%22Atividade+Paranormal+4%22","tweet_volume":null},{"name":"BELIEBERS VOTANDO","url":"http:\/\/twitter.com\/search?q=%22BELIEBERS+VOTANDO%22","promoted_content":null,"query":"%22BELIEBERS+VOTANDO%22","tweet_volume":56259},{"name":"South Carolina","url":"http:\/\/twitter.com\/search?q=%22South+Carolina%22","promoted_content":null,"query":"%22South+Carolina%22","tweet_volume":16795},{"name":"Deshaun Watson","url":"http:\/\/twitter.com\/search?q=%22Deshaun+Watson%22","promoted_content":null,"query":"%22Deshaun+Watson%22","tweet_volume":12224},{"name":"Soulja Boy","url":"http:\/\/twitter.com\/search?q=%22Soulja+Boy%22","promoted_content":null,"query":"%22Soulja+Boy%22","tweet_volume":196642},{"name":"\uB864\uB4DC\uCEF5","url":"http:\/\/twitter.com\/search?q=%EB%A1%A4%EB%93%9C%EC%BB%B5","promoted_content":null,"query":"%EB%A1%A4%EB%93%9C%EC%BB%B5","tweet_volume":null},{"name":"Racing","url":"http:\/\/twitter.com\/search?q=Racing","promoted_content":null,"query":"Racing","tweet_volume":69655},{"name":"Jimbo","url":"http:\/\/twitter.com\/search?q=Jimbo","promoted_content":null,"query":"Jimbo","tweet_volume":null},{"name":"Silver Scrapes","url":"http:\/\/twitter.com\/search?q=%22Silver+Scrapes%22","promoted_content":null,"query":"%22Silver+Scrapes%22","tweet_volume":null},{"name":"#\u0627\u0646\u0627_\u0645\u0648\u0627\u0637\u0646_\u0645\u062B\u0644\u064A_\u0645\u062B\u0644\u0643\u0645","url":"http:\/\/twitter.com\/search?q=%23%D8%A7%D9%86%D8%A7_%D9%85%D9%88%D8%A7%D8%B7%D9%86_%D9%85%D8%AB%D9%84%D9%8A_%D9%85%D8%AB%D9%84%D9%83%D9%85","promoted_content":null,"query":"%23%D8%A7%D9%86%D8%A7_%D9%85%D9%88%D8%A7%D8%B7%D9%86_%D9%85%D8%AB%D9%84%D9%8A_%D9%85%D8%AB%D9%84%D9%83%D9%85","tweet_volume":23899},{"name":"#\u0627\u0637\u0631\u062F\u0648_\u0627\u0635\u062D\u0627\u0628_\u0627\u0644\u0642\u0647\u0648\u0647_\u0627\u0644\u0633\u0648\u062F\u0627\u0621","url":"http:\/\/twitter.com\/search?q=%23%D8%A7%D8%B7%D8%B1%D8%AF%D9%88_%D8%A7%D8%B5%D8%AD%D8%A7%D8%A8_%D8%A7%D9%84%D9%82%D9%87%D9%88%D9%87_%D8%A7%D9%84%D8%B3%D9%88%D8%AF%D8%A7%D8%A1","promoted_content":null,"query":"%23%D8%A7%D8%B7%D8%B1%D8%AF%D9%88_%D8%A7%D8%B5%D8%AD%D8%A7%D8%A8_%D8%A7%D9%84%D9%82%D9%87%D9%88%D9%87_%D8%A7%D9%84%D8%B3%D9%88%D8%AF%D8%A7%D8%A1","tweet_volume":null},{"name":"#\u0627\u0646\u0627_\u0645\u062F\u0627\u0648\u0
D/LOG-DEBUG: Line 111:
W/System.err: org.json.JSONException: End of input at character 0 of
W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:92)
W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err: at .MainActivity$1$1.onResponse(MainActivity.java:113)
W/System.err: at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
And this the code block the error pointing :
#Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
CustomTwitterApiClient customTwitterApiClient = new CustomTwitterApiClient(session);
Call<ResponseBody> cevap = customTwitterApiClient.getCustomService().show(1);
cevap.enqueue(new retrofit2.Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
BufferedReader reader = null;
StringBuilder stringBuilder2 = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
} catch (Exception e) {
e.printStackTrace();
}
try {
Log.d("READER", "86 : reader.readLine() : "+reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
String line= "";
try{
while ((line = reader.readLine())!= null)
{
try {
stringBuilder2.append(line);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
catch(IOException e){
e.printStackTrace();
}
try {
Log.d("READER", "111: stringBuilder2.toString(): " +stringBuilder2.toString());
} catch (Exception e) {
e.printStackTrace();
}
try {
JSONArray sonucJsonArray = new JSONArray(stringBuilder2.toString());
JSONObject sonucJsonObject = sonucJsonArray.getJSONObject(0);
JSONArray trendsJsonArray = sonucJsonObject.getJSONArray("trends");
JSONObject trendJson;
for(int i=0; i < trendsJsonArray.length() ; i++){
TrendTopic trend = new TrendTopic();
trendJson = trendsJsonArray.getJSONObject(i);
trend.set_id(i+1);
trend.set_trendName(trendJson.getString("name"));
trend.set_trendQuery(trendJson.getString("query"));
trend.set_trendURL(trendJson.getString("url"));
trendTopics.add(i,trend);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is the CustomTwitterApiClient Class :
public class CustomTwitterApiClient extends TwitterApiClient {
public CustomTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {
#GET("/1.1/trends/place.json")
Call<ResponseBody> show(#Query("id") int id);
}

Related

Android studio web socket - Error receiving multiple JSON objects at once

I am struggling with something that really p*sses me off for several hours.
My android app manages to connect to a websoket, and receives json data which for now has worked perfectly, and here is the code for this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
This code above as I said works perfectly, and i get the data in everytime. HOWEVER, HOWEVER, HOWEVER: If i try to receive 2 json-objects at the sametime through this emittener, it does not work!!!!
Here is example when i try to receive multiple JSON objects, and NONE of them works!
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetFromSensor = new JSONObject( (String) args[0]);
int targetNum = incomingTargetFromSensor.getInt("target_number_count");
showTargetRep(targetNum); //NOT WORKING!
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position); //NOT WORKING!
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
In the first example I could receive the position data, and the code is exactly similar as the example above, but for some reasons it can not recevice data when i try to receive another JSON object.
Another example of why I always disliked JSON object.
Any help plz?
The solution at the end was to add multiple try/catches like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetRepFromSensor = new JSONObject((String ) args[0]);
int target_rep = incomingTargetRepFromSensor.getInt("target_repetition_count");
showTargetRep(target_rep);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingDataFromSensor = new JSONObject((String ) args[0]);
double the_position = incomingDataFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingTargetSetFromSensor = new JSONObject((String ) args[0]);
int target_set = incomingTargetSetFromSensor.getInt("target_set_count");
showTargetSet(target_set);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingRepsFromSensor = new JSONObject((String ) args[0]);
int the_repetitions = incomingRepsFromSensor.getInt("repetitions");
showCurrentReps(the_repetitions);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingSetsFromSensor = new JSONObject((String ) args[0]);
int the_sets = incomingSetsFromSensor.getInt("sets");
showCurrentSets(the_sets);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}

java.lang.NullPointerException: No authentication header information #467

private void setOauthParameter() {
GoogleOAuthParameters oauthParam = new GoogleOAuthParameters();
oauthParam.setOAuthConsumerKey(ClientId);
oauthParam.setOAuthConsumerSecret(ClientSecrate);
oauthParam.setOAuthType(OAuthParameters.OAuthType.TWO_LEGGED_OAUTH);
// Init the service and set the auth
service = new ContactsService("chat.com.contactssharing");
try {
service.setOAuthCredentials(oauthParam, new OAuthHmacSha1Signer());
service.getRequestFactory().setHeader("User-Agent", "chat.com.contactssharing");
} catch (OAuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void queryEntries() throws IOException, ServiceException {
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(50);
myQuery.setStartIndex(1);
myQuery.setStringCustomParameter("showdeleted", "false");
myQuery.setStringCustomParameter("requirealldeleted", "false");
myQuery.setStringCustomParameter("sortorder", "ascending");
try {
// Execution of this line i'm getting an exception
ContactFeed resultFeed = (ContactFeed) this.service.query(myQuery, ContactFeed.class);
Log.d(TAG, resultFeed.toString());
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
}
System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");
} catch (Exception ex) {
System.err.println("Not all placehorders of deleted entries are available");
}
}
My objective to get the friends contacts list from gmail and i have check no's of post for this Exception but no one is commented by correct solution.It's become blocker for me so please help me to out this problem and guide what is doing wrong at above code.

Thread-safe asynchronous Retrofit request

I'm struggling for few weeks now with this issue. I'm posting geolocation points to a server using Retrofit 2.0. I'm using a IntentService that I call every now and then when I have a new point to post.
For some reason, the server record the same point multiple time creating LOTS of duplicates. It seems that when I call my service and it's already active, it's will query the points and start a new request using some of the same points as was queried by the previous request. I also delete the point only when the request succeed. Is there a way to wait until executing the next batch of points?
How can I wait until all the processed point are sent to the server?
private String postAmazonPoints() throws IOException, JSONException {
ArrayList<EntityPoint> points = new ArrayList<>(GenericDAO.getInstance(EntityPoint.class).queryForAll());
if (points.size() == 0) {
return RESULT_OK;
}
if (connectAmazonApi()) {
int pointSize = points.size();
if(pointSize>5){
for(int i = 0; i<pointSize; i+=5){
int end = i+5;
if( end > pointSize ){
end = pointSize;
}
paginatePostPoint(points.subList(i, end-1));
}
}else{
paginatePostPoint(points.subList(0, pointSize-1));
}
}
return RESULT_OK;
}
private void paginatePostPoint(final List<EntityPoint> points) throws IOException, JSONException {
EntityPoints mPoints = new EntityPoints(points);
Call<ResponseBody> call = amazonServices.postGeopoints(mPoints);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
JSONObject json;
try {
json = (response != null ? new JSONObject(response.body().string()) : null);
Log.e(TAG, json.toString());
if(RESULT_OK.equals(handleJsonRequest(json))){
deleteDatabasePoints(points);
Log.e(TAG, "Point are correctly posted");
}else{
addFirebaseMsg(json.toString());
}
} catch (JSONException e) {
Log.e(TAG, e.getLocalizedMessage());
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
} else {
try {
addFirebaseMsg(response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
addFirebaseMsg(t.getMessage());
}
});
}
private void addFirebaseMsg(String message){
isConnectedToAmz = false;
Bundle params = new Bundle();
params.putString(FirebaseAnalytics.Param.VALUE, message.substring(0, Math.min(message.length(), 30)));
mFirebaseAnalytics.logEvent(Constants.EVENT_TAG_ERROR, params);
Log.d(TAG, message);
}
private boolean connectAmazonApi() {
if (isConnectedToAmz) {
return true;
}
Call<ResponseBody> call = amazonServices.postAuthenticate(settings.getString("token", ""),settings.getString(MyInstanceIDFireService.FIREBASE_TOKEN, ""), settings.getString("id", ""));
String errMsg = "";
try {
ResponseBody response = call.execute().body();
JSONObject json = (response != null ? new JSONObject(response.string()) : null);
if (json != null) {
Log.e(TAG, "Response: " + json.toString());
RetrofitCreator.setAmazonToken(json.getString("token"));
isConnectedToAmz = true;
return true;
}
Log.w(TAG, "Impossible to connect to Amazon API : " + json);
} catch (JSONException e) {
errMsg = e.getMessage();
} catch (IOException e) {
errMsg = e.getMessage();
}
Log.w(TAG, "Impossible to connect to Amazon API");
Bundle params = new Bundle();
params.putLong(FirebaseAnalytics.Param.VALUE, 1);
params.putString(FirebaseAnalytics.Param.VALUE, errMsg.substring(0, Math.min(errMsg.length(), 30)));
mFirebaseAnalytics.logEvent(Constants.EVENT_AMAZON_UNAVAILABLE, params);
return false;
}
You can use .execute instead of .enqueue and request will be synchronous, but in this case you should care about creating another thread for it. Create some service with asynсtask for example with queue.

Json Parsing from Url In Android , Not working

I am parsing data from URL , Its Getting below mentioned Error.
Raw Data is Showing Perfectly from Server.Not able to Split the Data Using Json Parsing.
Please help me solve this error
EDIT : 1
Json Response from URL
[
{
"ID": 4,
"Name": "Vinoth",
"Contact": "1111111111",
"Msg": "1"
},
{
"ID": 5,
"Name": "Mani",
"Contact": "22222222",
"Msg": "1"
},
{
"ID": 6,
"Name": "Manoj",
"Contact": "33333333333",
"Msg": "1"
}
]
Error :
org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:135)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:58)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:632)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.Looper.loop(Looper.java:136)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5584)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err: at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
public class MainActivity extends Activity {
TextView name1,email,status,face;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.button1);
name1 = (TextView)findViewById(R.id.sname);
email = (TextView)findViewById(R.id.email);
status = (TextView)findViewById(R.id.status);
face = (TextView)findViewById(R.id.fb);
GetServerData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Server Request URL
String serverURL = "http://webapp/api/values";
// Create Object and call AsyncTask execute Method
new LoadService().execute(serverURL);
}
});
}
// Class with extends AsyncTask class
private class LoadService extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private final String TAG = null;
String name = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
// UI Element
uiUpdate.setText("");
Dialog.setMessage("Loading service..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
// NOTE: Don't call UI Element here.
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// Close progress dialog
Dialog.dismiss();
Log.e(TAG, "------------------------------------- Output: " + Content);
try {
JSONArray jArr=new JSONArray(Content);
for(int i=0;i<jArr.length();i++) {
JSONObject json=jArr.getJSONObject(i);
name1.setText(json.getString("Name"));
email.setText(json.getString("ID"));
status.setText(json.getString("Contact"));
face.setText(json.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("EXCEPTION ","");
}
uiUpdate.setText("Raw Output : " + Content);
}
}
}
As per your response is JSONArray and gson library is better to use while json data parsing so use below class to any type of data like that
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ApiData {
#SerializedName("data")
#Expose
private JsonArray Data;
public <T> List<T> getData(Class<T> c) {
Type type = new ListParams(c);
return new Gson().fromJson(Data, type);
}
private class ListParams implements ParameterizedType {
private Type type;
private ListParams(Type type) {
this.type = type;
}
#Override
public Type[] getActualTypeArguments() {
return new Type[]{type};
}
#Override
public Type getRawType() {
return ArrayList.class;
}
#Override
public Type getOwnerType() {
return null;
}
#Override
public boolean equals(Object o) {
return super.equals(o);
}
}
}
Create model class like :
public class Model{
String ID;
String Name;
String Contact;
String msg;
}
Now parse your data like:
ApiData apiData = new Gson().fromJson(Content, ApiData.class);
Lis<Model> models = apiData.getData(Model.class);
try {
Object jsonObject = new JSONTokener(Content).nextValue();
JSONArray jArr=new JSONArray(jsonObject );
for(int i=0;i<jArr.length();i++) {
JSONObject json=jArr.getJSONObject(i);
name1.setText(json.getString("Name"));
email.setText(json.getString("ID"));
status.setText(json.getString("Contact"));
face.setText(json.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("EXCEPTION ","");
}
Directly you cannot apply string to array, you should convert string to jsonobject ,then you can do object to array.
Hope you understand
As i have added escaping to your json here only for storing it temporary :
Please check below parsing code and it is working for me :
String response = "[\r\n {\r\n \"ID\": 4,\r\n \"Name\": \"Vinoth\",\r\n \"Contact\": \"1111111111\",\r\n \"Msg\": \"1\"\r\n },\r\n {\r\n \"ID\": 5,\r\n \"Name\": \"Mani\",\r\n \"Contact\": \"22222222\",\r\n \"Msg\": \"1\"\r\n },\r\n {\r\n \"ID\": 6,\r\n \"Name\": \"Manoj\",\r\n \"Contact\": \"33333333333\",\r\n \"Msg\": \"1\"\r\n }\r\n]";
try {
JSONArray jsonArray = new JSONArray(response); // replace response with your response string
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("ID", jsonObject.getInt("ID") + "");
Log.e("Name", jsonObject.getString("Name"));
Log.e("Contact", jsonObject.getString("Contact"));
Log.e("Msg", jsonObject.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Logs I have printed :
12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 4 12-17
15:42:54.459 9064-9064/com.example.testapplication E/Name: Vinoth
12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact:
1111111111 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Msg: 1 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/ID: 5 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Name: Mani 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Contact: 22222222 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Msg: 1 12-17 15:42:54.459
9064-9064/com.example.testapplication E/ID: 6 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Name: Manoj 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Contact: 33333333333 12-17
15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1
Thanks ..!
The documentation of public JSONArray (String json) says it throws a
JSONException if the parse fails or doesn't yield a JSONArray.
Maybe he can't handle your response which is quite funny because a simple online json parser can: http://json.parser.online.fr/
As the user "Jelle van Es" mentioned in a previous comment, I would try Gson to do the work. (I would have commented under his comment but I have to few reputation xD)
You are using getString on "ID" when you should be using getInt. I tested the JSON string you provided in your question. The following code works:
String json =
"[{\"ID\":4,\"Name\":\"Vinoth\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Mani\",\"Contact\":\"22222222\",\"Msg\":\"1\"},{\"ID\":6,\"Name\":\"Manoj\",\"Contact\":\"33333333333\",\"Msg\":\"1\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0, len = jsonArray.length(); i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("ID");
String name = jsonObject.getString("Name");
String contact = jsonObject.getString("Contact");
String msg = jsonObject.getString("Msg");
System.out.println("id=" + id + ", name='" + name + "\', contact='" + contact + "\', msg='" + msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
Output from running the above code:
id=4, name='Vinoth', contact='1111111111', msg='1
id=5, name='Mani', contact='22222222', msg='1
id=6, name='Manoj', contact='33333333333', msg='1
If you are still getting an error, post the stacktrace.
Check this linkJSONArray
You should not directly use the response you get after hitting web service.First convert it to string as given in the link and also use getInt() when you are parsing your id
You can Parse your JSON like below.
try {
JSONArray _jArray = new JSONArray("YOUR_RESPONSE");
if (_jArray.length()>0){
for (int i = 0 ; i < _jArray.length();i++){
JSONObject _jSObject = _jArray.getJSONObject(i);
int ID = _jSObject.getInt("ID");
String Name = _jSObject.getString("Name");
String Contact = _jSObject.getString("Contact");
String Msg = _jSObject.getString("Msg");
System.out.println("Id : " + ID);
System.out.println("Name : " + Name);
System.out.println("Contact : " + Contact);
System.out.println("Msg : " + Msg);
}
}
} catch (Exception e) {
e.printStackTrace();
}
Best way and very fast parsing of JSON is GSON liabrary
dependacy for android studio compile 'com.google.code.gson:gson:2.3.1' OR you can download jar.
Make DTO names of all strings exactly same json of resonse.
Class ClassDTO{
String ID;
String Name;
String Contact;
String Msg;
take gettters & setters
}
Just include this lines in your code.
JSONArray array=new JSONArray(Content);
if (array.length() > 0) {
Gson gson = new Gson();
int i = 0;
while (i < array.length()) {
list.add(gson.fromJson(array.getJSONObject(i).toString(), ClassDTO.class));
i++;
}
} else {
Toast.makeText(JobCardActivity.this, "No response from server", Toast.LENGTH_LONG).show();
}
for json url hit and parsing of the data i have use this way
First i have created a class for Async request
public class AsyncRequestForActivities extends
AsyncTask<String, Integer, String> {
OnAsyncRequestComplete caller;
Context context;
String method = "POST";
List<NameValuePair> parameters = null;
ProgressDialog pDialog = null;
String Progress_msg;
// Three Constructors
public AsyncRequestForActivities(Context a, String m, String Msg,
List<NameValuePair> p) {
caller = (OnAsyncRequestComplete) a;
context = a;
method = m;
parameters = p;
Progress_msg = Msg;
}
public AsyncRequestForActivities(Context a, String m) {
caller = (OnAsyncRequestComplete) a;
context = a;
method = m;
}
public AsyncRequestForActivities(Context a) {
caller = (OnAsyncRequestComplete) a;
context = a;
}
// Interface to be implemented by calling activity
public interface OnAsyncRequestComplete {
public void asyncResponse(String response);
}
public String doInBackground(String... urls) {
// get url pointing to entry point of API
String address = urls[0].toString();
if (method == "POST") {
return post(address);
}
if (method == "GET") {
return get(address);
}
return null;
}
public void onPreExecute() {
pDialog = new ProgressDialog(context);
pDialog.setMessage(Progress_msg); // typically you will
pDialog.setCancelable(false); // define such
// strings in a remote file.
pDialog.show();
}
public void onProgressUpdate(Integer... progress) {
// you can implement some progressBar and update it in this record
// setProgressPercent(progress[0]);
}
public void onPostExecute(String response) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
caller.asyncResponse(response);
}
protected void onCancelled(String response) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
caller.asyncResponse(response);
}
#SuppressWarnings("deprecation")
private String get(String address) {
try {
if (parameters != null) {
String query = "";
String EQ = "=";
String AMP = "&";
for (NameValuePair param : parameters) {
query += param.getName() + EQ
+ URLEncoder.encode(param.getValue()) + AMP;
}
if (query != "") {
address += "?" + query;
}
}
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(address);
HttpResponse response = client.execute(get);
return stringifyResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
private String post(String address) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
if (parameters != null) {
post.setEntity(new UrlEncodedFormEntity(parameters));
}
HttpResponse response = client.execute(post);
return stringifyResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
private String stringifyResponse(HttpResponse response) {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
return sb.toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
now when you want to get Data you have to implement the interface in your activity
public class SomeClass extends Activity implements OnAsyncRequestComplete{
// your activity code here
// some where in class in any function you want
AsyncRequestForActivities req=new AsyncRequestForActivities(SomeClass.this, MethodType, YourMessage,
Perameters_in_List<NameValuePareType>);
req.execute(YourURL);
}//end of that function
#Override
public void asyncResponse(String response) {
try {
if (!(response == null)) {
JSONArray jArray = new JSONArray("response");
if (jArray.length()>0){
for (int i = 0 ; i < jArray.length();i++){
JSONObject jSObject = jArray.getJSONObject(i);
int ID = _jSObject.getInt("ID");
String Name = _jSObject.getString("Name");
String Contact = jSObject.getString("Contact");
String Msg = jSObject.getString("Msg");
System.out.println("Id : " + ID);
System.out.println("Name : " + Name);
System.out.println("Contact : " + Contact);
System.out.println("Msg : " + Msg);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Display the posts in facebook application

How Display the posts in facebook application. I tried to work with sample android API for Facebook. But nothing worked fine. I need to display a post that i post on my Facebook wall in android emulator. I need a sample code to run and display the JSON response as my post.
Please send me few working links.
Attach the given code with your facebook login class
public void postOnWall() {
try {
String response = Config.facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", Config.myAccessToken);
parameters.putString("message", "I am Now On FB");
parameters.putString("description", "");
response = Config.facebook.request("me/feed", parameters,
"POST");
if (response == null || response.equals("") ||
response.equals("false")) {
}
} catch(Exception e) {
e.printStackTrace();
}
}
Below is the code and sdk official for facebook on android
https://github.com/facebook/facebook-android-sdk/blob/master/examples/stream/src/com/facebook/stream/StreamHandler.java
public class StreamHandler extends Handler {
private static final String CACHE_FILE = "cache.txt";
/**
* Called by the dispatcher to render the stream page.
*/
public void go() {
dispatcher.getWebView().addJavascriptInterface(
new StreamJsHandler(this), "app");
// first try to load the cached data
try {
String cached = FileIO.read(getActivity(), CACHE_FILE);
if (cached != null) {
JSONObject obj = new JSONObject(cached);
dispatcher.loadData(StreamRenderer.render(obj));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Facebook fb = Session.restore(getActivity()).getFb();
new AsyncFacebookRunner(fb).request("me/home",
new StreamRequestListener());
}
public class StreamRequestListener implements RequestListener {
public void onComplete(String response, final Object state) {
try {
JSONObject obj = Util.parseJson(response);
// try to cache the result
try {
FileIO.write(getActivity(), response, CACHE_FILE);
} catch (IOException e) {
e.printStackTrace();
}
// Convert the result into an HTML string and then load it
// into the WebView in the UI thread.
final String html = StreamRenderer.render(obj);
getActivity().runOnUiThread(new Runnable() {
public void run() {
dispatcher.loadData(html);
}
});
} catch (JSONException e) {
Log.e("stream", "JSON Error:" + e.getMessage());
} catch (FacebookError e) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
}
public void onFacebookError(FacebookError e, final Object state) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("stream", "Resource not found:" + e.getMessage());
}
public void onIOException(IOException e, final Object state) {
Log.e("stream", "Network Error:" + e.getMessage());
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("stream", "Invalid URL:" + e.getMessage());
}
}
}

Categories

Resources