Parsing JSON in Android Master/Detail Flow - android

As the title says. I'd like to just use a JSON. Here is my code for what I'm guessing is my main activity. This grabs all the contents and places them in their respectful variables I'm hoping. Placed at the beginning:
public class WordDetailActivity extends FragmentActivity {
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null; {
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"wordlist.txt")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String word = jsonObj.getString("word");
String dictionary = jsonObj.getString("dictionary");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
Now I have another file called WordContent.java that defines these variable again (a non edited version):
public static Map<String, WordItem> ITEM_MAP = new HashMap<String, WordItem>();
static {
// Add 3 sample items.
addItem(new WordItem("1", "This Word", "Blah blah blah"));
}
private static void addItem(WordItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
/**
* A dummy item representing a piece of content.
*/
public static class WordItem {
public String id;
public String word;
public String dictionary;
public WordItem(String id, String word, String dictionary) {
this.id = id;
this.word = word;
this.dictionary = dictionary;
}
#Override
public String toString() {
return word;
}
}
}
I haven't edited them yet because I have no idea where to go from here. Or rather how to put the contents of my JSON to the WordItem so they show up when I run the program. Another way to look at all of my code that is similar to this is to just create a Master/Detail Flow project in the Eclipse ADT bundle. I hope I'm saying all of this right. Let me know if there are more details I should shed. Very new to Android Dev but any pointer in the right direction is greatly appreciated.

Personally, I would do the JSON parsing in a separate file and probably use an AsyncTask. This is so you can decouple your files/classes as you really do not need an Activity for the parsing.
I tried to reuse as much of your code you posted above. With that being said, something like this should work or put you in the right direction:
public class ParseJsonTask extends AsyncTask<Void, Void, String> {
private Context mCtx;
public ParseJsonTask(Context ctx) {
this.mCtx = ctx;
}
#Override
protected String doInBackground(Void... params) {
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(mCtx.getAssets().open("wordlist.txt")));
String temp;
while ( (temp = br.readLine()) != null )
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.tostring();
}
#Override
protected void onPostExecute(Void jsonString) {
WordContent word = new WordContent(); // We use this oject to add the JSON data to WordItem
// Try to parse JSON
try {
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(jsonString);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("employee");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
int id = jsonObj.getInt("id");
String word = jsonObj.getString("word");
String dictionary = jsonObj.getString("dictionary");
// We can use the three variables above...
word.addItem(new WordItem(id, word, dictionary));
// or we can simply do...
// word.addItem(new WordItem(jsonObj.getInt("id"), jsonObj.getString("word"), jsonObj.getString("dictionary")));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now whenever you want to parse the JSON file and use the class above you simply do the following:
ParseJsonTask task = new ParseJsonTask(getBaseContext());
task.execute();
Let me know if you have any questions...

Related

why can't I parsing value 'fields' in my code?

When I run my app, In logcat, "Problem parsing the earthquake Json results
org.json.JSONException: No value for fields"
Could you check my JSON code..? I'm beginner of JSON Parsing, So I searched a lot inf But I'm not sure about my code.
public class Utils {
private static List<News> extractFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject response = baseJsonResponse.getJSONObject("response");
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentNews = jsonArray.getJSONObject(i);
JSONObject fields = currentNews.getJSONObject("fields");
Drawable thumbnail = LoadImageFromUrl (fields.getString("thumbnail"));
String section = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String url = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
news.add(new News( section, title, url, date,thumbnail));
}
return news;
} catch (JSONException e) {
Log.e("Utils", "Problem parsing the news Json results", e);
}
return null;
}
private static Drawable LoadImageFromUrl(String imageurl) {
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = new URL(imageurl).openStream();
drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return drawable;
}
}
Try this to validate
Problem occur may be you dont have a field jsonobject in your json list. It may be not present in the some of other jsonobjects. So check if jsonobject has actual field jsonobject before parsing.
Use this condition whenever your json value might give null sometimes.
if(currentNews.has("fields"))
{
JSONObject fields = currentNews.getJSONObject("fields");
}
else
{
Log.d("JSON_TAG","NO FIELD JSON OBJECT");
}

JSON resolve from URL and post textview

