So I was following this tutorial and it has this method.
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... voids) {
Reader reader=API.getData("http://beta.json-generator.com/api/json/get/DiIRBM4");
Type listType = new TypeToken<ArrayList<DoctorBean>>(){}.getType();
beanPostArrayList = new GsonBuilder().create().fromJson(reader, listType);
postList=new StringBuffer();
for(DoctorBean post: beanPostArrayList){
postList.append("\n heroName: "+post.getHeroName()+"\n realName: "+post.getRealName()+"\n\n");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.d("JSON Result ", postList.toString());
}
}.execute();
The Log Result would only show these values.
JSON Result:
heroName: null realName: null
heroName: null realName: null
heroName: null realName: null
This is my JSON data
[
{
"heroName": "Dr. Strange",
"realName": "Stephen Strange"
},
{
"heroName": "Spider-Man",
"realName": "Peter Paker"
},
{
"heroName": "Captain America",
"realName": "Stever Rogers"
}
]
This is my Data Model
import com.google.gson.annotations.SerializedName;
public class DoctorBean {
#SerializedName("heroName")
private String heroName;
#SerializedName("realName")
private String realName;
public DoctorBean(String heroName, String realName) {
this.heroName = heroName;
this.realName = realName;
}
public String getHeroName() {
return heroName;
}
public void setHeroName(String heroName) {
this.heroName = heroName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
And this is my API class
public class API {
private static Reader reader=null;
public static Reader getData(String SERVER_URL) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new InputStreamReader(content);
} else {
// Log.e("error:", "Server responded with status code: "+ statusLine.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader;
}
}
I noticed that the log Result showed 3 rows, so I was thinking it was able to get the length of the array correctly. But as for the data, all was null.
As per your given tutorial,from this link response is as below:
[
{
"date":"11/8/2014",
"auther":"nirav kalola",
"description":"json object parsing using gson library is easy",
"post_name":"json object parsing"
},
{
"date":"12/8/2014",
"auther":"nirav kalola",
"description":"json array parsing using gson library",
"post_name":"json array parsing"
},
{
"date":"17/8/2014",
"auther":"nirav kalola",
"description":"store json file in assets folder and get data when required",
"post_name":"json parsing from assets folder"
}
]
So you need to try below POJO class for GSONBuilder. Replace your name with BeanPost.
import com.google.gson.annotations.SerializedName;
public class BeanPost {
#SerializedName("post_name")
private String post_name;
#SerializedName("auther")
private String auther;
#SerializedName("date")
private String date;
#SerializedName("description")
private String description;
public BeanPost(String post_name, String auther, String date, String description) {
this.post_name = post_name;
this.auther = auther;
this.date = date;
this.description = description;
}
public String getPost_name() {
return post_name;
}
public void setPost_name(String post_name) {
this.post_name = post_name;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Try to create beanPostArrayList as above pojo class arraylist. And try your code and get appropriate fields from it.
I hope its helps you.
Try this.
Create an array from response :
DoctorBean[] doctorBeanArray = new Gson().fromJson(response, DoctorBean[].class); // Where response is your string response
Then create an ArrayList :
ArrayList<DoctorBean> doctorBeanList = new ArrayList<DoctorBean>(Arrays.asList(doctorBeanArray));
Related
I want to parse json from json object and put it on textview. I tried some method but failed. The error:
expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
API SERVICE: Full ver http://139.255.86.189:83/service/api/checklistpertanyaan/1
{
"success": true,
"data": [
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
},
Harian.java
public class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
MainActivity.java
public class HarianActivity extends AppCompatActivity {
private TextView textViewResult;
/*private static String url = "http://139.255.86.189:83/service/api/checklistpertanyaan/1";*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_harian);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://139.255.86.189:83/service/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
HarianApi harianApi = retrofit.create(HarianApi.class);
Call<List<Harian>> call = harianApi.getHarian();
call.enqueue(new Callback<List<Harian>>() {
#Override
public void onResponse(Call<List<Harian>> call, Response<List<Harian>> response) {
if (!response.isSuccessful()) {
textViewResult.setText("CodeL " + response.code());
return;
}
List<Harian> harians = response.body();
for (Harian harian : harians) {
String content = "";
content += "ID " + harian.getIdRchecklistpompa() + "\n";
content += "NAMA " + harian.getNmChecklist() + "\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Harian>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
I would expect JSON that encapsulated a List of Harians to look like this:
[
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
}
]
Instead, yours begins with:
{
"success": true,
"data": [
...
So it isn't correct for your API to return List<Harian>. Instead, your API should return a different class which looks more like:
public class Container {
#SerializedName("success")
private boolean success;
#SerializedName("data")
List<Harian> data;
public static class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
}
And have your Retrofit API return Container rather than List<Harian>
Not sure if I understand but, to debug the problem what I would do is:
1.- Check as a String that response is a well formed JSON String.
Log.d(TAG, "My JSON String: " + response.code());
1.5.- Check if that string is a JSONObject or a JSONArray
2.- Probably try to create a JSONObject/JSONArray from that String to see if it triggers an exception.
try {
JSONObject jsonObject = new JSONObject(response.code());
} catch (JSONException e) {
e.printStackTrace();
}
3.- Try to parse the JSONObject but checking for exceptions:
try {
String nmChecklist = jsonObject.getString("nmChecklist");
} catch (JSONException e) {
e.printStackTrace();
}
4.- If you want to avoid exceptions since some objects may or may not have a key or value:
String nmChecklist = jsonObject.has("nmChecklist") && !jsonObject.isNull("nmChecklist") ? jsonObject.getString("nmChecklist") : null;
I hope this helps.
I think there is some problem with your class. The response is different from your pojo class. See json to pojo and create your Model as per the generated pojo.
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Using GSON to parse a JSON with dynamic "key" and "value" in android
(2 answers)
Closed 5 years ago.
This is my JsonResponse , and since its not in array i am facing some difficulties , can any one help me out ? in android
{
"errorno": "0",
"responsemsg": "Login Success.",
"busid": "1234",
"returnmobileno": "1234567890"
}
try this
try {
JSONObject lJsonObject = new JSONObject(response);
String errorno = lJsonObject .getString("errorno");
String responsemsg = lJsonObject .getString("responsemsg");
String busid = response.lJsonObject ("busid");
String returnmobileno = lJsonObject .getString("returnmobileno");
} catch (JSONException e) {
e.printStackTrace();
}
Try this,
try {
String errorno = response.getString("errorno");
String responsemsg = response.getString("responsemsg");
String busid = response.getString("busid");
String returnmobileno = response.getString("returnmobileno");
Log.d(TAG, "errorno:" + errorno+" responsemsg:"+responsemsg+" busid:"+busid+" returnmobileno:"+returnmobileno);
} catch (JSONException e) {
e.printStackTrace();
}
use below code to pass your strong
serverData = gson.fromJson(response, ServerData.class);
in build.gradle -> dependencies
// retrofit, gson
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
public class ApiClient {
public static final String SERVER_BASE_URL = "http://example.com/abc/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(SERVER_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface ApiInterface {
#POST("appServices/getData.php")
#FormUrlEncoded
Call<ResponseBody> getAllDataJSONFromServer(#Field("vcode") String vcode);
}
public class ServerData implements Parcelable {
public static final Creator<ServerData> CREATOR = new Creator<ServerData>() {
#Override
public ServerData createFromParcel(Parcel in) {
return new ServerData(in);
}
#Override
public ServerData[] newArray(int size) {
return new ServerData[size];
}
};
private static final int VERSION = 1;
#SerializedName("errorno")
private String errorno;
#SerializedName(responsemsg)
private String responsemsg;
#SerializedName("busid")
private String busid;
#SerializedName("returnmobileno")
private String returnmobileno;
private void readFromParcel(Parcel in) {
if (in.readInt() == VERSION) {
errorno = in.readString();
responsemsg = in.readString();
busid = in.readString();
returnmobileno = in.readString();
}
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(VERSION);
parcel.writeString(errorno);
parcel.writeString(responsemsg);
parcel.writeString(busid);
parcel.writeString(returnmobileno);
}
#Override
public int describeContents() {
return 0;
}
public String getErrorno() {
return errorno;
}
public void setErrorno(String errorno) {
this.errorno = errorno;
}
public String getResponsemsg() {
return responsemsg;
}
public void setResponsemsg(String responsemsg) {
this.responsemsg = responsemsg;
}
public String getBusid() {
return busid;
}
public void setBusid(String busid) {
this.busid = busid;
}
public String getReturnmobileno() {
return returnmobileno;
}
public void setReturnmobileno(String returnmobileno) {
this.returnmobileno = returnmobileno;
}
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
// get and save all data from server
Call<ResponseBody> call = apiService.getAllDataJSONFromServer(local_vcode, local_cvcode, pckgName);
call.enqueue(new Callback<ResponseBody>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responsebody) {
try {
String response = responsebody.body().string();
serverData = gson.fromJson(response, ServerData.class); // this will fetch data to model class ServerData
if (serverData != null) {
// do the rest here...
String vcode = serverData.getVcode();
Log.e("~~~ vode = ", vcode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
progressDialog.dismiss();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
try {
t.printStackTrace();
progressDialog.dismiss();
} catch (Exception ignored) {
}
}
});
I am building a taxi app similar to Uber.. I am using Android Studio and implementing code in Java. Java servlets and jsps for the server side with My sql as the DB.
Any links or code with my mentioned requirement would be of great help.
I want a search bar with suggestions with a drop down menu of pickup and drop off locations like the one in Uber app.?
Thanks in advance.
Create new activity and get input from user or use static input in order to query from google for nearby places
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/textsearch/json?");
sb.append("query=" + "Your input OR user input";
sb.append("&key=You Api key here");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
and create a PlacesTask class
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
And then create Paresetask
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlacesJSONParser placeJsonParser = new PlacesJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
if (customSearch) {
if (list.size() == 0) {
placesList.setVisibility(View.GONE);
error_text.setVisibility(View.VISIBLE);
error_text.setTextColor(getResources().getColor(R.color.error_message_color));
} else {
placesList.setVisibility(View.VISIBLE);
error_text.setVisibility(View.GONE);
}
mPlaceArrayList = new ArrayList<>();
mAdapter = new PlaceListAdapter(NearByPlaces.this, mPlaceArrayList, true);
placesList.setAdapter(mAdapter);
}
for (int i = 0; i < list.size(); i++) {
mNearByPlace = new NearByPlace();
HashMap<String, String> hmPlace = list.get(i);
mNearByPlace.setLatitude(hmPlace.get("lat"));
mNearByPlace.setLongitude(hmPlace.get("lng"));
mNearByPlace.setName(hmPlace.get("place_name"));
mNearByPlace.setVicinity(hmPlace.get("vicinity"));
mPlaceArrayList.add(mNearByPlace);
}
mAdapter.setPlaceArrayList(mPlaceArrayList);
}
}
and NearByPlace is
public class NearByPlace {
private String name;
private String address;
private String latitude;
private String longitude;
private String vicinity;
private String placeIcon;
public NearByPlace(){}
public String getPlaceIcon() {
return placeIcon;
}
public void setPlaceIcon(String placeIcon) {
this.placeIcon = placeIcon;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hope it will help you and you can resolve the minor errors in coz i copied and pasted code from one of my project..
I'm trying to simply make objects out of a Twitter stream I download from a user. I am using the information provided from https://github.com/Rockncoder/TwitterTutorial. Can someone help determine if this code actually works? Some of the classes are kind of sketchy, as in the Twitter.java class is just an ArrayList and it only has what's listed below in it.
Is my process correct? Any help is appreciated.
public class MainActivity extends ListActivity {
private ListActivity activity;
final static String ScreenName = "riddlemetombers";
final static String LOG_TAG = "rmt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
downloadTweets();
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final String CONSUMER_KEY = (String) getResources().getString(R.string.api_key);
final String CONSUMER_SECRET = (String)getResources().getString(R.string.api_secret);
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
#Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
#Override
protected void onPostExecute(String result) {
Twitter twits = jsonToTwitter(result);
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
// send the tweets to the adapter for rendering
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, R.layout.items, twits);
setListAdapter(adapter);
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
if(twits==null){Log.d(LOG_TAG, "Twits null");}
else if(twits!=null) {Log.d(LOG_TAG, "Twits NOT null");}
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
private String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
private String getTwitterStream(String screenName) {
String results = null;
// Step 1: Encode consumer key and secret
try {
// URL encode the consumer key and secret
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
// Concatenate the encoded consumer key, a colon character, and the
// encoded consumer secret
String combined = urlApiKey + ":" + urlApiSecret;
// Base64 encode the string
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
// Step 2: Obtain a bearer token
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
// Applications should verify that the value associated with the
// token_type key of the returned object is bearer
if (auth != null && auth.token_type.equals("bearer")) {
// Step 3: Authenticate API requests with bearer token
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
// construct a normal HTTPS request and include an Authorization
// header with the value of Bearer <>
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
// update the results with the body of the response
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
TWITTER CLASS
import java.util.ArrayList;
// a collection of tweets
public class Twitter extends ArrayList<Tweet> {
private static final long serialVersionUID = 1L;
}
TWEET CLASS
import com.google.gson.annotations.SerializedName;
public class Tweet {
#SerializedName("created_at")
private String DateCreated;
#SerializedName("id")
private String Id;
#SerializedName("text")
private String Text;
#SerializedName("in_reply_to_status_id")
private String InReplyToStatusId;
#SerializedName("in_reply_to_user_id")
private String InReplyToUserId;
#SerializedName("in_reply_to_screen_name")
private String InReplyToScreenName;
#SerializedName("user")
private TwitterUser User;
public String getDateCreated() {
return DateCreated;
}
public String getId() {
return Id;
}
public String getInReplyToScreenName() {
return InReplyToScreenName;
}
public String getInReplyToStatusId() {
return InReplyToStatusId;
}
public String getInReplyToUserId() {
return InReplyToUserId;
}
public String getText() {
return Text;
}
public void setDateCreated(String dateCreated) {
DateCreated = dateCreated;
}
public void setId(String id) {
Id = id;
}
public void setInReplyToScreenName(String inReplyToScreenName) {
InReplyToScreenName = inReplyToScreenName;
}
public void setInReplyToStatusId(String inReplyToStatusId) {
InReplyToStatusId = inReplyToStatusId;
}
public void setInReplyToUserId(String inReplyToUserId) {
InReplyToUserId = inReplyToUserId;
}
public void setText(String text) {
Text = text;
}
public void setUser(TwitterUser user) {
User = user;
}
public TwitterUser getUser() {
return User;
}
#Override
public String toString(){
return getText();
}
}
I've done several Log.d(LOG_TAG, Stuff) to see if I'm getting stuff, and it indicates I'm getting some kind of content back. Maybe the problem is in making objects of the data.
Not sure why you want to use the code from https://github.com/Rockncoder/TwitterTutorial.
Why don't use use http://twitter4j.org. They have give sample example to use it.
Moreover it support Twitter 1.1 as well. Just include twitter-core.jar and you are ready write your code.
Hope it helps.
I'm trying to read a very heavy JSON (over than 6000 objects) and store them on a hash map to insert it into my database later.
But the problem is that I face with OOM and that's cause from my heavy JSON, however GSON library should rid me from this situation, but it is not !!!
Any ideas?
public Map<String,String> readJsonStream(InputStream in) throws IOException
{
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Map<String,String> contentMap = new HashMap<String,String>();
Gson mGson = new Gson();
contentMap = mGson.fromJson(reader, contentMap.getClass());
reader.close();
return contentMap;
}
From my experience, yes you can use google GSON to stream JSON data this is an example how to do it :
APIModel result = new APIModel();
try {
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(APIParam.API_001_PRESENT(
serial_id, api_key));
try {
response = myClient.execute(myConnection);
Reader streamReader = new InputStreamReader(response
.getEntity().getContent());
JsonReader reader = new JsonReader(streamReader);
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("result")) {
if (reader.nextString() == "NG") {
result.setResult(Util.API_001_RESULT_NG);
break;
}
} else if (name.equals("items")) {
result = readItemsArray(reader);
} else {
reader.skipValue(); // avoid some unhandle events
}
}
reader.endObject();
reader.close();
} catch (Exception e) {
e.printStackTrace();
result.setResult(Util.API_001_RESULT_NG);
}
} catch (Exception e) {
e.printStackTrace();
result.setResult(Util.API_001_RESULT_NG);
}
readItemsArray function :
// read items array
private APIModel readItemsArray(JsonReader reader) throws IOException {
APIModel result = new APIModel();
String item_name, file_name, data;
result.setResult(Util.API_001_RESULT_OK);
reader.beginArray();
while (reader.hasNext()) {
item_name = "";
file_name = "";
data = "";
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("name")) {
item_name = reader.nextString();
} else if (name.equals("file")) {
file_name = reader.nextString();
} else if (name.equals("data")) {
data = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
result.populateModel("null", item_name, file_name, data);
}
reader.endArray();
return result;
}
API Model Class :
public class APIModel {
private int result;
private String error_title;
private String error_message;
private ArrayList<String> type;
private ArrayList<String> item_name;
private ArrayList<String> file_name;
private ArrayList<String> data;
public APIModel() {
result = -1;
error_title = "";
error_message = "";
setType(new ArrayList<String>());
setItem_name(new ArrayList<String>());
setFile_name(new ArrayList<String>());
setData(new ArrayList<String>());
}
public void populateModel(String type, String item_name, String file_name, String data) {
this.type.add(type);
this.item_name.add(item_name);
this.file_name.add(file_name);
this.data.add(data);
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public String getError_title() {
return error_title;
}
public void setError_title(String error_title) {
this.error_title = error_title;
}
public String getError_message() {
return error_message;
}
public void setError_message(String error_message) {
this.error_message = error_message;
}
public ArrayList<String> getType() {
return type;
}
public void setType(ArrayList<String> type) {
this.type = type;
}
public ArrayList<String> getItem_name() {
return item_name;
}
public void setItem_name(ArrayList<String> item_name) {
this.item_name = item_name;
}
public ArrayList<String> getFile_name() {
return file_name;
}
public void setFile_name(ArrayList<String> file_name) {
this.file_name = file_name;
}
public ArrayList<String> getData() {
return data;
}
public void setData(ArrayList<String> data) {
this.data = data;
}
}
before I use the streaming API from google GSON I also got OOM error because the JSON data I got is very big data (many images and sounds in Base64 encoding) but with GSON streaming I can overcome that error because it reads the data per token not all at once. And for Jackson JSON library I think it also have streaming API and how to use it almost same with my implementation with google GSON. I hope my answer can help you and if you have another question about my answer feel free to ask in the comment :)