How to display the parsed JSON data in android - android

I have parsed the JSON data and storing the parsed JSON data into ArrayList HashMap with the key value ,when I want to display the parsed data I am getting only the last value of the parsed Data rest all data are not displayed for reference
public HashMap<String,String> map = new HashMap<String, String>();
create HASHmap then arraylist
public static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
void parsing(JSONObject json)
{
String id="";
String countryn="";
try
{
countryobj = json.getJSONArray("country_details");
for(int i = 0;i<countryobj.length(); i++)
{
JSONObject items = countryobj.getJSONObject(i);
Log.e("i","value==="+i);
if(items.has("countryid"))
{
id = items.getString("countryid");
map.put("countryid",id);
Log.e("id","valueID==="+id);
}
if(items.has("country"))
{
countryn= items.getString("country");
map.put("country",countryn);
Log.e("counyrt","valueName==="+countryn);
}
contactList.add(i,map);
Log.e("lisvaluet","val--"+i +contactList.get(i));
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
in Log I am getting only 08-20 12:13:45.830: E/--ID---(654): value--{countryid=275, country=Palestinian Territory} with 269 times can any help me out where I am doing wrong in storing the parsed data , I am stuck here.

Check this.
private JSONObject[] items;
JSONArray countryobj = json.getJSONArray("country_details");
items = new JSONObject[countryobj.length()];
for(int i=0, i < countryobj.length(); i++)
{
items[i] = countryobj.optJSONObject(i);
id = items[i].getString("countryid");
map.put("countryid",id);
countryn= items[i].getString("country");
map.put("country",countryn);
contactList.add(i,map);
}

Related

Unable to get the JSON data from the JSONObject in android?

Currently, I'm having a minor trouble trying to get the string data from the jsonArray, however, I'm unable to get the value . I've got the data in the json object Example:
{
"lot":[
{
"id":"271",
"lot_date":"2015-05-25"
}
],
"numb3":[
{
"id":"675",
"lot_date":"2015-05-25"
}
],
"num4":[
{
"id":"676",
"lot_date":"2015-05-25"
}
],
"result":"OK"
}
The data above is stored in the JsonObject jsonobj. And what I want to do is to check if the JSON array JSONArray lot6 = jsonobj.optJSONArray("lot6"); contains the values or not , and if it's not null get the string data. However, even the data contains in the lot6 array, the result is null.
JSONArray lot6 = jsonobject.optJSONArray("lot6");
Log.d("LOT6",lot6+"");
if (lot6 != null) {
jsonarry2 = jsonobject.getJSONArray("lot6");
//3.if not null get the string data from the
for (int i = 0; i < jsonarry2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarry2.getJSONObject(i);
ListData worldpop = new ListData();
worldpop.set_date(jsonobject.optString("lot_date"));
worldpop.set__id(jsonobject.optString("id"));
world.add(worldpop);
}
//5. test this part of the variable
String lotdate = world.get(0).get_date();
String lotid = world.get(0).get__id();
Hi please check Not lot6 its lot. please folloe below formate to get out out.
String s="{\"lot\":[{\"id\":\"271\",\"lot_date\":\"2015-05-25\"}],\"numb3\":[{\"id\":\"675\",\"lot_date\":\"2015-05-25\"}],\"num4\":[{\"id\":\"676\",\"lot_date\":\"2015-05-25\"}],\"result\":\"OK\"} ";
try{
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
String arr[]={"lot","numb3","num4"};
for(int i=0;i<json.size()-1;i++){
JSONArray ja=(JSONArray)json.get(arr[i]);
for(int j=0;j<ja.size();j++){
JSONObject jo1=(JSONObject) ja.get(j);
System.out.println("lot_date: "+jo1.get("lot_date")+" Id "+jo1.get("id"));
}
// System.out.println(ja);
}
System.out.println(json.get("result"));
}catch (Exception e) {
System.out.println(e);
}

how to parse JSONArray in android NullPointerException

I want to parse jsonObject passed by another activity
intent.putextra("result", json.toString());
It shows everything right with name, branch and session. but it shows NullPointerException while fetching array. at here
mSubList.add(map);
this array has 6 rows.
this is my code. please tell me exactly where Im wrong.
JSONObject json;
ListView sub_list;
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mSubList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_page);
name = (TextView)findViewById(R.id.name_roll);
branch= (TextView)findViewById(R.id.branchname);
session = (TextView)findViewById(R.id.Session);
sub_list = (ListView)findViewById(R.id.sub_list);
try {
json = new JSONObject(getIntent().getStringExtra("result"));
name.setText(json.getString("REGNO")+" - "+json.getString("STUDENTNAME"));
branch.setText(json.getString("BRANCHNAME"));
session.setText(json.getString("SESSIONNAME"));
mComments = json.getJSONArray("DATA");
// looping through all subjects according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String code = c.getString("CCODE");
String subject = c.getString("COURSENAME");
String passfail = c.getString("PASSFAIL");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put("CCODE", code);
map.put("COURSENAME", subject);
map.put("PASSFAIL", passfail);
// adding HashList to ArrayList
mSubList.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mSubList,
R.layout.singlesubject, new String[] { "CCODE", "COURSENAME",
"PASSFAIL" }, new int[] { R.id.sub_id, R.id.sub_name,R.id.sub_res });
sub_list.setAdapter(adapter);
}catch(Exception e){
e.printStackTrace();
}
}
}
if I want to change each listitem background(R.layout.singlesubject) if "PASSFAIl"=P then Green color else Red color. then what changes i have to do ?
mSubList.add(map);
this line of code is failing because you do not initialize the array before adding the map
You can initialize it by using...
mSubList = new ArrayList<Hashmap<String, String>>();
init your mSubList before add item
mSubList = new ArrayList<HashMap<String, String>>();
I think you forgot to initialize mSubList before adding data to it:
mSubList = new ArrayList<HashMap<String, String>>();

