JSON data is read but cannot be converted to JSONArray - android

I'm developing an app which reads JSON data. Json Data is parsed but it is not viewing in the listview. Logcat says about a type mismatch. I'm not that much familiar in Json.
http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json
This is my logcat and code. Please hemp me with this.
org.json.JSONException: Index 1 out of range [0..1)
org.json.JSONArray.get(JSONArray.java:263)
org.json.JSONArray.getString(JSONArray.java:421)
com.is.parsej.ParseJ$GetContacts.doInBackground(ParseJ.java:141)
com.is.parsej.ParseJ$GetContacts.doInBackground(ParseJ.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:287)
java.util.concurrent.FutureTask.run(FutureTask.java:234)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
public class ParseJ extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json";
// JSON Node names
private static final String TAG_COd = "list"; //edited
private static final String TAG_ID = "dt"; //edited
private static final String TAG_WEATHER = "weather";
private static final String TAG_MAIN = "main";
private static final String TAG_DESC = "description";
private static final String TAG_TEMP = "temp";
private static final String TAG_DAY = "day";
private static final String TAG_MIN = "min";
private static final String TAG_MAX = "max";
private static final String TAG_NIGHT = "night";
private static final String TAG_MORN= "morn";
private static final String TAG_HUMIDITY = "humidity";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_j);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String weather = ((TextView) view.findViewById(R.id.main))
.getText().toString();
String Temp = ((TextView) view.findViewById(R.id.Descrption))
.getText().toString();
String Humidity = ((TextView) view.findViewById(R.id.temp))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_WEATHER, weather);
in.putExtra(TAG_TEMP, Temp);
in.putExtra(TAG_HUMIDITY, Humidity);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ParseJ.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_COd);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String humidity = c.getString(TAG_HUMIDITY);
// Phone node is JSON Object
JSONObject temp = c.getJSONObject(TAG_TEMP);
String day = temp.getString(TAG_DAY);
String maxTemp = temp.getString(TAG_MAX);
String minTemp = temp.getString(TAG_MIN);
String morningTemp = temp.getString(TAG_MORN);
//edited
JSONArray weather = c.getJSONArray(TAG_WEATHER);
String main = weather.getString(1);
String desc = weather.getString(2);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_DAY, day);
contact.put(TAG_DESC, desc);
contact.put(TAG_HUMIDITY, humidity);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ParseJ.this, contactList,
R.layout.list_item, new String[] { TAG_DAY, TAG_DESC,
TAG_HUMIDITY }, new int[] { R.id.temp,
R.id.main, R.id.Descrption });
setListAdapter(adapter);
}
}
}

based on your JSON it is just a list of element. Arrays have [ at the beginning and ] at the end. look closely at your JSON you may find some array elements there that has [].
weather only has 1 element
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]
index out of bounds because you are using
JSONArray weather = c.getJSONArray(TAG_WEATHER);
String main = weather.getString(1);
String desc = weather.getString(2);
where there is no 1 and 2 in your json array weather, since the weather seems to have only 1 element put it in another json object
JSONObject weather = c.getJSONArray(TAG_WEATHER).getJSONObject(0);
String main = weather.getString("main");
String desc = weather.getString("description");

JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("list");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
}
change this in your code and let me know, if any issue.

