Get value from gson with index - android

I am trying to parse huge json using gson library and my main idea is to get one value from each object and save it as String. This the json file i am using. And this is the code i am using to parse the json:
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
public TextView textss;
public int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
textss = (TextView)findViewById(R.id.texts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.posts, menu);
return true;
}
private void handlePostsList(List<Post> posts) {
this.posts = posts;
runOnUiThread(new Runnable() {
#Override
public void run() {
for(Post post : PostsActivity.this.posts) {
Toast.makeText(PostsActivity.this, post.title + " " + i, Toast.LENGTH_SHORT).show();
}
}
});
}
private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat. bls bls bls " , Toast.LENGTH_SHORT).show();
}
});
}
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://kylewbanks.com/rest/posts";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
for ( i = 0; i < 4; i++) {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
content.close();
handlePostsList(posts);
}
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
}
I am still learning and what i understand is that all values are saved in one big list and later these values are displayed as in Toast. What i am trying to do is save a value in String like i would to it with json like this:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
How can i achieve this by using Gson library?

Here's what I've tried as you want.
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
//List<Post> posts = Arrays.asList(gson.fromJson(reader, Post[].class));
JsonArray posts = new JsonParser().parse(reader).getAsJsonArray();
// Get first element at index 0
Post post1 = gson.fromJson(posts.get(0).getAsJsonObject(), Post.class);
Log.d(TAG, "post1 .. " + post1.getTitle());
content.close();
//handlePostsList(posts);
First of all, I create a Gson JsonArray. And assign it by creating a new JsonParser which parses the reader as a JsonArray.
And then you can extract the first element of the posts by getting the element at index 0, and deserializes with respective Object.
I've used set/get for Post object so I get the title as post1.getTitle().
The log says
post1 .. Disabling Google Analytics in Development Using Only
JavaScript

Related

Get JSON response in listview and how to show it in listview?

I am a beginner in Android. I want to get a JSON response in a list and show it in a ListView . How to do this?
Here is my code for JSON post.
public class NewTest extends AppCompatActivity { TextView
txtJson;
Button btnOkay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_test);
txtJson= (TextView) findViewById(R.id.txtJson);
assert (findViewById(R.id.btnOkay)) != null;
(findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { new TaskPostWebService("written url here").execute(((TextView)
findViewById(R.id.txtJson)).getText().toString());
}
}); }
private class TaskPostWebService extends AsyncTask<String,Void,String> {
private String url;
private ProgressDialog progressDialog;
private JSONParser jsonParser;
public TaskPostWebService(String url ){
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(NewTest.this,"","");
}
#Override
protected String doInBackground(String... params) {
String fact = "";
try {
final MediaType JSON = MediaType.parse("application/json");
android.util.Log.e("charset", "charset - " + JSON.charset());
OkHttpClient client = new OkHttpClient();
//Create a JSONObject with the data to be sent to the server
final JSONObject dataToSend = new JSONObject()
.put("nonce", "G9Ivek")
.put("iUserId", "477");
android.util.Log.e("data - ", "data - " + dataToSend.toString());
//Create request object
Request request = new Request.Builder()
.url("written url here")
.post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
.addHeader("Content-Type", "application/json")
.build();
android.util.Log.e("request - ", "request - " + request.toString());
android.util.Log.e("headers - ", "headers - " + request.headers().toString());
android.util.Log.e("body - ", "body - " + request.body().toString());
//Make the request
Response response = client.newCall(request).execute();
android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
String responseData = response.body().string();
//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);
//See the response from the server
Log.i("response data", dataReceived.toString());
}
catch (Exception e){
e.printStackTrace();
}
return fact;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView text = (TextView) findViewById(R.id.txtJson);
text.setText(s);
progressDialog.dismiss();
}
}
So, how can I get a response in a list and show it in a ListView?
Welcome to stackOverflow,
as you are beginner so before going to complete solutions, you can think and follow following steps.
1.Network request:
For network request, we have lib volley(by Google) and retrofit(by Square). You can use this for network request and response.
2.JSON Parsing: You can used eigther GSON lib or using JSONObject/ jsonArray to parse json data. I'll recommend you to write your own parsing code for better understanding of JSON parsing.
3.ListView data binding: At this step, you should have parsed data in list(other data structure can be used to store data also). Create Adapter and bind listview with adapters.
I have not provided solutions for this, you should implement yourself and let me know for any doubts. Hope this should work.
ArrayList<JSONObject> arrayListJson;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
ListView listView = (ListView) fragmentView.findViewById(R.id.listView);
adapter = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
now in a separate thread:
JSONObject jResponse = new JSONObject(responseStr);
JSONArray jArray= jResponse.getJSONArray("OUTER_KEY");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
arrayList.add(jsonObject.optString("INNER_KEY"));
arrayListJson.add(jsonObject);
}
adapter.notifyDataSetChanged();

