I'm just trying to get a simple JSON array in the following format: ["Country1","Country2","Country3"] from the web and then use that array as a listview in my android app. I'm not stuck on how to make this JSON array, i'm just confused on how to get it into a listview in the app.
I have tried a few different tutorials, but none of them are using the same layout as such as mine.
My app is using a viewflipper, to keep a tabbased layout in view at all times throughout the app, therefore none of the tutorials seem to be working with my layout.
Any help is much appreciated.
EDIT:
Here's some code, yes i want to parse it from a web service and display it in a listview.
public class Activity extends TabActivity implements OnClickListener {
Button doSomething;
TabHost tabHost;
ViewFlipper flipper;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablayout_1);
doSomething = (Button) findViewById(R.id.btn_do_something);
doSomething.setOnClickListener(this);
flipper = (ViewFlipper) findViewById(R.id.layout_tab_one);
listview = (ListView) findViewById(R.id.listview);
#SuppressWarnings("unchecked")
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,fetchTwitterPublicTimeline());
//ListAdapter adapter = new SimpleAdapter(this, this.fetchTwitterPublicTimeline() , R.layout.main, new int[] { R.id.item_title, R.id.item_subtitle });
listview.setAdapter(adapter);
flipper.setOnClickListener(this);
String tabname1 = getString(R.string.tabexample_tab1);
String tabname2 = getString(R.string.tabexample_tab2);
String tabname3 = getString(R.string.tabexample_tab3);
String tabname4 = getString(R.string.tabexample_tab4);
tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setContent(R.id.layout_tab_one).setIndicator(tabname1));
tabHost.addTab(tabHost.newTabSpec("tab2").setContent(R.id.layout_tab_two).setIndicator(tabname2));
tabHost.addTab(tabHost.newTabSpec("tab3").setContent(R.id.layout_tab_three).setIndicator(tabname3));
tabHost.addTab(tabHost.newTabSpec("tab4").setContent(R.id.layout_tab_four).setIndicator(tabname4));
tabHost.setCurrentTab(0);
listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
flipper.showNext();
}});
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
UPDATE: I still can't get it working, any ideas what's wrong in the code below?
public class Activity extends TabActivity implements OnClickListener {
Button doSomething;
TabHost tabHost;
ViewFlipper flipper;
ListView listview;
HttpResponse re;
String json;
JSONObject j;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
//final String TAG = "MainActivity";
//final String URL = "JSON.php";
super.onCreate(savedInstanceState);
setContentView(R.layout.tablayout_1);
final String[] listItems = new String[] { };
/*========================================
// JSON object to hold the information, which is sent to the server
JSONObject jsonObjSend = new JSONObject();
try {
// Add key/value pairs
jsonObjSend.put("key_1", "value_1");
jsonObjSend.put("key_2", "value_2");
// Add a nested JSONObject (e.g. for header information)
JSONObject header = new JSONObject();
header.put("deviceType","Android"); // Device type
header.put("deviceVersion","2.0"); // Device OS version
header.put("language", "es-es"); // Language of the Android client
jsonObjSend.put("header", header);
// Output the JSON object we're sending to Logcat:
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = HTTPClient.SendHttpPost(URL, jsonObjSend);
String temp = jsonObjRecv.toString();
/*==============================================*/
doSomething = (Button) findViewById(R.id.btn_do_something);
doSomething.setOnClickListener(this);
flipper = (ViewFlipper) findViewById(R.id.layout_tab_one);
listview = (ListView) findViewById(R.id.listview);
/* try {
JSONArray array = jsonObjRecv.getJSONArray(""); //(JSONArray) new JSONTokener(json).nextValue();
String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
listview.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}*/
//#SuppressWarnings("unchecked")
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,fetchTwitterPublicTimeline());
//ListAdapter adapter = new SimpleAdapter(this, this.fetchTwitterPublicTimeline() , R.layout.main, new int[] { R.id.item_title, R.id.item_subtitle });
listview.setAdapter(adapter);
flipper.setOnClickListener(this);
String tabname1 = getString(R.string.tabexample_tab1);
String tabname2 = getString(R.string.tabexample_tab2);
String tabname3 = getString(R.string.tabexample_tab3);
String tabname4 = getString(R.string.tabexample_tab4);
tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setContent(R.id.layout_tab_one).setIndicator(tabname1));
tabHost.addTab(tabHost.newTabSpec("tab2").setContent(R.id.layout_tab_two).setIndicator(tabname2));
tabHost.addTab(tabHost.newTabSpec("tab3").setContent(R.id.layout_tab_three).setIndicator(tabname3));
tabHost.addTab(tabHost.newTabSpec("tab4").setContent(R.id.layout_tab_four).setIndicator(tabname4));
tabHost.setCurrentTab(0);
listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
flipper.showNext();
}});
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line = null;
//make sure youe String line is completely filled after that..
if (!line.equals(null) && !line.equals("") && line.startsWith("["))
{
JSONArray jArray = new JSONArray(line);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject jobj = jArray.getJSONObject(i);
// also make sure you get the value from the jsonObject using some key
// like, jobj.getString("country");
listItems.add(jobj.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
/* public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
//make sure youe String line is completely filled after that..
if (!line.equals(null) && !line.equals("") && line.startsWith("["))
{
JSONArray jArray = new JSONArray(line);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject jobj = jArray.getJSONObject(i);
// also make sure you get the value from the jsonObject using some key
// like, jobj.getString("country");
listItems.add(jobj.getString(""));
}
}
/* String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}*/
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Update, here are the values of jArray as reported by Logcat:
08-26 16:49:07.246: VERBOSE/app(472): jarray value: ["Country1","Country2","Country3"]
These are the correct values!
This works in a simple test app I just created...
ListView list = (ListView) findViewById(...);
String json = "[\"Country1\",\"Country2\",\"Country3\"]";
try {
JSONArray array = (JSONArray) new JSONTokener(json).nextValue();
String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}
Related
I just can't seem to get it to work, I have tried many different things, the parsing works fine and returns a list of titles in an arraylist and I can't get them to then view on the ListView. Here is the code;
/**
* Created by Matt on 4/21/2015.
*/
public class Discussion_Fragment extends Fragment {
View rootview;
ListView listView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.discussion_layout, container, false);
ArrayList<String> titles = new ArrayList<String>();
listView = (ListView) rootview.findViewById(R.id.listView1);
parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
for(int i=0;i<titles.size();i++){
titles.add(titles.get(i));
}
ArrayAdapter saAdapter = new ArrayAdapter(getActivity(), R.layout.discussion_layout, titles);
listView.setAdapter(saAdapter);
return rootview;
}
public static String getHTTP(String urlToRead) {
URL url;
HttpURLConnection conn;
BufferedReader rd;
String line;
String result = "";
boolean response = false;
while (!response)
{
try {
url = new URL(urlToRead);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
result += line;
}
rd.close();
response = true;
} catch (IOException e) {
e.printStackTrace();
try {
Thread.sleep(600);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static List<String> parse(String httpResponse)
{
ArrayList<String> titles = new ArrayList<String>();
try {
JSONObject obj = new JSONObject(httpResponse);
//JSONObject posts = obj.getJSONObject("kind");
JSONObject posts1 = obj.getJSONObject("data");
JSONArray posts2 = posts1.getJSONArray("children");
for (int i = 0; i < posts2.length(); i++) {
JSONObject test = posts2.getJSONObject(i);
JSONObject test1 = test.getJSONObject("data");
Object test2 = test1.get("title");
titles.add(test2.toString());
}
}
catch(Exception e) {
e.printStackTrace();
}
return titles;
}
}
You should do like
List<String> titles = parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
As parse(...) method return List<String>
replace this:
parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
for(int i=0;i<titles.size();i++){
titles.add(titles.get(i));
}
with this:
titles = parse(getHTTP("https://www.reddit.com/r/DotA2.json?limit=10"));
Move your getHTTP() in AsynTask as you are fetching data on main thread. Do it in background.
I am using the Facebook Graph API to request a list of Facebook profiles and return them in a ListView displaying both names and profile pictures. I have two EditText fields in my main acitivty to enter both first and second names. A button starts my ListViewActivity when clicked and the names are passed. The ListView inflates and the request is sent to Facebook and each row in the ListView is updated using a custom adapter.
The problem is, I suspect, a memory leak. It is very temperamental as in, it would work once or twice if I'm lucky and any other attempts to update the ListView wouldn't work, the activity would remain blank. It doesn't work for some more common names either.
Below is my ListViewActivity:
public class ListViewActivity extends Activity implements OnItemClickListener {
public String firstname, secondname;
URL imageURL;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
public static final String[] descriptions = new String[] {"Description"};
ListView listView;
List<RowItem> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
loadData();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.listview);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
public void loadData() {
Session session = Session.getActiveSession();
firstname = getIntent().getExtras().getString("firstname");
secondname = getIntent().getExtras().getString("secondname");
if(session==null){
session = Session.openActiveSessionFromCache(this);
} else if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("fields", "name, picture, url, id");
params.putString("limit", "10");
Request request = new Request(session, "search?q="+ firstname + "%20" + secondname + "&limit=10&type=user&fields=name,picture", params, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
JSONObject jsonObject = null;
JSONArray jArray = null;
imageURL = null;
try {
jsonObject = new JSONObject(response.getGraphObject().getInnerJSONObject().toString());
jArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject element = null;
element = jArray.getJSONObject(i);
imageURL = new URL("http://graph.facebook.com/"+ element.get("id") +"/picture?type=large");
names.add(element.getString("name").toString());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
bitmaps.add(BitmapFactory.decodeStream(imageURL.openConnection().getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
thread.join();
if (bitmaps.size() == jArray.length()) {
for (int j=0; j<jArray.length(); j++) {
RowItem item = new RowItem(bitmaps.get(j), names.get(j), descriptions[0]);
rowItems.add(item);
}
}
}
} catch (JSONException e) {
System.out.println("JSON EXCEPTION:"+ e);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Log.d("close", " ");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
Would appreciate it if someone could help spot a memory leak (if that is indeed the issue because i'm getting between 7 - 10% free) and advise whether there is a better way of implementing this? Thanks
EDIT: Just to clarify I'm updating the list by going back to the main activity to enter a new name in the edit text fields and clicking the button to start the list view again
Does scaling the images help any?
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
I added in those two lines at line 67
public class ListViewActivity extends Activity implements OnItemClickListener {
public String firstname, secondname;
URL imageURL;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
public static final String[] descriptions = new String[] {"Description"};
ListView listView;
List<RowItem> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
loadData();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.listview);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
public void loadData() {
Session session = Session.getActiveSession();
firstname = getIntent().getExtras().getString("firstname");
secondname = getIntent().getExtras().getString("secondname");
if(session==null){
session = Session.openActiveSessionFromCache(this);
} else if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("fields", "name, picture, url, id");
params.putString("limit", "10");
Request request = new Request(session, "search?q="+ firstname + "%20" + secondname + "&limit=10&type=user&fields=name,picture", params, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
JSONObject jsonObject = null;
JSONArray jArray = null;
imageURL = null;
try {
jsonObject = new JSONObject(response.getGraphObject().getInnerJSONObject().toString());
jArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject element = null;
element = jArray.getJSONObject(i);
imageURL = new URL("http://graph.facebook.com/"+ element.get("id") +"/picture?type=large");
names.add(element.getString("name").toString());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
bitmaps.add(BitmapFactory.decodeStream(imageURL.openConnection().getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
thread.join();
if (bitmaps.size() == jArray.length()) {
for (int j=0; j<jArray.length(); j++) {
RowItem item = new RowItem(bitmaps.get(j), names.get(j), descriptions[0]);
rowItems.add(item);
}
}
}
} catch (JSONException e) {
System.out.println("JSON EXCEPTION:"+ e);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Log.d("close", " ");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
I successfully parsed data from this website here. After writing a few codes, I get a string in which I would like to display into a ListView. Basically, I want to display the whole array from the website into a ListView.
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://ec2-54-213-155-95.us-west-2.compute.amazonaws.com/notices.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
try {
JSONObject jObject = new JSONObject(result);
JSONArray jsonArray = jObject.getJSONArray("notices");
for(int i = 0; i < jsonArray.length(); i++) {
String arrayString = jsonArray.getString(i);
Log.d("notices", arrayString);
ListView listView1 = (ListView) findViewById(R.id.listView1);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am thinking of using arrayAdapter but I am not to sure of how to use it!
First decide whether you want to store your data in ArrayList or the Database before showing it in ListView. For ArrayList to ListView you will need ArrayAdapter and from database to ListView you will need CursorAdapter.
In ArrayList if you only have only TextView then you can use Simple ArrayAdapter else if there are multiple TextViews or more components then go for Custom ArrayAdapter.
you can use SimpleArrayAdapter as follows :-
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++) {
String arrayString = jsonArray.getString(i);
Log.d("notices", arrayString);
list .add(arrayString);
}
// and after filling this array list you can set this adapter to you list as
ListView listView1 = (ListView) findViewById(R.id.listView1);
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listView1 .setAdapter(adapter)
If you want to show your data in listview then u can use following code:
private ArrayAdapter<String> mArrayAdapter;
ListView listView1 ;
// Initialize array adapter.
mArrayAdapter = new ArrayAdapter<String>(this, R.layout.array_layout);
listView1 = (ListView) findViewById(R.id.listView1);
// Rest of your code...
//
//
try {
JSONObject jObject = new JSONObject(result);
JSONArray jsonArray = jObject.getJSONArray("notices");
for(int i = 0; i < jsonArray.length(); i++) {
String arrayString = jsonArray.getString(i);
mArrayAdapter.add(arrayString) ;
Log.d("notices", arrayString);
}
listView1.setAdapter(mArrayAdapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
array_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
/>
Try to add the data using ArrayList<String> and StableArrayAdapter as below:
ListView listView1 = (ListView) findViewById(R.id.listView1);
JSONObject jObject = new JSONObject(result);
JSONArray jsonArray = jObject.getJSONArray("notices");
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length; ++i)
{
String arrayString = jsonArray.getString(i);
Log.d("notices", arrayString);
list.add(arrayString);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview1.setAdapter(adapter);
StableArrayAdapter class
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
You may have got the answer till now but still it may help others.
I did it this way and it works great.
I made an xml recco_list file with 4 text views in.
Declare these.
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
ListView list;
Getting into array
for(int i = 0; i < RECCO_ARRAY.length(); i++) {
try {
JSONObject recco = RECCO_ARRAY.getJSONObject(i);
JSONObject program = recco.getJSONObject("program");
JSONObject outlet = recco.getJSONObject("outlet");
String normalized_weight = recco.getString("normalized_weight");
String distance = recco.getString("distance");
HashMap<String, String> map = new HashMap<String, String>();
String program_name = program.getString("name");
String outlet_basics = outlet.getString("basics");
String outlet_name = new JSONObject(outlet_basics).getString("name");
map.put("program_name", program_name);
map.put("outlet_name", outlet_name);
map.put("normalized_weight", normalized_weight);
map.put("distance", distance);
oslist.add(map);
list= (ListView) rootView.findViewById(R.id.recco_list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.recco_list_view, new String[] {"program_name","outlet_name", "normalized_weight", "distance"},
new int[]{R.id.program_name,R.id.outlet_name, R.id.normalized_weight, R.id.distance});
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
im writing an app for a site which uses JSON API. Im trying to parse the JSON but i get:
Error parsing data org.json.JSONException: Value error of type
java.lang.String cannot be converted to JSONArray
This is due its a string, i've tried other methods but i can only get information from the first string, because each string has its own randomly generated "filename/id", you can take a look at the json output:
{"error":"","S8tf":{"infoToken":"wCfhXe","deleteToken":"gzHTfGcF","size":122484,"sha1":"8c4e2bbc0794d2bd4f901a36627e555c068a94e6","filename":"Screen_Shot_2013-07-02_at_3.52.23_PM.png"},"S29N":{"infoToken":"joRm6p","deleteToken":"IL5STLhq","size":129332,"sha1":"b4a03897121d0320b82059c36f7a10a8ef4c113d","filename":"Stockholmsyndromet.docx"}}
Im trying to get it to show both of the "objects" from the json string. How can i make a lopp for it to find all the items or simply make it list all the "objects" contained in the "error" identifier?
My Main Activity:
public class FilesActivity extends SherlockListActivity implements
OnClickListener {
private ProgressDialog mDialog;
ActionBar ABS;
TextView session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dblist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Files");
TextView txt = (TextView)findViewById(R.id.nodata);
/**String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = null;
try {
jObject = new JSONObject(s);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject menu = null;
try {
menu = jObject.getJSONObject("menu");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String,String> map = new HashMap<String,String>();
Iterator<String> iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = null;
try {
value = menu.getString(key);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map.put(key,value);
txt.setText(value);
} **/
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
#Override
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/files?session=" + PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
//session = (TextView)findViewById(R.id.textView1);
//session.setText(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String files = null;
try {
int id;
String name;
JSONArray array = new JSONArray("error");
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
//JSONArray shows = object.getJSONArray("");
/*String shows = object.getString("S*");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
//JSONObject e = shows.getJSONObject(i);
files = shows;
//map.put("video_location", "" + e.getString("video_location"));
//TextView txt = (TextView)findViewById(R.id.nodata);
//txt.setText(files);
mylist.add(map); *
}*/
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
new String[] { files, "video_location" }, new int[] { R.id.item_title,
R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
//Intent myIntent = new Intent(ListShowsController.this,
// TestVideoController.class);
//myIntent.putExtra("video_title", o.get("video_title"));
//myIntent.putExtra("video_channel", o.get("video_channel"));
//myIntent.putExtra("video_location", o.get("video_location"));
//startActivity(myIntent);
}
});
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
Any help is much appreciated!
You're trying to get the error field as a JSONArray. Its a string. You can't process a string as an array, it throws that exception. In fact, I don't see any arrays in there at all.
I would look into using a JSon library like Gson (https://code.google.com/p/google-gson/). You are able to deserialize collections, which is much easier than doing it yourself.
{
"user": {
"name": ["bineesh", "Administrator", "binu", "binu", "bijith", "prem"]
},
"email": ["bineesh256#gmail.com", "erpadmin#gmail.com", "binu245#gmail.com", "binu245#gmail.com", "bijith256#gmail.com", "toast#gmail.com"],
"phone": ["7293553814", "12345", "0", "0", "0", "9046567239"]
}
I can't parse this response:
Object(result);
// JSONObject jObject;
// jObject= new JSONObject(result);
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
System.out.println(jo.getString("name"));
}
How can I see this response in listview?
Sample code:
public class HomeActivity extends ListActivity {
/** Called when the activity is first created. */
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"http://twitter.com/statuses/public_timeline.json");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}
sample code :
public void parse(String s){
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject namejObj = jsonObject.getJSONObject("user");
JSONArray nameArray = namejObj.getJSONArray("name");
for(int i =0;i<nameArray.length();i++){
Log.i("System out","name : "+nameArray.getString(i).toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can use below method to parse JSON file
JSONObject obj = new JSONObject(result);
JSONObject objUser = obj.getJSONObject("user");
JSONArray arrUser = objUser.getJSONArray("name");
for(int i=0;i<arrUser.length();i++)
{
String name = arrUser.getString(i);
}
JSONArray arrEmail = objUser.getJSONArray("email");
for(int i=0;i<arrEmail.length();i++)
{
String email = arrEmail.getString(i);
}
JSONArray arrPhone = objUser.getJSONArray("phone");
for(int i=0;i<arrPhone.length();i++)
{
String phone = arrPhone.getString(i);
}