how to resolve this json for Android Studio
and need each item is individually displayed in the textview
Thank you all....
url content only
{"s":true,"code":0,"errors":[],"c":"2.54","y":"5.8","i":"2.9","x":"0"}
My Someone Activity
public class aFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, null);
super.onCreate(savedInstanceState);
new TransTask()
.execute("MYURL");
return view;
}
class TransTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(params[0]);
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String line = in.readLine();
while(line!=null){
Log.d("HTTP", line);
sb.append(line);
line = in.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("JSON", s);
parseJSON(s);
}
private void parseJSON(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
String name = jsonObject.getString("s");
String title = jsonObject.getString("code");
String tag = jsonObject.getString("errors");
String info = jsonObject.getString("c");
String info = jsonObject.getString("y");
String inf = jsonObject.getString("i");
String in = jsonObject.getString("x");
}
catch(JSONException e) {
e.printStackTrace();
}
}
why super.onPostExecute(s); cannot resolve method 'onPostExecute(java.lang.string)'
You could set the values for various widgets in the 'onPostExecute' method for your AsyncTask.
Initialize a JSONObject with the string returned. Then use the various methods like getBoolean, getString, getDouble, etc. for the values. You can even get nested json objects or arrays using getJSONObject and getJSONArray methods. Using JSONObject will require you to handle a JSONException in your code.
JSONObject jsonObject = new JSONObject(stringObject);
boolean s = jsonObject.getBoolean("s");
int code = jsonObject.getInt("code");
JSONArray errors = jsonObject.getJSONArray("errors");
//Similar to above
Alternately, you can also use a library like GSON to deserialize your json.

populate json array in android spinner