I have used Gson libary,but can see my output

This is my Main Class.Can any one tell me why it s returning null in System.print().I have used Gson external libs.What i am doing wrong here.How can i display all contains
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
private void handlePostsList(List<Post> posts) {
this.posts = posts;
runOnUiThread(new Runnable() {
#Override
public void run() {
for(Post post : PostsActivity.this.posts) {
Toast.makeText(PostsActivity.this, post.TITLE, Toast.LENGTH_SHORT).show();
}
}
});
}
private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
Post po = gson.fromJson(reader, Post.class);
List<Post> posts = Arrays.asList(po);
System.out.println("ID:"+po);
content.close();
handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
}
//Post.java
public class Post {
#SerializedName("id")
public long ID;
public String TITLE;
public String AUTHOR;
public String URL;
#SerializedName("date")
public Date dateCreated;
public String body;
public List<Tag> tags;
public Post() {
}
public String toString() {
return "Student [id=" + ID + ", title="
+ TITLE + ", thumb_url=" + URL
+ ", dt=" + AUTHOR + "]";
}
}
There are a few things you need to consider. First of all, your fields need have proper #SerializedName("") annotation. It indicates that the property name (like thumb_url, dt) does not match the field name in your JSON. If both names do match, there is no need for the annotation.
Secondly, you need to "parse" the response that you get from the server to JsonObject and then read the JsonElement.
Here's the code you need:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yy-d-M hh:mm");
//2014-06-14 02:39:24
//yy-d-M hh:mm
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
JsonParser jsonParser = new JsonParser();
JsonObject details = jsonParser.parse(reader).getAsJsonObject();
JsonArray array = details.getAsJsonArray("veg_food");
for ( JsonElement element : array ){
Post post = gson.fromJson(element, Post.class);
posts.add(post);
}
System.out.println("ID:"+ posts);
Also, make sure you change your Post.java class to this:
#SerializedName("id")
public long ID;
#SerializedName("title")
public String TITLE;
#SerializedName("thumb_url")
public String URL;
#SerializedName("dt")
public Date dateCreated;
Hope it helps.
[EDIT]
Output:

Parsing JSON from sdcard - GSON

Hi I created parsing JSON from http server based on this tutorial. But I want parse this JSON file from sdcard. I'm able to print json file location using Environment.getExternalStorageDirectory().getAbsolutePath(), But I don't know how to change the AsyncTask read the file. can someone help me to do this stuff? (I'm new to android development)
Code looks like this:
public class ClientActivity extends Activity {
TextView capitalTextView;
ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
capitalTextView = (TextView) findViewById(R.id.capital_textview);
this.retrieveCapitals();
}
void retrieveCapitals() {
progressDialog = ProgressDialog.show(this,
"Please wait...", "Retrieving data...", true, true);
CapitalsRetrieverAsyncTask task = new CapitalsRetrieverAsyncTask();
task.execute();
progressDialog.setOnCancelListener(new CancelListener(task));
}
private class CapitalsRetrieverAsyncTask extends AsyncTask<Void, Void, Void> {
Response response;
#Override
protected Void doInBackground(Void... params) {
String url = "http://sample.com/sample_data.json";
HttpGet getRequest = new HttpGet(url);
File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/example.json");
System.out.println(file);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse getResponse = httpClient.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
InputStream httpResponseStream = getResponseEntity.getContent();
Reader inputStreamReader = new InputStreamReader(httpResponseStream);
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
System.out.println(this.response);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
StringBuilder builder = new StringBuilder();
for (Shop shop : this.response.shops) {
builder.append(String.format("<br>ID: <b>%s</b><br>Shop: <b>%s</b><br>Description: <b>%s</b><br><br>", shop.getId(), shop.getName(), shop.getDescription()));
}
capitalTextView.setText(Html.fromHtml(builder.toString()));
progressDialog.cancel();
}
}
private class CancelListener implements OnCancelListener {
AsyncTask<?, ?, ?> cancellableTask;
public CancelListener(AsyncTask<?, ?, ?> task) {
cancellableTask = task;
}
#Override
public void onCancel(DialogInterface dialog) {
cancellableTask.cancel(true);
}
}
}
Don't save the JSON file as it is. JSON is meant for transferring values from one place to another.
Instead, depending on the data, you can use Shared Preference or SQLite database to store it.
Check this out:
http://developer.android.com/guide/topics/data/data-storage.html
Then you can easily retrieve it and make modifications to the data.

Android GSON processing remote JSON runtime exception