the json is here
{"cod":"200","message":0.2809,"city":{"id":1244926,"name":"Hambantota","coord":{"lon":81.1185,"lat":6.1241},"country":"LK","population":0},"cnt":10,"list":[{"dt":1409896800,"temp":{"day":301.95,"min":300.47,"max":302.12,"night":301.31,"eve":301.87,"morn":300.47},"pressure":1020.63,"humidity":88,"weather":[{"id":803,"main":"Clouds","description":"broken
clouds","icon":"04d"}],"speed":6.47,"deg":243,"clouds":56},{"dt":1409983200,"temp":{"day":301.11,"min":299.62,"max":301.29,"night":299.62,"eve":300.76,"morn":300.13},"pressure":1021.53,"humidity":92,"weather":[{"id":802,"main":"Clouds","description":"scattered
clouds","icon":"03d"}],"speed":6.66,"deg":249,"clouds":48},{"dt":1410069600,"temp":{"day":300.9,"min":299.36,"max":300.9,"night":299.58,"eve":300.2,"morn":299.36},"pressure":1022.25,"humidity":90,"weather":[{"id":803,"main":"Clouds","description":"broken
clouds","icon":"04d"}],"speed":7.21,"deg":242,"clouds":80},{"dt":1410156000,"temp":{"day":299.47,"min":298.71,"max":300.44,"night":299.5,"eve":299.96,"morn":298.71},"pressure":1023.27,"humidity":98,"weather":[{"id":802,"main":"Clouds","description":"scattered
clouds","icon":"03d"}],"speed":5.83,"deg":252,"clouds":44},{"dt":1410242400,"temp":{"day":301.38,"min":297.39,"max":301.38,"night":298.36,"eve":300.82,"morn":297.39},"pressure":1012.02,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":3.87,"deg":250,"clouds":76,"rain":0.38},{"dt":1410328800,"temp":{"day":301.77,"min":297.49,"max":301.77,"night":299.44,"eve":301.13,"morn":297.49},"pressure":1011.84,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":4.88,"deg":259,"clouds":27,"rain":0.82},{"dt":1410415200,"temp":{"day":302.15,"min":299.15,"max":302.15,"night":299.43,"eve":300.52,"morn":299.15},"pressure":1011.1,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":6.3,"deg":257,"clouds":64,"rain":1.82},{"dt":1410501600,"temp":{"day":301.52,"min":299.16,"max":301.52,"night":299.36,"eve":300.59,"morn":299.16},"pressure":1011.05,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":8.05,"deg":257,"clouds":50,"rain":2.38},{"dt":1410588000,"temp":{"day":301.26,"min":298.74,"max":301.26,"night":299.53,"eve":300.43,"morn":298.74},"pressure":1010.43,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":7.69,"deg":258,"clouds":33,"rain":1.34},{"dt":1410674400,"temp":{"day":300.01,"min":298.37,"max":300.01,"night":298.48,"eve":298.37,"morn":298.87},"pressure":1010.17,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate
rain","icon":"10d"}],"speed":8.36,"deg":253,"clouds":55,"rain":8.91}
and then you get object with tag "cod"
contacts = jsonObj.getJSONArray(TAG_COd)
"cod":"200"
you will get "200"
how can "200" be converted to JSONArray?
the array structure is just like this
[{"dt":1409896800},{"dt":1409896800},{"dt":1409896800},{"dt":1409896800}]
starts with "[" and end with "]"

Exception is self Explaining
org.json.JSONException: Value 200 at cod of type java.lang.String cannot be converted to JSONArray
You are converting String to JSONArray here,
contacts = jsonObj.getJSONArray(TAG_COd);
cod is a String while you're converting it to JSONArray
String cod = jsonObj.getJSONString(TAG_COd);

Related

how to prevent to show the duplicate and repetatvie value in listview when we update it by swipe down?

i used a list view in my app.i used scroll bar for update the details. i got complete updated list again.which added all the data in ny list. i wants to avoid it so plz suggest me how i retrict the duplicate values in list after updation.... my code snippet is here.....
public class MainActivity extends ListActivity implements SwipeRefreshLayout.OnRefreshListener {
private ProgressDialog pDialog;
ListView mListView;
SwipeRefreshLayout swipeLayout;
Adapter mAdapter;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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 single contact activity
Intent in = new Intent(getApplicationContext(),
ak.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
//Dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/* if (pDialog.isShowing())
pDialog.dismiss();*/
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE}, new int[]{R.id.name,
R.id.email, R.id.mobile});
setListAdapter(adapter);
}
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new GetContacts().execute();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
The only thing you have to do is set adapter like this way and it won't replicate data. It just add new data below older one.
adapter = null;
if (adapter == null) {
adapter = new CustomAdapter(this, arrayList);
listvie.setAdapter(adapter);
}
adapter.notifyDataSetChanged();
Hope it will work.
Thanks. :)
Solution is very simple.
Create ListAdapter before executing AsyncTask with empty Collection
Set adapter for ListView with created adapter
In AsyncTask create local field ArrayList<HashMap<String, String>> localList
Parsed contacts put to localList, not to contactList
After download items, clear Collection by calling contactList.clear();
Add download contacts contactList.addAll(localList);
Call adapter.notifyDataSetChanged();

Android JSON ListView import

I'm slowly turning crazy here.
I've got NewsActivity that gets information from a website and puts it in the listview but it isn't working.
public class NewsActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String NEWS_URL = "http://www.bandofbrothersgaming.nl/android/news.php";
// JSON Node names
private static final String TAG_POSTID = "sid";
private static final String TAG_POSTSUBJECT = "title";
private static final String TAG_POSTTEXT = "hometext";
// contacts JSONArray
JSONArray post_id = null;
// Hashmap for ListView
ArrayList < HashMap < String, String >> NewsList;
#
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
NewsList = new ArrayList < HashMap < String, String >> ();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#
Override
public void onItemClick(AdapterView <? > parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.post_id))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.post_subject))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.post_text))
.getText().toString();
// Starting single contact activity
/* Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);*/
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask < Void, Void, Void > {
#
Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#
Override
protected Void doInBackground(Void...arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(NEWS_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
post_id = jsonObj.getJSONArray(TAG_POSTID);
// looping through All Posts
for (int i = 0; i < post_id.length(); i++) {
JSONObject c = post_id.getJSONObject(i);
String postid = c.getString(TAG_POSTID);
String postsubject = c.getString(TAG_POSTSUBJECT);
String posttext = c.getString(TAG_POSTTEXT);
// tmp hashmap for single contact
HashMap < String, String > contact = new HashMap < String, String > ();
// adding each child node to HashMap key => value
contact.put(TAG_POSTID, postid);
contact.put(TAG_POSTSUBJECT, postsubject);
contact.put(TAG_POSTTEXT, posttext);
// adding contact to contact list
NewsList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#
Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NewsActivity.this, NewsList,
R.layout.list_item, new String[] {
TAG_POSTID, TAG_POSTSUBJECT,
TAG_POSTTEXT
}, new int[] {
R.id.post_id,
R.id.post_subject, R.id.post_text
});
setListAdapter(adapter);
}
}
}
When I run it LogCat says the following :
12-29 13:56:39.698: W/System.err(1685): org.json.JSONException: Value [{"hometext":"Welcome to Nuke-Evolution.<br \/><br \/>\r\n\r\nYou must now setup an admin account. You can do this by <a href=\"admin.php\">clicking here<\/a>.<br \/><br \/><br \/><br \/>\r\n\r\n<b>NOTE:<\/b> You can remove this by going into the News Administration or by clicking the delete button below.\r\n","sid":"1","time":"2005-07-02 10:38:28","title":"Welcome To Nuke-Evolution"},{"hometext":"<p>\n\ttest android<\/p>\n<p>\n\tandroid test<\/p>","sid":"2","time":"2014-12-28 23:21:25","title":"android test"}] of type org.json.JSONArray cannot be converted to JSONObject
Does anybodey knows what im doing wrong?
You are trying to convert jsonStr to a JSONObject, but in fact is a JSONArray, looking at the LogCat. So convert it to a JSONArray first, then iterate over it and get the data you are looking for.
You can use
JSONArray post_id = new JSONArray(jsonStr);
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
post_id = jsonObj.getJSONArray(TAG_POSTID);
because jsonStr you get is a JSONArray
That is response of you php file, review your code PHP.
try this
JSONArray jsonArr = new JSONArray(jsonStr);
for(int i = 0; i < jsonArr.length(); i++){
JSONObject item = jsonArr.getJSONObject(i);
String postid = item.getString(TAG_POSTID);
String postsubject = item.getString(TAG_POSTSUBJECT);
String posttext = item.getString(TAG_POSTTEXT);
// tmp hashmap for single contact
HashMap < String, String > contact = new HashMap < String, String > ();
// adding each child node to HashMap key => value
contact.put(TAG_POSTID, postid);
contact.put(TAG_POSTSUBJECT, postsubject);
contact.put(TAG_POSTTEXT, posttext);
// adding contact to contact list
NewsList.add(contact);
}

