Getting: Error parsing data when i get response from JSON - android

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.

Related

App with json and sqlite crashes if internet connection is not available

I am working on JSON data fetching and displaying but before that I store it in Sqlite.
After fetching from that Sqlite table, it works fine when internet is available but app automatically closed when internet connection is not available. I am using hash-map custom adapter to showing data in listview. I have created a fetchdata method from SqlHelper class
protected Void doInBackground(Void... params)
{
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
int state = NetworkUtilClass.checkInternetConenction(getActivity());
if (state == 1) {
// jsonobject = new JSONObject(str1);
jsonobject = JSONFunction.getJSONfromURL("url");
JSONObject collection = null;
try {
collection = jsonobject.getJSONObject("collection");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray response = null;
try {
response = collection.getJSONArray("response");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobject1 = null;
try {
jsonobject1 = (JSONObject) response.get(i);
noticeId = jsonobject1.getString("id").toString();
noticeTitle = jsonobject1.getString("title").toString();
noticeDescription = jsonobject1.getString("description").toString();
noticePublishedBy = jsonobject1.getString("publishedBy").toString();
noticeValidFrom = jsonobject1.getString("validFrom").toString();
noticeValidTo = jsonobject1.getString("validTo").toString();
Log.e(noticeId, "show");
Log.e(noticeTitle, "show");
Log.e(noticeDescription, "show");
//demo_database.insertData(noticeTitle,noticeDescription,noticePublishedBy,noticeValidFrom,noticeValidTo);
demo_database.insertNoticeData(noticeId,noticeTitle,noticeDescription, noticePublishedBy,
noticeValidFrom, noticeValidTo);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else{
onPostExecute(null);
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
// Locate the listview in listview_main.xml
getData();
demo_database.close();
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void getData() {
// TODO Auto-generated method stub
try {
arraylist = demo_database.fetchNoticeData();
} catch (Exception e) {
e.printStackTrace();
}
listview = (ListView) getActivity().findViewById(R.id.listview);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Toast.makeText(getActivity(), "ListView clicked", Toast.LENGTH_SHORT).show();
}
});
// Pass the results into ListViewAdapter.java
adapter = new NoticeListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
Actually the thing is that when you are trying to access the json through url when internet is not available so the json Array with name response get no items in that so it got Null and when you try to execute For loop in which you give the length of json array it would be crash because of null pointer exception..
Your App is Crashing on the for Loop Right?

ListView with loadmore button replacing the old data

I am developing android app in that i want to display json data in listview with load more button, but when i click load more button old data is replaceing by new one i want both and old and new data to be displayed.Lihstview should show all data whats wrong in the code below
public class Newjava extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
CustomAdapter1 adapter2;
CustomAdapter1 adapter;
ProgressDialog mProgressDialog;
ArrayList<FeedAddress> arraylist;
String url = "http://xxxx.vdv.com/api/fvn/page1";
String arraymovie = "all";
public String string;
ListView listView;
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
jsonobject = JSONfunctions.getJSONfromURL(url);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject.getJSONObject("appname");
jsonarray = jsonObject1.getJSONArray("kfnh");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.xxhbc.com/upload/dv/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");
// Adding Load More button to lisview at bottom
listView.addFooterView(btnLoadMore);
// Getting adapter
adapter = new CustomAdapter1(this, arraylist);
listView.setAdapter(adapter);
/**
* Listening to Load More button click event
* */
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
i += 1;
new DownloadJSON().execute();
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Newjava.this);
// Set progressdialog title
mProgressDialog.setTitle("APP Name");
mProgressDialog.setIcon(R.drawable.ic_launcher);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<FeedAddress>();
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
String URL = "http://zvzvs.vczx.com/api/v/page"
+ i;
System.out.println("new url " + URL);
jsonobject = JSONfunctions.getJSONfromURL(URL);
try {
// Locate the array name
JSONObject jsonObject1 = jsonobject
.getJSONObject("fvvzx");
jsonarray = jsonObject1.getJSONArray("allmovies");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject post = (JSONObject) jsonarray.getJSONObject(i);
FeedAddress map = new FeedAddress();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.setMovieName(post.getString("movieName"));
// map.setName(post.getString("movieActors"));
map.setMovieId(post.getString("movieId"));
String imageUrl = "http://www.vsv.com/upload/vc/thumbnail/"
+ post.getString("moviePhoto")
+ post.getString("moviePhotoExt");
map.setImageUrl(imageUrl);
System.out.println("ldhslhdljh " + imageUrl);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
int currentPosition = listView.getFirstVisiblePosition();
// Appending new data to menuItems ArrayList
adapter = new CustomAdapter1(Newjava.this, arraylist);
listView.setAdapter(adapter);
// Setting new scroll position
listView.setSelectionFromTop(currentPosition + 1, 0);
updateList(string);
}
}
public void updateList(final String string) {
// TODO Auto-generated method stub
listView.setVisibility(View.VISIBLE);
// mProgressDialog.dismiss();
listView.setAdapter(new CustomAdapter1(Newjava.this, arraylist));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(),"position[]" ,
// Toast.LENGTH_SHORT).show();
Object o = listView.getItemAtPosition(position);
FeedAddress newsData = (FeedAddress) o;
System.out.println("hgsh " + string);
System.out.println("next " + newsData.getMovieId());
Intent intent = new Intent(Newjava.this,
SingleMenuItemActivity.class);
intent.putExtra("feed", newsData.getMovieId());
intent.putExtra("actor", newsData.getName());
startActivity(intent);
}
});
}
}
It replaces data because you recreate adapter every time. You should create adapter once and then add to it more data, not recreate it.