I am attempting to write an Android app which casts JSON input. This is my sample input.
I have the following class to serve as the data container:
public class DATA {
public Long id;
public String title;
public String author;
public String url;
public String date;
public String body;
public DATA() {
// TODO Auto-generated constructor stub
}
#Override
public String toString(){
return "DATA-Oblect: ID=> " + id + "/nTITLE=> " + title;
}
}
Using the following code:
protected void doInBackground(String... url) {
try{
//create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://kylewbanks.com/rest/posts");//url[0]);
//perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
content = entity.getContent();
try{
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<DATA> Data = new ArrayList<DATA>();
Data = Arrays.asList(gson.fromJson(reader, DATA[].class));
content.close();
}catch(Exception ex){
Log.e(TAG, "JSON parse failed due to: " + ex);
}
}else{
Log.e(TAG, "Server response code: " + statusLine.getStatusCode());
}
}catch(Exception ex){
Log.e(TAG, "HTTP-Post failed due to: " + ex);
}
}
I get the following exception error:
JSON parse failed due to: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
What am I doing wrong?
Update
The following the the my main activity code:
public class MainActivity extends Activity {
private List<DATA> Data;
public static final String jsonSource = "http://kylewbanks.com/rest/posts";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// DataRetriever("http://kylewbanks.com/rest/posts");
new DataRetriever(this.getApplicationContext()).execute(jsonSource);
}
/**
* Callback function for handling retrieved data from the
* DATARetrieve class
* #param Data
*/
public void DataListDrop(List<DATA> Data){
this.Data = Data;
Toast.makeText(MainActivity.this, "Testing ... testing!", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(DATA data : MainActivity.this.Data){
Toast.makeText(MainActivity.this, data.title, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Callback function for responding no-data return from the
* DATARetrieve class
*/
private void NoData(){
runOnUiThread(new Runnable() {
#Override
public void run(){
Toast.makeText(MainActivity.this, "No data to process! Checkout LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
}

Code in FOR loop not executed

I have a ProgressDialog that retrieves in background data from database by executing php script.
I'm using gson Google library. php script is working well when executed from browser:
{"surveys":[{"id_survey":"1","question_survey":"Are you happy with the actual government?","answer_yes":"50","answer_no":"20"}],"success":1}
However, ProgressDialog background treatment is not working well:
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.4/tn_surveys/get_all_surveys.php";
HttpGet getRequest = new HttpGet(url);
Log.d("GETREQUEST",getRequest.toString());
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d("URL1",url);
HttpResponse getResponse = httpClient.execute(getRequest);
Log.d("GETRESPONSE",getResponse.toString());
final int statusCode = getResponse.getStatusLine().getStatusCode();
Log.d("STATUSCODE",Integer.toString(statusCode));
Log.d("HTTPSTATUSOK",Integer.toString(HttpStatus.SC_OK));
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
Log.d("RESPONSEENTITY",getResponseEntity.toString());
InputStream httpResponseStream = getResponseEntity.getContent();
Log.d("HTTPRESPONSESTREAM",httpResponseStream.toString());
Reader inputStreamReader = new InputStreamReader(httpResponseStream);
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("HELLO","HELLO");
StringBuilder builder = new StringBuilder();
Log.d("STRINGBUILDER","STRINGBUILDER");
for (Survey survey : this.response.data) {
String x= survey.getQuestion_survey();
Log.d("QUESTION",x);
builder.append(String.format("<br>ID Survey: <b>%s</b><br> <br>Question: <b>%s</b><br> <br>Answer YES: <b>%s</b><br> <br>Answer NO: <b>%s</b><br><br><br>", survey.getId_survey(), survey.getQuestion_survey(),survey.getAnswer_yes(),survey.getAnswer_no()));
}
Log.d("OUT FOR","OUT");
capitalTextView.setText(Html.fromHtml(builder.toString()));
progressDialog.cancel();
}
HELLO Log is displayed.
STRINGBUILDER Log is displayed.
QUESTION Log is NOT displayed.
OUT FOR Log is displayed.
Survey Class:
public class Survey {
int id_survey;
String question_survey;
int answer_yes;
int answer_no;
public Survey() {
this.id_survey = 0;
this.question_survey = "";
this.answer_yes=0;
this.answer_no=0;
}
public int getId_survey() {
return id_survey;
}
public String getQuestion_survey() {
return question_survey;
}
public int getAnswer_yes() {
return answer_yes;
}
public int getAnswer_no() {
return answer_no;
}
}
Response Class:
public class Response {
ArrayList<Survey> data;
public Response() {
data = new ArrayList<Survey>();
}
}
Any help please concerning WHY the FOR loop is not executed.
Thank you for helping.
Any help please concerning WHY the FOR loop is not executed.
Simply put: data is empty. (So there is nothing for the loop to iterate over...)
Try something like this, from GSON's documentation:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
I haven't used GSON myself, but there are other examples of how to read lists:
Android gson deserialization into list
GSON : custom object deserialization
Your onPostExecute takes in a parameter called result. Your for loop iterates over the elements in an instance variable called response. Are they supposed to be the same?

Categories

Resources