'for' statement does not loop (contact application)

I am trying to send the numbers of my contacts to the server to check if these numbers are contained in my database. All numbers contained in database and in the address list of the phone finally should be displayed in a listview.
While using the for each loop ('for (String phoneNumberString : aa)') I get this warning: 'for' statement does not loop...
How can I solve this problem?
public class AllUserActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
// url to get all users list
private static String url_all_user = "http://.../.../.../get_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USER = "user";
private static final String TAG_PHONE = "phone";
private static final String TAG_UID = "uid";
private static final String TAG_USERNAME = "username";
String phoneNumber;
ArrayList<String> aa= new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_user);
// Hashmap for ListView
usersList = new ArrayList<HashMap<String, String>>();
// Loading users in Background Thread
new LoadAllUsers().execute();
getNumber(this.getContentResolver());
}
// get all numbers of contacts
public void getNumber(ContentResolver cr)
{
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
// use the cursor to access the contacts
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneNumberString = phoneNumber.replaceAll("\\D+","");
// get phone number
System.out.println(".................."+phoneNumberString);
aa.add(phoneNumberString);
}
phones.close();// close cursor
}
class LoadAllUsers extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUserActivity.this);
pDialog.setMessage("Loading users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (String phoneNumberString : aa){
params.add(new BasicNameValuePair("phone[]", phoneNumberString));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", params);
// Check your log cat for JSON response
Log.d("All users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray users = json.getJSONArray(TAG_USER);
// looping through all contacts
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String uid = c.getString(TAG_UID);
String phone = c.getString(TAG_PHONE);
String username = c.getString(TAG_USERNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, uid);
map.put(TAG_PHONE, phone);
map.put(TAG_USERNAME, username);
// adding HashList to ArrayList
usersList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all users
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(
AllUserActivity.this, usersList,
R.layout.list_users, new String[] { TAG_PHONE,
TAG_USERNAME},
new int[] { R.id.phone, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}}
}
You have a return statement at the end of your for loop, meaning it will go through the first element and return from your doInBackground() call.

How to parse a json rss feed into an android widget

please i need help, am a rookie, how can i create a widget that get its feed from from a Json in android. Is there a helpful tutorial that can help with this or a source code i can look at. I have checked online for a suitable tutorail but i found none that can help directly. this is the json url feed i want to pass into my android widget:url
public class MinistryNews extends SherlockListActivity {
private ActionBarMenu abm;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://";
// JSON Node names
private static final String TAG_QUERY = "query";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
// private static final String TAG_CAT_CODE = "cat_code";
// private static final String TAG_STATUS = "status";
// private static final String TAG_CREATED_TIME = "created_time";
private static final String TAG_UPDATE_TIME = "update_time";
// private static final String TAG_AUTHOR_ID = "author_id";
// contacts JSONArray
JSONArray query = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> queryList;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ministry_news);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
abm = new ActionBarMenu(MinistryNews.this);
if (com.cepfmobileapp.org.service.InternetStatus.getInstance(this)
.isOnline(this)) {
// Toast t = Toast.makeText(this,"You are online!!!!",8000).show();
// Toast.makeText(getBaseContext(),"You are online",Toast.LENGTH_SHORT).show();
// Calling async task to get json
new GetQuery().execute();
} else {
// Toast.makeText(getBaseContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
// Toast t =
// Toast.makeText(this,"You are not online!!!!",8000).show();
// Log.v("Home",
// "############################You are not online!!!!");
AlertDialog NetAlert = new AlertDialog.Builder(MinistryNews.this)
.create();
NetAlert.setMessage("No Internet Connection Found! Please check your connection and try again!");
NetAlert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
// finish();
}
});
NetAlert.show();
}
queryList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.time))
.getText().toString();
String description = ((TextView) view
.findViewById(R.id.content)).getText().toString();
// String plain = Html.fromHtml(description).toString();
// description.replace(/<\/?[^>]+>/gi, '');
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleActivity.class);
in.putExtra(TAG_TITLE, name);
in.putExtra(TAG_UPDATE_TIME, cost);
in.putExtra(TAG_CONTENT, description);
startActivity(in);
}
});
// Calling async task to get json
// new GetQuery().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetQuery extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MinistryNews.this);
pDialog.setMessage("Please wait..Loading news");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
query = jsonObj.getJSONArray(TAG_QUERY);
// looping through All Contacts
for (int i = 0; i < query.length(); i++) {
JSONObject c = query.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String update_time = c.getString(TAG_UPDATE_TIME);
// String address = c.getString(TAG_ADDRESS);
// String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject(TAG_PHONE);
// String mobile = phone.getString(TAG_PHONE_MOBILE);
// String home = phone.getString(TAG_PHONE_HOME);
// String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_TITLE, title);
contact.put(TAG_CONTENT, content);
contact.put(TAG_UPDATE_TIME, update_time);
// contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
queryList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MinistryNews.this,
queryList, R.layout.list_item, new String[] { TAG_TITLE,
TAG_UPDATE_TIME, TAG_CONTENT }, new int[] {
R.id.title, R.id.time, R.id.content });
setListAdapter(adapter);
}
}
here is a nice tutorial for you to import json data http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944
if its hard for you still.i can suggest you one thing ,you can import your rss to any website and customize it there as you want it to be and post them as json data it will be easier to do i guess.
its a raugh test for geting json data only the method i think its a bit easier and detail u can return the values instead of showing them in a text from the textvw
public void getdata()
{
String result=null;
InputStream inputstream=null;
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www.hadid.aero/news_and_json");
HttpResponse response=httpclient.execute(httppost);
HttpEntity httpentity=response.getEntity();
inputstream= httpentity.getContent();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 1st exception");
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!= null)
{
sb.append(line +"\n");
}
inputstream.close();
result=sb.toString();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 2nd exception");
}
try{
String s="test :";
JSONArray jarray=new JSONArray(result);
for(int i=0; i<jarray.length();i++)
{
JSONObject json=jarray.getJSONObject(i);
s= s +"+json.getString("lastname")+"\n"+
"newsid&title : "+json.getString("id_news")+" "+json.getString("title")+"\n"+
"date :"+json.getString("date")+"\n"+
"description : "+json.getString("description");
}
resultview.setText(s);
}
catch(Exception ex)
{
this.resultview.setText(ex.getMessage()+"at 3rd exception");
}
Check out GSON library which will create Java object with JSON content and use this in Your widget