Getting Index Position of ListView Clicked Item not getting String Value

I am trying to pass value of KEY_TITLE from one activity to another activity, using click on List Item the particular row title which i have clicked, in my case i am trying to pass value of this: static final String KEY_TITLE = "title"; from OldEventActivity to OldUploadActivity but always i am getting "index position like: 0, 1", not getting actual string for KEY_TITLE.
OldEventActivity.java:
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet(URL);
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Convert this response into a readable string
String jsonString = null;
try {
jsonString = StreamUtils.convertToString(response.getEntity()
.getContent());
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a JSON object that we can use from the String
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
itemsList.add(map);
}
return itemsList;
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new LazyAdapters(OldEventActivity.this, itemsList);
list.setAdapter(adapter);
// Show Item Title in Header
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Intent mViewCartIntent = new Intent(OldEventActivity.this, OldUploadActivity.class);
mViewCartIntent.putExtra("KEY", KEY_TITLE);
startActivity(mViewCartIntent);
}
});
}
}
}
OldUploadActivity.java:
public class OldUploadActivity extends Activity {
public static final String LOG_TAG = "OldUploadActivity";
private ListView lstView;
private Handler handler = new Handler();;
Bundle bundle;
String keytitle;
List <String> ImageList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploads);
bundle = getIntent().getExtras();
keytitle = bundle.getString("KEY");
/*** Get Images from SDCard ***/
ImageList = getSD();
Log.d(OldUploadActivity.LOG_TAG, "getSD() :::--- " + ImageList);
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
private List <String> getSD()
{
List <String> it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/PicsAngels/";
File f = new File (string + keytitle + "/");
Log.d(OldUploadActivity.LOG_TAG, "KEY_TITLE :::--- " + f);
File[] files = f.listFiles ();
Log.d(OldUploadActivity.LOG_TAG, "getListImages() :::--- " + files);
for (int i = 0; i <files.length; i++)
{
File file = files[i];
Log.d(Upload.LOG_TAG, "i<files.length() :::--- " + i);
Log.d("Count",file.getPath());
it.add (file.getPath());
}
Log.d(Upload.LOG_TAG, "List <String> it :::--- " + it);
return it;
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> map = itemsList.get(position);
Intent mViewCartIntent = new Intent(OldEventActivity.this, OldUploadActivity.class);
mViewCartIntent.putExtra("KEY", map.get(KEY_TITLE));
startActivity(mViewCartIntent);
}
});
try the above code and see that your OldUploadActivity.class is not empty.
Please do not use the static keyword better to send with intent like
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
String KEY_TITLE= lv1.getItemAtPosition(position).toString();
Intent mViewCartIntent = new Intent(OldEventActivity.this, OldUploadActivity.class);
mViewCartIntent.putExtra("KEY", KEY_TITLE)
startActivity(mViewCartIntent);
}
and get in otheractivty'
Bundle bundle=getIntent().getExtras();
String kettitle=bundle.getString("KEY")
The problem is that in this line:
File f = new File (string + OldEventActivity.KEY_TITLE + "/");
You are appending OldEventActivity.KEY_TITLE, which you can see is a static final String.
static final String KEY_TITLE = "title";
So basically, your f is looking at the path /mnt/sdcard/Pictures/MyPics/title/, as your code is telling it to do.
It looks like you are trying to send a different value, not the value of KEY_TITLE. Instead of sending the value (ie. "title"), use that as the KEY and send the real value. Ie, instead of
Intent mViewCartIntent = new Intent(OldEventActivity.this, OldUploadActivity.class);
mViewCartIntent.putExtra("KEY", KEY_TITLE);
startActivity(mViewCartIntent);
You should write something like:
Intent mViewCartIntent = new Intent(OldEventActivity.this, OldUploadActivity.class);
mViewCartIntent.putExtra(KEY_TITLE, "whatever title value you want to send here.");
startActivity(mViewCartIntent);
And then in your activity where you want to get the value, you simply access it via
String passedTitle = intent.getStringExtra(OldEventActivity.KEY_TITLE);