I am getting problem to parse json in android spinner. I have tried by below listed code but I am getting full json array in spinner like screenshot
My Json Array
{"Department":[{"1":"Computer"},{"2":"IT"},{"3":"Civil"}]} // like this type json string
My Code
public class GetDropdownItems extends AsyncTask<Void, Void, String[]> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String[] doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return new String[]{"unreachable"};
}
BufferedReader brstaffDep = new BufferedReader(new InputStreamReader(responsestaffDep));
String readstaffDep;
try {
while ((readstaffDep = brstaffDep.readLine()) != null) {
//System.out.println(read);
sbstaffdep.append(readstaffDep);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
brstaffDep.close();
} catch (IOException e) {
e.printStackTrace();
}
String[] finaldata = new String[1];
finaldata[0] = sbstaffdep.toString();
return finaldata;
}
#Override
protected void onPostExecute(String[] s) {
super.onPostExecute(s);
if (s[0].equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
String[] dataofdropdowndep = s[0].split(",");
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
public class GetDropdownItems extends AsyncTask<Void, Void, String> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return "unreachable";
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
responsestaffDep, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("-------------", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s.equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
Json js=new Json(s);
JSONArray array=js.getJSONArray("Department");
for(JSONArray b:array){
// traverse array here
}
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
HI Change your Json Response from server or you can change manually .
Here is your format :
{"Department"
[
{
"1": "Computer"
},
{
"2": "IT"
},
{
"3": "Civil"
}
]
}
Please check it with any json viewer format online.
this type json data:
check this json array:
{
"schools": [{
"Name": "Hill View Elementary",
"SchoolID": "HVE"
}, {
"Name": "Mill View",
"SchoolID": "MVE"
}, {
"Name": "Big School",
"SchoolID": "BSC"
}]
}
your mistake is you are not putting comma between two objects
The way you are fetching the Json file is wrong, there is already Json classes that can easly get each array,object or key alone.
org.json is the library we are going to use with the JSONArray and JSONObject classes.
Before we start you should know a basic understanding of the Json file scheme :
"name":{} this is the array syntax represented by the {} symbols, this array can hold arrays,objects or keys.
[] represent and object which can hold arrays and keys too but it doesn't have name.
"key":"value" now the is key type which can hold the data or values you want and has a key to retrieve it by name.
Now here is a piece of code to fetch your file and get each part of the Json file alone and then you can populate it as you wish.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
public class Fetch {
final private static String DEPARTMENT = "Department";
String [] departments ;
public void fetch(Resources r , int resourceID) {
String JsonString = readStringFromRaw(r, resourceID);
//the whole josn file is a json object even if it starts with { and ends with } so...
try {
JSONObject mainObject = new JSONObject(JsonString);
// the JSONObject throws a JSONException if there is something wrong with the syntax
JSONArray department = mainObject.getJSONArray(DEPARTMENT);
int length = department.length();
departments = new String[length];
JSONObject object;
for(int i = 0 ; i < length ; i++){
object = department.getJSONObject(i);
departments[0] = object.getString(""+i+1);
//this because you tagged the keys with 1 , 2 , 3 and so on.. so it has the value of the object that it is in + 1 .
//the reason I put "" empty quotations is because I want it a string so this is a way to cast the numbers to strings .
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String readStringFromRaw(Resources r, int resourceID) {
InputStream is = r.openRawResource(resourceID);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(1000);
String line;
try {
while ((line = br.readLine()) != null)
sb.append(line);
br.close();
is.close();
return sb.toString();
} catch (IOException e) {
return e.getMessage();
}
}
}
With this class you can get a String array holding the departments you want for your json file that you have.
The heirarchy between arrays and objects is very important so keep in mind that when you write a json file make it less complicated to extract the information easier.

Android JsonArray into ListView

Im trying to parse json array data into listview!I searched the whole internet and always was on one point! Json aray must have header something like this
"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
Where by my understanding the "emp_info" is the header file by which i must search for rest data inside it in android!My College pretending that i can accept and parse the same data into listview without that header name,but every bit of code where i searched to parse json in android was a single line like this!
JSONObject obj = new JSONObject(jsonString);
JSONArray stations = obj.getJSONArray("emp_inf");
where i just have to put the jsonarray header file as you can see in this piece of code!So please help me is that possible to accept json array without this code?because if i try to remove this code i get nullpointer in my code!Will be very happy if you could at least say yes or no!
Posting Full Codes!
Here is the android class which gets the Json and loads it into List View
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://54.148.41.171/server/index/dompy");
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
String outPut = name + "-" + number;
employeeList.add(createEmployee("data", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employee no" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
And by this json array im successfully able to fetch the json which type is the next!
{"emp_info":[{"employee name":"Adam","employee no":"101700"},{"employee name":"John","employee no":"101701"},{"employee name":"Paul","employee no":"101702"},{"employee name":"Mark","employee no":"101703"},{"employee name":"Donald","employee no":"101704"},{"employee name":"Brain","employee no":"101705"},{"employee name":"Kevin","employee no":"101706"}]}
And here is the json array which my college pretends that i must accept!
{"data":"123"}
And im Saying that its not possible to load this json into list view just because it dont have header file like mine the emp_info,but hes saying its not matter i just MUST accept!We just on same project and i just cant understand is it even possible to do what he says?
String name = jsonChildNode.optString("empployee no");
String number = jsonChildNode.optString("etc.");
How can you get the data by "etc." tag I could not understand it firstly. It should return "" instead of employee number.

How to make onPostExecute() or Json parsing work?

I am a beginner in Android, and I am writing a short program to download a JSON feed from URL and parse it. I use AsyncTask to do the downloading.
The doInBackground() part seems to work well. Then I set my breakpoint to onPostExecute(), it can even stop at parseJSON(result), and 'result' is showing the correct json string downloaded. But when I try to step into parseJSON(result), it will NOT step into the function correctly(either throw JSONException directly or go to some random lines within parseJSON(result)).
From DDMS log it's not showing any valuable information as well.
How might I find what the problem is? Is it because I used onPostExecute() incorrectly, or parseJSON() has some problem?
public class MainActivity extends Activity {
private listItem[] items;
public class listItem {
String title;
String description;
String imageHref;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new listItem[50];
new DownloadJsonFeed().execute("http://dl.dropbox.com/u/10168342/facts.json");
}
private class DownloadJsonFeed extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
return downloadUrl(params[0]);
} catch (IOException e) {
return "Unable to retrieve json feed. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
try {
parseJSON(result); // Here !!!!!!
} catch (JSONException e) {
}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
} finally {
if (is != null) {
is.close();
}
}
}
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = new JSONArray(rows);
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}
JSONObject.getString() will try to get String type value, but what you want is array type.
I think you didn't get the JSON array right. The json_obj.getString will give you an String instead an array.
Try to change as follows:
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = json_obj.getJSONArray("rows"); //<---- change this line
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}

Categories

Resources