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.
Related
I'm trying to get JSON value by EditText.
At first I had a bunch of nullpointer exceptions, solved that. But now my function just isn't working. Been wrapping my brain over this...
I tried to create a EditText, get that value to a String, and get it over to the JSON Object. Don't know what I'm doing wrong... Or am I forgetting something?
public class MyActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
EditText edt;
Button Btngetdata;
//URL to get JSON Array
private static String url = "*";
//JSON Node Names
private static final String TAG_TAG = "tag";
private static final String TAG_ID = "id";
private static final String TAG_LAST_NAME = "last_name";
private static final String TAG_EMAIL = "country";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Btngetdata = (Button)findViewById(R.id.getdata);
edt = (EditText)findViewById(R.id.edittext);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MyActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_TAG);
JSONObject c = user.getJSONObject(0);
String xyz = edt.getText().toString();
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
edt.setText(xyz);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
{"tag":[{"id":"1","first_name":"Philip","last_name":"Porter","email":"pporter0#admin.ch","country":"China","ip_address":"26.83.255.206"},{"id":"2","first_name":"Nancy","last_name":"Martin","email":"nmartin1#google.ca","country":"Colombia","ip_address":"160.93.80.1"},{"id":"3","first_name":"Ann","last_name":"Peterson","email":"apeterson2#utexas.edu","country":"China","ip_address":"251.254.74.162"},{"id":"4","first_name":"Rachel","last_name":"Clark","email":"rclark3#mayoclinic.com","country":"Brazil","ip_address":"58.218.248.5"},{"id":"5","first_name":"Heather","last_name":"Burton","email":"hburton4#creativecommons.org","country":"Ethiopia","ip_address":"244.69.119.16"},{"id":"6","first_name":"Ruth","last_name":"Lane","email":"rlane5#va.gov","country":"Brazil","ip_address":"18.173.102.54"},{"id":"7","first_name":"Andrew","last_name":"Turner","email":"aturner6#devhub.com","country":"United States","ip_address":"13.119.240.234"},{"id":"8","first_name":"Wanda","last_name":"Medina","email":"wmedina7#pagesperso-orange.fr","country":"Netherlands","ip_address":"151.139.21.237"},{"id":"9","first_name":"Robert","last_name":"Elliott","email":"relliott8#joomla.org","country":"United States","ip_address":"34.200.249.109"},{"id":"10","first_name":"Kevin","last_name":"Harrison","email":"kharrison9#nih.gov","country":"Brazil","ip_address":"106.84.164.86"}]}
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "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();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
EDIT
JSONObject c = user.getJSONObject(Integer.parseInt(xyz));
I Modified to this, im getting a response other than default 1 when base value was getJSONObject(0), but now im entering 1 and im getting 2, entering 4 getting 5..
Does anyone know how to solve this one?
If you are trying to parse the whole json array then use this.In you post execute
List<String> allid = new ArrayList<String>();
JSONArray obj= jsonResponse.getJSONArray("tag");
for (int i=0; i<obj.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String id= actor.getString("id");
allNames.add(id);
}
Then you can use a for loop to get the id in the list accordingly.
Otherwise you can do this parsing Using the Gson Library(you can download Gson library here
Just create a class in your package
public class DetailArray {
public boolean status;
public List<Detail_User> details;
public class Detail_User {
public String id;
public String first_name;
public String last_name;
public String email;
public String country;
}
}
In your post execute
Where response is the json response
DetailArray detail1 = (new Gson()).fromJson(response.toString(),
DetailArray.class);
Now Suppose , if you want to set the names in a list view then
//return a arraylist
private ArrayList<String> getName(DetailArray detail) {
ArrayList name = new ArrayList<String>();
for (int i=0;i< detail.details.size();i++) {
name.add(splitStr[i]);
}
return names;
}
Setting the array adapter and setting it to a list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
getName(detail);
listview.setAdapter(arrayAdapter);
For a particular position try like this
int positionToShow = Integer.parseInt(edt.getText().toString()) - 1;
user = json.getJSONArray(TAG_TAG);
for(int i = 0; i < user.length(); i++) {
if(positionToShow == i) {
JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_LAST_NAME);
String email = c.getString(TAG_EMAIL);
uid.setText(id);
name1.setText(name);
email1.setText(email);
}
}
i've parse your json ...acc to number entered ..and it shows exact result....refer this....
final EditText no=(EditText)findViewById(R.id.editText1);
final Button click=(Button)findViewById(R.id.button1);
click.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try
{
Toast.makeText(MainActivity.this, no.getText().toString(), 0).show();
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet("http://192.168.0.30/test.js");
HttpResponse response=client.execute(request);
HttpEntity entity=response.getEntity();
String json=EntityUtils.toString(entity);
JSONObject j1=new JSONObject(json);
JSONArray ja1=j1.getJSONArray("tag");
JSONObject j2=ja1.getJSONObject(Integer.parseInt(no.getText().toString())-1);
Toast.makeText(MainActivity.this, j2.getString("first_name").toString() , 0).show();
entity.consumeContent();
}
catch(Exception e)
{
e.getStackTrace();
Toast.makeText(MainActivity.this, e.toString() , 0).show();
}
}
});
This is my
I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:
CustomizedListView.java
public class CustomizedListView extends Activity {
// All static variables
static final String URL ="";
// XML node keys
JSONArray theaters = null;
JSONObject json = null;
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
json=new JSONObject();
try {
// Getting Array of Contacts
theaters = json.getJSONArray(KEY_SONG);
// looping through All Contacts
for(int i = 0; i < theaters.length(); i++){
JSONObject c = theaters.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(KEY_TITLE);
String distance = c.getString(KEY_DURATION);
String pincode = c.getString(KEY_ARTIST);
//String image = c.getString(TAG_MOVIEIMAGE);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put(KEY_TITLE,distance);
map1.put(KEY_DURATION,pincode);
map1.put(KEY_ARTIST,name);
//map.put(TAG_MOVIEIMAGE, image);
// adding HashList to ArrayList
songsList.add(map1);
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("this is error" +e);
}
// adding HashList to ArrayList
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:
pl help me to resolve error..
You are not assigning any value to the json object, you have to do it in Async Task to fetch the feed from your service.
As #Abed El Majeed K has already said, you need to do it as an async task.
i've found that any downloading, or internet actions are required to be preformed on a separate thread & not on the MainUI.
An example:
public class task extends AsyncTask<String, Void, String>{
private StringBuilder inputStreamToString(InputStream is){
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedRead rd = new Buffer3edReader(new InputStreamReader(is));
while((rLine = rd.readLine()) != null){
answer.append(rLine);
}
return answer;
}
protected String doInBackground(String... param){
String uRL = "http://example.com";
URL url = new URL(uRL);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
return jsonResult;
}
protected void onPostExecute(String result){
JSONObject jsonResponse = new JSONObject(result);
JSONArray jsonNode = jsonResponse.getJSONArray(whatever_your_json_stream_is_called);
for(int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonchild = jsonNode.getJSONObject(i);
String some_value = jsonchild.getString(some_key);
...
}
}
}
by running requests on AsyncTask, you are not causing the MainUiThread to pause, or wait for the download to complete.
With that said, the JSON source you are using is incorrect.
JSON structure is like this:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
here might help: http://json.org/
i am getting JSON data from http://abinet.org/?json=1 and displaying the titles in a ListView. the code is working fine but the problem is, it is skipping few titles in my ListView and one title is being repeated.
You can see the json data from url given above by copy paste it in JSON editor online http://www.jsoneditoronline.org/
i want titles in the "posts" array to be displayed in ListView, however it is being displayed like this:
if you see the JSON data from the link above, its missing like 3 titles (they should come between the first and second title) and 5th title is being repeated. Dont know why this is happening. What minor adjustments i need to do? Please help me.
this is my code :
public class MainActivity extends Activity {
// URL to get contacts JSON
private static String url = "http://abinet.org/?json=1";
// JSON Node names
private static final String TAG_POSTS = "posts";
static final String TAG_TITLE = "title";
private ProgressDialog pDialog;
JSONArray contacts = null;
TextView img_url;
ArrayList<HashMap<String, Object>> contactList;
ListView lv;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.newslist);
contactList = new ArrayList<HashMap<String, Object>>();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
// Making a request to url and getting response
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject jsonObj = jParser.getJSONFromUrl(url);
// if (jsonStr != null) {
try {
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_POSTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
// JSONObject c = contacts.getJSONObject(i);
JSONObject posts = contacts.getJSONObject(i);
String title = posts.getString(TAG_TITLE).replace("’", "'");
JSONArray attachment = posts.getJSONArray("attachments");
for (int j = 0; j< attachment.length(); j++){
JSONObject obj = attachment.getJSONObject(j);
JSONObject image = obj.getJSONObject("images");
JSONObject image_small = image.getJSONObject("thumbnail");
String imgurl = image_small.getString("url");
HashMap<String, Object> contact = new HashMap<String, Object>();
contact.put("image_url", imgurl);
contact.put(TAG_TITLE, title);
contactList.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
adapter=new LazyAdapter(MainActivity.this, contactList);
lv.setAdapter(adapter);
}
}
}
this is my JsonParser class (although its not required):
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "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();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and this is adapter class:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, Object>> data;
private static LayoutInflater inflater=null;
public LazyAdapter(Activity a,ArrayList<HashMap<String, Object>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.third_row, null);
TextView title = (TextView)vi.findViewById(R.id.headline3); // title
SmartImageView iv = (SmartImageView) vi.findViewById(R.id.imageicon);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
// Setting all values in listview
title.setText((CharSequence) song.get(MainActivity.TAG_TITLE));
iv.setImageUrl((String) song.get("image_url"));
thumb_image);
return vi;
}
}
Please help me. I am stuck at this for more than a week now. I think there is just something to be changed in my MainActivity class.
Some of the 10 (well today there are 10 ) 'titles' have no 'attachments'. Some have one and some have two. There are only 5 titles wich have one or two images. You only create a new
HashMap<String, Object> contact
if there are attachments. (The attachment are the images). You should create the 'contact' before you enter the attachments loop. Further you only need one image for each title. You can set the image null if there are no attachments. In getView if the image is null you set some image from your drawable res.
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...
I'm trying to integrate an API into an android application I am writing, but am having a nightmare trying to get the JSON array. The API has a URL that returns a an JSON array, but having never used JSON before I have no idea how this works, or how to do it.
I've looked and found tons, and tons of examples, but nothing to explain why/how it is done. Any help understanding this would be greatly appreciated.
This is what I've ended up with, again with no understanding of JSON, it was a shot in the dark on my part (using examples/tutorials as a guide)...but it doesn't work :(
import org.json.*;
//Connect to URL
URL url = new URL("URL WOULD BE HERE");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
//Get Data from URL Link
int ok = connection.getResponseCode();
if (ok == 200) {
String line = null;
BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = buffer.readLine()) != null)
sb.append(line + '\n');
//FROM HERE ON I'm Kinda Lost & Guessed
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString()); //ERROR HERE:complains it dosn't know what JSONValue is
JSONArray array = (JSONArray)obj.get("response");
for (int i=0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("name")); //Used to debug
}
}
UPDATE/SOLUTION:
So, it turns out that there was nothing wrong w/t the code. I was missusing what I thought it returns. I thought it was a JSONObject array. In actuality it was a JSONObjects wrapped in an array, wrapped in a JSONObject.
For those interested/ having similar issues, this is what I ended up with. I broke it into two methods. First connect/download, then:
private String[] buildArrayList(String Json, String Find) {
String ret[] = null;
try {
JSONObject jObject = new JSONObject(Json);
JSONArray jArray = jObject.getJSONArray("response");
ret = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String var = json_data.getString(Find);
ret[i] = var;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
1) use webservice to download your required Json string
2) convert it to your desired object using Google Gson
Gson gson = new Gson();
MyClass C1 = gson.fromJson(strJson, MyClass.class);
Here you used JSONValue.parse() that is invalid.
Insted of that Line write this code:
JSONObject obj = new JSONObject(<String Value>);
Ok my friend, i solved the same problem in my app with the next code:
1.- Class to handle the Http request:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONObject jObj1 = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "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.e("JSONObject(JSONParser1):", json);
} catch (Exception e) {
Log.e("Buffer Error json1" +
"", "Error converting result json1:" + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj1 = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser1:", "Error parsing data json1:" + e.toString());
}
// return JSON String
return jObj;
}
}
Later, a class to handle the json info (Arrays, Objects, String, etc...)
public class ListViewer extends ListActivity{
TextView UserName1;
TextView LastName1;
// url to make request
private static String url = "http://your.com/url";
// JSON Node names
public static final String TAG_COURSES = "Courses"; //JSONArray
//public static final String TAG_USER = "Users"; //JSONArray -unused here.
//Tags from JSon log.aspx All Data Courses.
public static final String TAG_COURSEID = "CourseId"; //Object from Courses
public static final String TAG_TITLE = "title";
public static final String TAG_INSTRUCTOR = "instructor";
public static final String TAG_LENGTH = "length";
public static final String TAG_RATING = "Rating"; //Object from Courses
public static final String TAG_SUBJECT = "subject";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_STATUS = "Status"; //Object from Courses
public static final String TAG_FIRSTNAME = "FirstName"; //Object from User
public static final String TAG_LASTNAME = "LastName"; //Object from User
// contacts JSONArray
JSONArray Courses = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
// Hashmap for ListView
final ArrayList<HashMap<String, String>> coursesList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance (json2)
JSONParser2 jParser2 = new JSONParser2();
// getting JSON string from URL json2
final JSONObject json2 = jParser2.getJSONFromUrl(url);
try {
// Getting Array of Contacts
Courses = json2.getJSONArray(TAG_COURSES);
// looping through All Courses
for(int i = 0; i < Courses.length(); i++){
JSONObject courses1 = Courses.getJSONObject(i);
// Storing each json item in variable
String courseID = courses1.getString(TAG_COURSEID);
//String status = courses1.getString(TAG_STATUS);
String Title = courses1.getString(TAG_TITLE);
String instructor = courses1.getString(TAG_INSTRUCTOR);
String length = courses1.getString(TAG_LENGTH);
String rating = courses1.getString(TAG_RATING);
String subject = courses1.getString(TAG_SUBJECT);
String description = courses1.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COURSEID,courseID);
map.put(TAG_TITLE, Title);
map.put(TAG_INSTRUCTOR, instructor);
map.put(TAG_LENGTH, length);
map.put(TAG_RATING, rating);
map.put(TAG_SUBJECT, subject);
map.put(TAG_DESCRIPTION, description);
//adding HashList to ArrayList
coursesList.add(map);
}} //for Courses
catch (JSONException e) {
e.printStackTrace();
}
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, coursesList,
R.layout.list_courses,
new String[] { TAG_COURSEID, TAG_TITLE, TAG_INSTRUCTOR, TAG_LENGTH, TAG_RATING, TAG_SUBJECT, TAG_DESCRIPTION }, new int[] {
R.id.txt_courseid, R.id.txt_title, R.id.txt_instructor, R.id.txt_length, R.id.txt_rating, R.id.txt_topic, R.id.txt_description });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
//#Override --------check this override for onClick event---------
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String courseID = ((TextView) view.findViewById(R.id.txt_courseid)).getText().toString();
String Title = ((TextView) view.findViewById(R.id.txt_title)).getText().toString();
String instructor = ((TextView) view.findViewById(R.id.txt_instructor)).getText().toString();
String length = ((TextView) view.findViewById(R.id.txt_length)).getText().toString();
String rating = ((TextView) view.findViewById(R.id.txt_rating)).getText().toString();//Check place in layout
String subject = ((TextView) view.findViewById(R.id.txt_topic)).getText().toString();// <- HERE
String description = ((TextView) view.findViewById(R.id.txt_description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(TAG_COURSEID, courseID);
in.putExtra(TAG_TITLE, Title);
in.putExtra(TAG_INSTRUCTOR, instructor);
in.putExtra(TAG_LENGTH, length);
in.putExtra(TAG_RATING, rating);
in.putExtra(TAG_SUBJECT, subject);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});//lv.SetOnclickListener
}//onCreate
}// Activity
in this case, i'll get the Arrays, objects... Hope this give you ideas...