How to filter data from Json in android?

i am getting the data in json form like
{"Users":[
{"category_id":"1","user_email":"a#a.com"},
{"category_id":"5","user_email":"a#b.com"},
{"category_id":"1","user_email":"a#c.com"},
{"category_id":"5","user_email":"a#d.com"},
{"category_id":"3","user_email":"a#d.com"}]}
now my question is can it is possible in android to filter this json base on category_id for example if i am select 1 from my spinner then it should be return the data which is content the category_id = 1 example
{"Users":[{"category_id":"1","user_email":"a#a.com"},
{"category_id":"1","user_email":"a#c.com"}]}
if select 3 then it should return the user which is content the category_id = 3
{"Users":[
{"category_id":"3","user_email":"a#d.com"}]}
i just want to know is there any method is available in android so i can easily filter the
data.
First you need to create your variables in your activity
//URL to get JSON
private static String url = "your url to parse data";
//JSON Node Names
private static final String TAG_USERS = "users";
private static final String TAG_CATEGORY_ID = "category_id";
private static final String TAG_USER_EMAIL = "user_email";
// Data JSONArray
JSONArray users = null;
//HashMap to keep your data
ArrayList<HashMap<String, String>> userList;
inside onCreate() function instantiate your userList
userList = new ArrayList<HashMap<String, String)>>();
then you need to parse your data and populate this ArrayList in doInBackground() function
//Create service handler class instance
ServiceHandler sh = new ServiceHandler();
//Url request and response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if(jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//Get Json Array Node
users = jsonObj.getJSONArray(TAG_USERS);
// Looping through all data
for(int i = 0; i < users.length(); i++) {
JSONObject u = users.getJSONObject(i);
String category_id = u.getString(TAG_CATEGORY_ID);
String user_email = u.getString(TAG_USER_EMAIL);
// Temporary HashMap for single data
HashMap<String, String> user = new HashMap<String, String>();
// Adding each child node to Hashmap key -> value
user.put(TAG_CATEGORY_ID, category_id);
user.put(TAG_USER_EMAIL, user_email);
//Adding user to userList
userList.add(user);
}
}catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from url");
}
Now you have your data stored in your userList. You can use your userList however you want. To get the category_id field in the list you can use this syntax
// i being the counter of your loop
String catId = userList.get(i).get("category_id");
if(catId == 3) {
... your code
}
finally i got the answer..
private void applySearch(String searchStr) {
ArrayList<User> searchEmail = new ArrayList<User>();
for (int i = 0; i < UserArray.size(); i++) {
if(UserArray.get(i).getcategory_id().toLowerCase().contains(searchStr.toLowerCase())) {
searchEmail.add(UserArray.get(i));
}
}
// set the adapter hear
}
without for loop it is not possible ...
UserArray is my array list content user object
Use JSONObject from the Android SDK. Check out the documentation here:
http://developer.android.com/reference/org/json/JSONObject.html
You basically need to parse the JSON, then loop through and only operate on the items with the specified category id.
For larger data sets, using JsonReader will be more performant if written properly.
http://developer.android.com/reference/android/util/JsonReader.html