Loading image in ListView from Array ID Android

I currently have a ListAdapter set up that is passed information pulled from a MYSQL database via JSON. I'm trying to display an image I have stored in the drawable folder based on the ID of the product. e.g For Product 1 R.drawable.img1 is shown in and so on..
public class GetProducts extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSON jParser = new JSON();
Functions uf = new Functions();
ArrayList<HashMap<String, Object>> productsList;
// url to get all products list
private static String url_all_products = "http://jumpto.be/api/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_IMGURL = "image";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, Object>>();
new GetProductsFromDB().execute();
// Loading products in Background Thread
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
/*lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
OrderBuild.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});*/
}
class GetProductsFromDB extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(GetProducts.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url_all_products, params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String ImgUrl = c.getString(TAG_PID);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
String imageLink = "R.drawable.img"+id;
map.put(TAG_IMGURL, imageLink);
// adding HashList to ArrayList
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
GetProducts.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_IMGURL},
new int[] { R.id.pid, R.id.name, R.id.img });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The current code I have just tells me it cannot find the directory. I have looked at URI but I can't figure out how I run them in the array / for loop.
Many Thanks
R.drawable.img1 is actually just an int value defined in your automatically generated R.java file, so you cannot use it directly.
However, you can retrieve your drawable using the following:
Resources resources = getResources();
int resId = resources.getIdentifier("img" + id, "drawable", getPackageName());
Drawable myDrawable = resources.getDrawable(resId);
Alternatively, you can place your image files in your assets directory and load them from there using the filename.
InputStream inputStream = getAssets().open("img" + id + ".jpg");
Drawable drawable = Drawable.createFromStream(inputStream, null);
mImageView.setImageDrawable(drawable);
You can set int value for drawable in hashmap. It is easy to bind in list adapter.
int imageLink = R.drawable.img1;
map.put(TAG_IMGURL, imageLink);

Categories

Resources