my PostExecute doesn't execute in my Async - android

I'm trying to read data from this API: http://events.makeable.dk/api/getEvents with the AsyncTask method which Is first time I try this. I'm trying to only read all TITLES from the API, but I'm not getting any titles.
Instead I get this exception: W/System.err: org.json.JSONException: (...)
Which shows me the whole API.
I have put Log.d(); around my code and I can se that my code never do or reach something in onPostExecute(String s) and thats is maybe why I never get any TITLES.
The many examples on the web of how to do this is so different from eachother and makes this very frustrating to solve!
private class JsonParser extends AsyncTask<String, Void, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "LOADING DATA FROM API", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
try{
url = new URL(URL);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine())!= null){
result.append(line);
}
return (result.toString());
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
//------ never comes below this area //-----------
try{
JSONArray jsonArray = new JSONArray(s);
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("TAG", "JSON: " + jsonObject.getString("TITLE"));
}
}catch (Exception e){
e.printStackTrace();
}
}
}

I viewed your API's response at this Website. It is a JSON Object because it is started by an open curly brace {. So therefore use JSONObject first.
The response looks like this:
{
"success": true,
"message": "548 events returned successfully",
"last_change": 1459515263,
"events": [
{
"category": "Musik",
"category_id": "75",
"datelist": [
{
"start": 1436536800,
"end": 1436544000
}
],
"description": "",
"description_english": "",
"description_german": "",
"eventgroup": "",
"eventid": "55815f7fe714a",
"family_friendly": "0",
"last_updated": 1436166668,
"location_address": "Klostertorv 1",
"location_city": "Århus C",
"location_id": "1593",
"location_latitude": 56.158092,
"location_longitude": 10.206756,
"location_name": "Klostertorv",
"location_postcode": "8000",
"organizer_email": "",
"organizer_name": "Café Smagløs ",
"organizer_phone": "",
"picture_name": "http://www.jazzfest.dk/img/photos_big/tcha-badjo---strings-og-buttons.jpg",
"price": "-1",
"subcategory": "Musik",
"subcategory_id": "84",
"subtitle": "",
"subtitle_english": "",
"subtitle_german": "",
"tags": "Swing/Mainstream",
"tickets_url": "",
"title": "Tcha Badjo + Strings & Buttons KONCERT AFLYST",
"title_english": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"title_german": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
"url": "http://www.jazzfest.dk/?a=reviews&lang=&kryds_id=2122&y=2015",
"user_id": "23",
"video_url": ""
}]
}
So therefore it is:
try {
JSONObject object = new JSONObject(s);
JSONArray events = object.getJSONArray("events");
int evSize = events.length();
for (int x = 0; x < evSize; x++) {
JSONObject object1 = events.getJSONObject(x);
String title = object1.getString("title");
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

error type JSONArray cannot be converted to JSONObject

I'm creating an app to get posts from a web server, and i'm getting a jsonarray to object error I'm new to android development and tutorials i see the JsonArray is named before, so it'd be array of dogs, and then inside that would have breed and name and so on, mines not named.
the code i have is
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try{
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(JSONURL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while(data !=-1){
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(urlConnection !=null){
urlConnection.disconnect();;
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("");
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
postList,
R.layout.item,
new String[]{"name", "post"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
the json code i'm trying to parse is
[
{
"0": "2",
"id": "2",
"1": "anon",
"name": "anon",
"2": "goodbye people of skivecore",
"post": "goodbye people of skivecore",
"3": "38.751053",
"lat": "38.751053",
"4": "-90.432915",
"lng": "-90.432915",
"5": "",
"ip": "",
"6": "6.204982836749738",
"distance": "6.204982836749738"
},
{
"0": "1",
"id": "1",
"1": "anon",
"name": "anon",
"2": "hello people of skivecore",
"post": "hello people of skivecore",
"3": "38.744453",
"lat": "38.744453",
"4": "-90.607986",
"lng": "-90.607986",
"5": "",
"ip": "",
"6": "9.280600590285143",
"distance": "9.280600590285143"
}
]
and stacktrace message
2021-04-28 23:45:02.156 20352-20352/com.skivecore.secrets W/System.err: org.json.JSONException: Value [{"0":"2","id":"2","1":"anon","name":"anon","2":"goodbye people of skivecore","post":"goodbye people of skivecore","3":"38.751053","lat":"38.751053","4":"-90.432915","lng":"-90.432915","5":"","ip":"","6":"6.204982836749738","distance":"6.204982836749738"},{"0":"1","id":"1","1":"anon","name":"anon","2":"hello people of skivecore","post":"hello people of skivecore","3":"38.744453","lat":"38.744453","4":"-90.607986","lng":"-90.607986","5":"","ip":"","6":"9.280600590285143","distance":"9.280600590285143"}] of type org.json.JSONArray cannot be converted to JSONObject
You should use like below
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
I think here is the issue JSONObject jsonObject = new JSONObject(s); as I can see your response is a JSONArray because it has [ and ] at the beginning and the end.
So, I think this would be more appropriate.
try{
JSONArray jsonArray = jsonObject.getJSONArray(s);
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
}
please usding gson library To use jasonArray And JsonObject Easley
1). https://github.com/google/gson
2). libraby import then use
https://www.jsonschema2pojo.org/
for your jsonArray to Model class
Then Use jsonArray
Use this instead....
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//put to hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();

Pull JSONObject from JSONArray?

I'm trying to pull the "price" object from the "current" array, I have been at it for hours now with no luck, any help is appreciated! :)
try {
URL url = new URL("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=2");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
JSONArray nu1 = jobj.getJSONArray("current");
JSONObject jobj = nu1.getJSONObject(0);
String price = jobj.getString("price");
Toast.makeText(getApplicationContext(), price, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
}
}
}
I tried to get response from your URL. here is the response :
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_sprite.gif?id=2",
"icon_large": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_big.gif?id=2",
"id": 2,
"type": "Ammo",
"typeIcon": "http://www.runescape.com/img/categories/Ammo",
"name": "Cannonball",
"description": "Ammo for the Dwarf Cannon.",
"current": {
"trend": "neutral",
"price": 339
},
"today": {
"trend": "positive",
"price": "+1"
},
"members": "true",
"day30": {
"trend": "positive",
"change": "+1.0%"
},
"day90": {
"trend": "negative",
"change": "-11.0%"
},
"day180": {
"trend": "negative",
"change": "-21.0%"
}
}
}
there is no array in the response.
Edit:
assume that you store your response in a String named response, you can get price, using the following code:
JSONObject json = new JSONObject(response);
JSONObject item = json.getJSONObject("item");
JSONObject current = item.getJSONObject("current");
int price = current.getInt("price");
Edit2: use
String response = stringBuilder.toString();
and then make a JSONObject from 'response' .

How to parse Json Array and Json Object having two keys and values in android?

I want to populate my spinner from wallet array from SQL database and then store the wallet id which is being selected by the user in the particular user details, not the wallet name. I have written this particular code and o have added the screenshot as well for the error.
Android Part
public class User extends AppCompatActivity {
ArrayAdapter<String> adapter;
ArrayList<Populate> listItems;
LinkedHashMap<String,String> walletId;
Button logout,editdetails;
SharedPreferences sp;
SharedPreferences.Editor editor;
public static final String DEFAULT = "N/A";
TextView usermail;
String email;
int id;
public static final int DEFAULTI = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
listItems = new ArrayList<>();
usermail = (TextView) findViewById(R.id.usermail);
editdetails = (Button) findViewById(R.id.editdetails);
logout = (Button) findViewById(R.id.logout);
sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
email = sp.getString("email", DEFAULT);
usermail.setText("Welcome " + email);
id = sp.getInt("id",DEFAULTI);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/** pref = getSharedPreferences("Login", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("loginfirst",false);
editor.commit();**/
Intent i = new Intent(User.this, Login.class);
startActivity(i);
finish();
}
});
}
public void onEdit(View v){
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute(String.valueOf(id));
}
class BackgroundTask extends AsyncTask<String, Void, String> {
ArrayList<Populate> list;
String add_info_url;
#Override
protected void onPreExecute() {
list=new ArrayList<>();
add_info_url = "http://192.168.2.6/Deal%20Engine/editdetails.php";
}
#Override
protected void onPostExecute(String result) {
listItems.addAll(list);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
//SharedPreferences sp = getSharedPreferences("Login",Context.MODE_PRIVATE);
Intent i = new Intent(User.this, EditDetails.class);
startActivity(i);
}
#Override
protected String doInBackground(String... args) {
BufferedReader reader = null;
try {
URL url = new URL(add_info_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String dataString = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(String.valueOf(id), "UTF-8");
Log.d("id", String.valueOf(id));
bufferedWriter.write(dataString);
Log.d("Result", dataString);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
Log.d("String", finalJson);
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("user");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
int status_code = finalObject.getInt("status_code");
String status_desc = finalObject.getString("status_desc");
String user_id = finalObject.getString("user_id");
int id = finalObject.getInt("id");
String name=finalObject.getString("name");
String pass= finalObject.getString("pass");
String location = finalObject.getString("location");
String cards=finalObject.getString("cards");
String category= finalObject.getString("category");
String wallet = finalObject.getString("wallet");
String operator=finalObject.getString("operator");
String loyaltyProgram= finalObject.getString("loyaltyProgram");
String membership= finalObject.getString("membership");
JSONObject walletArrayObject = new JSONObject(finalObject.getString("wallet_array"));
JSONArray walletArray = walletArrayObject.getJSONArray("wallets");
Log.d("Arraysize",String.valueOf(walletArray));
for(int j =0;j<walletArray.length();j++)
{
JSONObject walletObject = walletArray.getJSONObject(j);
list.add(new Populate(String.valueOf(walletObject.getInt("id")),walletObject.getString("wallet_name")));
}
sp = getSharedPreferences("Login",Context.MODE_PRIVATE);
editor=sp.edit();
editor.putString("name",name);
editor.putString("pass",pass);
editor.putInt("id",id);
editor.putString("location",location);
editor.putString("cards",cards);
editor.putString("category",category);
editor.putString("wallet",wallet);
editor.putString("operator",operator);
editor.putString("wallets",String.valueOf(list));
editor.putString("loyaltyProgram",loyaltyProgram);
editor.putString("membership",membership);
editor.commit();
finalBufferedData.append(status_code + " - " + status_desc + " -" + user_id + " -"+id + " -"+name+ " -"+list +"\n");
}
inputStream.close();
httpURLConnection.disconnect();
Log.d("Result", dataString);
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
error I am getting
06-29 12:53:08.015 28974-28988/com.example.tanmayjain.twowaycommunication D/String: {"user":[{"status_code":"1","status_desc":"Success","user_id":"482","id":"26","name":"tanmay ","pass":"a006b22f887f7d922bafa4c8186ccafd","location":"Ahmedabad","cards":"ICICI Bank","category":"Platinum","wallet":"","operator":"Vodafone","loyaltyProgram":"Any","membership":"All Time","wallet_array":"{\"wallets\":[{\"1\":[\"Paytm\"],\"2\":[\"Freecharge\"],\"3\":[\"Mobikwik\"],\"4\":[\"PayUmoney\"],\"5\":[\"CitrusCash\"],\"6\":[\"Airtel Money\"],\"7\":[\"Oxigen Wallet\"],\"8\":[\"OLAMoney\"],\"9\":[\"HDFC PayZapp\"],\"10\":[\"Chillr by HDFC\"],\"11\":[\"Pockets by ICICI bank\"],\"12\":[\"JioMoney\"],\"13\":[\"SBI Buddy\"],\"14\":[\"mRupee\"],\"15\":[\"Itzcash\"]}]}"}]}
06-29 12:53:08.015 28974-28988/com.example.tanmayjain.twowaycommunication D/Arraysize: [{"1":["Paytm"],"2":["Freecharge"],"3":["Mobikwik"],"4":["PayUmoney"],"5":["CitrusCash"],"6":["Airtel Money"],"7":["Oxigen Wallet"],"8":["OLAMoney"],"9":["HDFC PayZapp"],"10":["Chillr by HDFC"],"11":["Pockets by ICICI bank"],"12":["JioMoney"],"13":["SBI Buddy"],"14":["mRupee"],"15":["Itzcash"]}]
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: org.json.JSONException: No value for id
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at org.json.JSONObject.get(JSONObject.java:389)
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at org.json.JSONObject.getInt(JSONObject.java:478)
06-29 12:53:08.016 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at com.example.tanmayjain.twowaycommunication.User$BackgroundTask.doInBackground(User.java:167)
06-29 12:53:08.017 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at com.example.tanmayjain.twowaycommunication.User$BackgroundTask.doInBackground(User.java:85)
06-29 12:53:08.017 28974-28988/com.example.tanmayjain.twowaycommunication W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
I want to fetch id and wallet name from the array displayed in array size but i am getting this error.
Your json is wrong, because your walletObject contains this:
{
"wallets": [{
"1": ["Paytm"],
"2": ["Freecharge"],
"3": ["Mobikwik"],
"4": ["PayUmoney"],
"5": ["CitrusCash"],
"6": ["Airtel Money"],
"7": ["Oxigen Wallet"],
"8": ["OLAMoney"],
"9": ["HDFC PayZapp"],
"10": ["Chillr by HDFC"],
"11": ["Pockets by ICICI bank"],
"12": ["JioMoney"],
"13": ["SBI Buddy"],
"14": ["mRupee"],
"15": ["Itzcash"]
}]
}
You got the error because you would like to get the value of id property, but your json doesn't contains id field.
Your json has more problems:
1. send an object instead of array (wallet_array)
2. change your wallet object structure
I think you should use this json structure:
{
"user": [{
"status_code": "1",
"status_desc": "Success",
"user_id": "482",
"id": "26",
"name": "tanmay ",
"pass": "a006b22f887f7d922bafa4c8186ccafd",
"location": "Ahmedabad",
"cards": "ICICI Bank",
"category": "Platinum",
"wallet": "",
"operator": "Vodafone",
"loyaltyProgram": "Any",
"membership": "All Time",
"wallet_array": [{
"id": 1,
"name": "Paytm"
},
{
"id": 2,
"name": "Freecharge"
},
{
"id": 3,
"name": "Mobikwik"
},
{
"id": 4,
"name": "PayUmoney"
},
{
"id": 5,
"name": "CitrusCash"
},
{
"id": 6,
"name": "Airtel Money"
},
{
"id": 7,
"name": "Oxigen Wallet"
},
{
"id": 8,
"name": "OLAMoney"
},
{
"id": 9,
"name": "HDFC PayZapp"
}
]
}]
}

How do I match data by ID's in Android using JSON?

I have two fragments, one shows a program list and one shows a course list. How do I get the selected program from the mainactivity to only show the corresponding course description? They match by ID. Currently, when I click on a program, the whole course list shows up instead of the corresponding course.
MainActivity Fragment (shows all data in JSON file):
ProgramAdapter programAdapter;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ProgramDetail item = (ProgramDetail) getListAdapter().getItem(position);
Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
intent.putExtra(ProgramDetailActivity.EXTRA_ID, item.getId());
startActivity(intent);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
programAdapter = new ProgramAdapter(getActivity());
setListAdapter(programAdapter);
setListShown(false);
new HttpAsyncTask().execute("https://gist.githubusercontent.com/kdotzenrod517/39bc7372759c762e33188fb1a6cbce5d/raw/a2baa28d19fd597be999c8fddb6b48c888cd33f4/gistfile1.txt");
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.e("HttpAsyncTask", "doInBackground");
String result = "";
HttpURLConnection urlConnection = null;
try{
URL url = new URL(params[0]);
Log.e("HttpAsyncTask", params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.e("HttpAsyncTask", "getInputStream");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String s = "";
while ((s = reader.readLine()) != null){
result += s;
Log.e("HttpAsyncTask", result);
}
} catch (Exception e){
Log.e("HttpAsyncTask", "EXCEPTION: " + e.getMessage());
} finally {
if (urlConnection != null){
urlConnection.disconnect();
}
}
return result;
}
#Override
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> items = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(new ProgramDetail(jsonObject.getString("name"),null,jsonObject.getLong("id")));
}
programAdapter.addAll(items);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
}
}
}
CourseList Fragment (should only show matching JSON data by ID)
`
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> item = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
item.add(new ProgramDetail(jsonObject.getString("name"), null, jsonObject.getLong("id")));
}
programAdapter.addAll(item);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
Program List
[
{
"id": "0",
"name": "Intro to Android"
},
{
"id": "1",
"name": "Advanced Android"
},
{
"id": "2",
"name": "Intro to Java"
},
{
"id": "3",
"name": "Advanced Java"
},
{
"id": "4",
"name": "Intro to Data Science"
}
]
Course List JSON
{
"id": "0",
"name": "Welcome to Android!"
},
{
"id": "1",
"name": "Enterprise level Android Dev"
},
{
"id": "2",
"name": "Welcome to Java!"
},
{
"id": "3",
"name": "Enterprise Level Java"
},
{
"id": "4",
"name": "Welcome to Data Science!"
}

Reading JSON data using GSON

I spent the past 4 hours looking at various answers and other resources but I simply can't wrap my head around JSON parsing. I need some help.
Here is the JSON string:
{
"success": true,
"categories": [
{
"category_id": "20",
"parent_id": "0",
"name": "Desktops",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "25",
"parent_id": "0",
"name": "Components",
"image": "***",
"href": "***",
"categories": null
},
{
"category_id": "34",
"parent_id": "0",
"name": "MP3 Players",
"image": "***",
"href": "***",
"categories": null
}
]
}
Here is my Data class:
public class Data
{
String success;
List<Category> categories;
// Various get/set functions and a toString override
public class Category
{
String category_id;
String name;
String image;
// Various get/set functions
}
}
Here is where I'm trying to read this:
private class GetJson extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
String results = "Fail";
URL url = null;
try
{
url = new URL("***");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
URLConnection ucon = null;
try
{
ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(is));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
{
result += line;
}
Data data = new Gson().fromJson(result, Data.class);
result = data.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return results;
}
protected void onPostExecute(String result)
{
Toast.makeText(con, result, Toast.LENGTH_SHORT);
}
}
I'm not getting anything on the stacktrace at all. I checked ADB several times. Everything seems to be working but I get no Toast or error message.
What am I doing wrong?
you forgot to show your Toast
try this
Toast.makeText(con, result, Toast.LENGTH_SHORT).show();
lol
and further
Data data = new Gson().fromJson(result, Data.class);
result = data.toString();
return result; // need return this
otherwise will always get "Fail"
//First generate getter setter of data class variables.
TypeToken<Data> tokenPoint1 = new TypeToken<Data>() {};
//SYSO result string here for Confirmation
Gson gson = new Gson();
Data dataobj= gson.fromJson(result, tokenPoint1.getType());
// syso dataobj.getname();
//Hope this will work for you

Categories

Resources