How to parse JSON data to Android?

I have followed a tutorial online and tweaked some of the code, I would like the application to read information from a different location. Currently the app is correctly reading the data from here. Now I would like to read data from here. I'm looking to attain Observation Time, Temp_C & Visibility, I imagine I would need to change my code within the try { bracket in order to read this data? Any suggestions?
public class MainActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_DATA = "contacts";
private static final String TAG_OBSERV = "name";
private static final String TAG_TEMP = "email";
private static final String TAG_VISIB = "gender";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParse jParser = new JSONParse();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_OBSERV);
String email = c.getString(TAG_TEMP);
String gender = c.getString(TAG_VISIB);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_OBSERV, name);
map.put(TAG_TEMP, email);
map.put(TAG_VISIB, gender);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_OBSERV, TAG_TEMP, TAG_VISIB }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_OBSERV, name);
in.putExtra(TAG_TEMP, cost);
in.putExtra(TAG_VISIB, description);
startActivity(in);
}
});
}
}
How to parse JSON data to Android?
So at first you should move your code where you are attempt to perfrom network connection(fetching data from JSON) to background Thread. Actually you're doing it at Main(UI) Thread and it's not very good and correct. If your app will be installed on a device that runs on Android 3.0+ you will get NetworkOnMainThreadException and it's not nice, ins't?
Second, save your JSON and make some formatting to see its structure better. Multiset bracket { indicates JSONObject and bracket [ indicated JSONArray.
Now you should be able to parse JSON. Now i write you a little snippet of code how to start:
JSONObject o = new JSONObject(sourceString);
if (o != null) {
JSONObject data = o.getJSONObject("data"); // getting JSONObject with key data
if (data != null) {
JSONArray current = data.getJSONArray("current_condition");
}
}
...
The easiest and prettiest way would be to create a DTO with the wanted properties and then use a library such as Jackson or Gson to map the JSON to object(s). Then it would be 2 lines of code instead of that 'manual parsing'.
Here is the way you should parse and get your values from that json :
JSONObject mMainObject = new JSONObject(myResponseString);
if(mMainObject != null){
JSONObject data = mMainObject.getJSONObject("data");
if(data != null){
JSONArray currentCondition = data.getJSONArray("current_condition");
if(currentCondition != null){
for(int i = 0; i < currentCondition.lenght(); i++){
JSONObject obj = currentCondition.get(i);
if(obj != null){
String observation_time = obj.getString("observation_time");
String temp_C = obj.getString("temp_C");
String visibility = obj.getString("visibility");
}
}
}
}
}
Doing that you should consider the proper way to download the data from internet using AsyncTask for example. In this way it will not block your UI and your app will be more responsive.
Hope this help! : )

ArrayAdapter : Json data to be sent to spinner

Hi I have created an activity which pulls data from json format text and displays in a spinner view. But im a little confused with the last part. The contactList is a ArrayList type, ArrayAdapter is not accepting contactList as its arugument.
Is
Here's my code
public class RegisterForEventActivity extends Activity {
private static String url = "http://10.0.2.2/Contacts.txt";
private static final String TAG_NAME = "name";
private static final String TAG_CONTACTS = "contacts";
JSONArray jsonArray = null;
Spinner areaspinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] array_spinner = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, contactList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaspinner.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is because you are passing a list of HashMap, and not an array of String. Make an array of String, add your contact data in it and pass it to the array.
instead of using this
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
use this
ArrayList<String> contactList = new ArrayList<String>();
Yes, I figured it out!
sp=(Spinner)findViewById(R.id.spinner1);
// Hashmap for ListView
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
System.out.println("Hello");
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] items = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
items[i]=c.getString(TAG_NAME);
System.out.println("Hello events "+items);
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources