basically I have some data stories in an API in JSON format.
I have managed to get the data from the JSON, loop through the, put them into a TextView, add onClick() on the textView.
but I want to be able to use the optical button on the phone to scroll, so I been told I need a ListView()
So I put the text I want into an array and added the array to the listView
As the example shows below
But how do I add onClick for each Item and pass the ID (intStoryID)?????????
My Code Example
BufferedReader jsonBr = null;
ArrayList arrStoryList = null;
public void onCreate(Bundle savedInstancesState){
super.onCreate(savedInstancesState);
setContentView(R.layout.stories_main);
if(setTopStoryData()){
setStoriesArray();
buildPage();
}else{
// TODO add Error Handling
}
}
public boolean setTopStoryData(){
String strURL = "http://www.example.com/api/index.php?my=params";
JSONConn jsonConn = new JSONConn();
JSONConn.setURL(strURL);
if(jsonConn.setData()){
jsonBr = jsonConn.Br();
return true;
}else{
// my Error Handling
return false;
}
}
public void setStoriesArray(){
String line;
String strAddDate;
String strCurrentStatus;
String strStatusRead;
int intStoryID;
int intNumStories;
arrStoryList = new ArrayList();
JSONObject arrStories;
JSONObject arrAllStories;
JSONObject arrSingleStory;
try{
while((line = jsonBr.readLine()) != null){
arrStories = new JSONObject(line);
intNumStories = Integer.parseInt(arrStories.optString("NumStories"));
arrAllStories = arrStories.getJSONObject("StoryData");
if(intNumStories > 0){
for(int i = 0; i < intNumStories; i++){
arrSingleStory = arrAllStories.getJSONObject("Story"+i);
intStoryID = Integer.parseInt(arrSingleStory.getString("ID"));
strAddDate = arrSingleStory.getString("ADDEDDATE");
strCurrentStatus = arrSingleStory.getString("CURRENTSTATUS");
if(strCurrentStatus.equals("y")){
strStatusRead = "Online";
}else if(strCurrentStatus.equals("n")){
strStatusRead = "Offline";
}else{
strStatusRead = "Pending";
}
String strStoryText = strAddDate+" - " +strCurrentStatus;
arrStoryList.add(strStoryText));
} // end FOR loop
}
} //End while loop
} catch (IOException e) {
// TODO Auto-generated catch block
strDEBUG += "Error (2)";
} catch (JSONException e) {
// TODO Auto-generated catch block
strDEBUG += "Error (3) "+e.getLocalizedMessage()+"\n";
}
}
public void buildPage(){
if(this.arrStoryList != null){
ListView lv1 = (ListView)findViewById(R.id.listView1);
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,this.arrStoryList));
}
}
use onItemClickListener() to the list view to get click event on each item
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
// do whatever you want here
}
});
Related
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?
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();
}
}
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.
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);
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...
}