How to retrieve value from ArrayList in android

I am trying to retrieve values from a json api and displaying then in a listView. The listView contains 3 elements and I am also implementing onItemClickListner() and when an Item is clicked it will display a detailed view related to that item. I am using an ArrayList to store all the json values. Now I want to retrieve a value from that ArrayList so that the OnClickListner() will get that value and from that value the detailed view will be displayed..
I am using AsyncTask to retrieve all the json values
#Override
protected String doInBackground(String... DATA) {
if(rqst_type.equals("top5"))
{
String url = DATA[1];
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONfromUrl(url);
try
{
JSONArray top5 = json.getJSONArray(TAG_TOP5);
public static ArrayList<HashMap<String, String>> top5List = new ArrayList<HashMap<String, String>>();
top5List.clear();
for(int i=0; i<top5.length(); i++)
{
Log.v(TAG_LOG, "Value of i: "+String.valueOf(i));
JSONObject t = top5.getJSONObject(i);
course_id = t.getString(TAG_CRSID);
created_date = t.getString(TAG_CRTDATE);
golfcourse_name = t.getString(TAG_GLFCRSNAME);
facilities = t.getString(TAG_FCLTY);
holes = t.getString(TAG_HOLES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CRSID, course_id);
map.put(TAG_CRTDATE, created_date);
map.put(TAG_GLFCRSNAME, golfcourse_name);
map.put(TAG_FCLTY, facilities);
map.put(TAG_HOLES, holes);
top5List.add(map);
Log.v(LoadingScreen.TAG_LOG, "top5List: "+String.valueOf(top5List));
}
}
catch(JSONException e)
{
Log.v(TAG_LOG, String.valueOf(e));
}
}
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(rqst_type.equals("top5"))
{
Intent in = new Intent(context, MyTop5.class);
in.putExtra(TAG_CRSID, course_id);
in.putExtra(TAG_CRTDATE, created_date);
in.putExtra(TAG_GLFCRSNAME, golfcourse_name);
in.putExtra(TAG_FCLTY, facilities);
in.putExtra(TAG_HOLES, holes);
Log.v(TAG_LOG, "Valuse to MyTop5: "+course_id+" "+created_date+" "+golfcourse_name+" "+
facilities+" "+holes);
context.startActivity(in);
}
This is the file to where I am displaying the list and the onItenClickListner()..
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_top5);
Intent in = getIntent();
golfcourse_name = in.getStringExtra(TAG_GLFCRSNAME);
course_id = in.getStringExtra(TAG_CRSID);
created_date = in.getStringExtra(TAG_CRTDATE);
facilities = in.getStringExtra(TAG_FCLTY);
holes = in.getStringExtra(TAG_HOLES);
Log.v(LoadingScreen.TAG_LOG, "course id: "+String.valueOf(course_id));
ListAdapter adapter = new SimpleAdapter(this, LoadingScreen.top5List, R.layout.top5_list,
new String[] { TAG_GLFCRSNAME, TAG_CRSID, TAG_CRTDATE, TAG_FCLTY, TAG_HOLES },
new int[] { R.id.top_golfname, R.id.top_courseid, R.id.top_createdate, R.id.top_fclty, R.id.top_holes });
setListAdapter(adapter);
Log.v(LoadingScreen.TAG_LOG, "course id: "+String.valueOf(course_id));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String url = "http://mygogolfteetime.com/iphone/viewdeal/127";
new LoadingScreen(MyTop5.this).execute("view_detail", url);
}
});
}
In the given URL I want to change the 127 to the value which is stored in the top5List.
String url = "http://mygogolfteetime.com/iphone/viewdeal/127";
The value I am trying to find in the top5List is the value of "course_id"
Thanks in advance..
top5List.get(your position).get(your Key);
With this code you can find the value on which you want to change.

Android App: JSON array from web to listview

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...
}

Categories

Resources