Displaying a string into a listview - android

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();
}
}

Related

How to grouping data by date display in listview (data based on parse json)?

I wanna grouping my data such as an schedule by date or week where i display in listview.
I hope the result like this :
here my activity to show the data based on json parse :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tampil_semua_pgw);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And here my custom adapter :

How to set Assets json file data in two spinner + android?

Json File:
{
"Iraq":["Baghdad","Karkh","Sulaymaniyah","Kirkuk","Erbil","Basra","Bahr","Tikrit","Najaf","Al Hillah","Mosul","Haji Hasan","Al `Amarah","Basere","Manawi","Hayat"],
"Lebanon":["Beirut","Zgharta","Bsalim","Halba","Ashrafiye","Sidon","Dik el Mehdi","Baalbek","Tripoli","Baabda","Adma","Hboub","Yanar","Dbaiye","Aaley","Broummana","Sarba","Chekka"]
}
I need to display country name in first spinner and city name in second spinner as per selected countries of spinner.
How to code it android?
My Code:
public class Search_for_room extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<CollegeList> world;
String value,key;
List<String> al;
ArrayAdapter<String> adapter;
HashMap<String, String> m_li = new HashMap<String, String>();
public ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
CustomAdapterStatus customAdapter;
Search_for_room activity = null;
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_for_room);
activity = this;
ArrayList<String> items=getCountries("countriesToCities.json");
spinner=(Spinner)findViewById(R.id.spCountry);
spinnerCity=(Spinner)findViewById(R.id.spCity);
}
private ArrayList<String> getCountries(String fileName){
JSONArray jsonArray=null;
ArrayList<String> cList=new ArrayList<String>();
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
JSONObject jsonObj = new JSONObject(json);
// JSONObject resultObject = jsonObj.getJSONObject("result");
System.out.print("======Key: "+jsonObj);
Iterator<String> stringIterator = jsonObj.keys();
while(stringIterator.hasNext()) {
key = stringIterator.next();
value = jsonObj.getString(key);
System.out.println("------------"+key);
m_li.put(key,value);
al = new ArrayList<String>(m_li.keySet());
final SpinnerModel sched = new SpinnerModel();
/******* Firstly take data in model object ******/
sched.setCountryName(value);
// sched.setImage(key);
sched.setStates(key);
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
Resources res = getResources();
customAdapter = new CustomAdapterStatus(activity, R.layout.spinner_item, CustomListViewValuesArr,res);
spinner.setAdapter(adapter);
}
}catch (JSONException ex){
ex.printStackTrace();
/*jsonArray=new JSONArray(json);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobj = jsonArray.getJSONObject(i);
System.out.pri
//cList.add(String.valueOf(jobj.keys()));
}
}*/
}catch (IOException e){
e.printStackTrace();
}
return cList;
}
}
try this code it can help you
try {
// load json from assets
JSONObject obj = new JSONObject(loadJSONFromAsset());
// than get your both json array
JSONArray IraqArray = obj.getJSONArray("Iraq");
JSONArray LebanonArray = obj.getJSONArray("Lebanon");
// declare your array to store json array value
String Iraq[] = new String[IraqArray.length()];
String Lebanon[] = new String[LebanonArray.length()];
//get json array of Iraq
for (int i = 0; i < IraqArray.length(); i++) {
Iraq[i] = IraqArray.getString(i);
}
//get json array of Lebanon
for (int i = 0; i < LebanonArray.length(); i++) {
Lebanon[i] = LebanonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
ask me in case of any query
add menu item in spinner
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/spinner"
android:title="Select Week"
app:actionViewClass="android.widget.Spinner"
android:textColor="#android:color/white"
android:textSize="11dp"
app:showAsAction="always" />
</menu>
add your json to array list
public void onPostExecute(String response) {
try {
list.clear();
MatchData vid = null;
Gson gson = new Gson();
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("items");
for (int i = 0; i < array.length(); i++) {
vid = gson.fromJson(array.getJSONObject(i).toString(), MatchData.class);
list.add(vid);
}
matchDataAdapter = new MatchDataAdapter(MainActivity.this, list);
mRecyclerView.setAdapter(matchDataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
finally set adapter to spinner
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
**ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lists);**
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getSelectedItem();
Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG).show();
week = Integer.parseInt(selected);
requestforinfo();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return true;
}
You had done everything correct uptil now. Just make my suggestion and you are good to go with long list of JSON data.
First make the JSON Response of file accessible to whole activity/fragment by declaring at top.
Added following function to retrieve cityList of particular country:
private ArrayList<String> getCityList(String countryName){
ArrayList<String> cityList = new ArrayList<>();
//Here jsonObj is the your JSON response from the file.
try {
JSONArray jArray =jsonObj.getJSONArray(countryName);
for(int i=0;i<jArray.length();i++){
cityList.add(jArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
return cityList;
}
Then add on spinnerItemSelected call the below function:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = ((SpinnerModel) parent.getSelectedItem()).getCountryName();
//For sake of your answer I had used String Array and ArrayAdapter. You can modify as you want.
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(YourActivity.this, R.layout.single_textview,getCityList(selected));
spinnerCity.setAdapter(cityAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Json array parsing always has null result in Android

How I can parse this json array?
{"1":
{"0":"3","id_disc":"3","1":"Дослідження і проектування компютерних систем","name":"Дослідження і проектування компютерних систем","2":"ДПКМС ","s_name":"ДПКМС "}
,"2":
{"0":"5","id_disc":"5","1":"Цивільний захист і охорона праці в галузі","name":"Цивільний захист і охорона праці в галузі","2":"ЦЗ і ОП","s_name":"ЦЗ і ОП"}
,"3":
{"0":"1","id_disc":"1","1":"Дослідження і проектування інтелектуальних систем (Лекція)","name":"Дослідження і проектування інтелектуальних систем (Лекція)","2":"ДіПІС","s_name":"ДіПІС"}
}
I was trying this method, but I always have null result.
String[] sA = new String[100];
try {
JSONArray cast = getDisc(paraaams).getJSONArray(" ");
for (int i=0; i<cast.length(); i++) {
JSONObject disc = cast.getJSONObject(i);
sA[i-1] = disc.getString("name");
}
}catch (JSONException e){}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
public JSONArray getDisc(Object params[]){
HTTPWorker httpWorker=new HTTPWorker();
JSONArray mjson =new JSONArray();
String s = httpWorker.doInBackground(params);
try {
mjson = new JSONArray(s);
Log.e("JSONinClass ",mjson.toString());
}catch (JSONException e){}
return mjson;
I think i try to parse it like json object, but i don't know how correct work with json arrays.
Thanks for help:)
my ListFragment:
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
String[] sA = new String[100];
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
int i =0;
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA[i]=name;
Log.e("value= ", name);
i+=1;
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
I cut it a bit, removed it is not important for the question :)
Try this for your Response to Parse
May Help you
try{
JSONObject jsonObject = new JSONObject(response);
List<String> keyList = getAllKeys(jsonObject);
for(String key : keyList){
JSONObject innerObject = jsonObject.getJSONObject(key);
List<String> innerKeyList = getAllKeys(innerObject);
for(String innerKey: innerKeyList){
System.out.println(innerObject.getString(innerKey));
}
}
}catch(Exception e){
e.printStackTrace();
}
This method will return keys
private List<String> getAllKeys(JSONObject jsonObject) throws JSONException{
List<String> keys = new ArrayList<String>();
Iterator<?> iterator = jsonObject.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
keys.add(key);
}
return keys;
}
try this:
please check below changes replace array to arraylist
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
ArrayList<String> sA = new ArrayList<>();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA.add(name);
Log.e("value= ", name);
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
Here is a tested code to parse json.
try {
JSONObject json = new JSONObject(json);
int jsonLength = json.length();
for(int i=1; i<=jsonLength; i++){
JSONObject jObject = json.getJSONObject(""+i);
String data = jObject.getString("0");
}
} catch (JSONException e) {
e.printStackTrace();
}
It is just a plain JSONObject not an JSONArray, so you have to cast it to a JSONObject first
JSONObject json = new JSONObject(jsonString);
To loop through it
for (Iterator<String> iter = json.keys(); iter.hasNext();) {
String key = iter.next();
JSONObject value = (JSONObject) json.getJSONObject(key);
String name = value.getString("name");
}

Refresh data in ListFragment

I want to get data from php, then show in listview. But I do not know not to tell the listview update the data I have got for php. I have try to use notifyDataSetChanged();, but I do know where should it put.
public class List_View extends ListFragment{
private String result;
private ListView listView;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items));
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
items.add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
You should collect all arrived data in other collection (other than used in list adapter) in separate thread and then replace the list colletion source and right after than you should call notifyDataSetChanged().
public class List_View extends ListFragment{
private String result;
private ListView listView;
protected List newData;
protected ArrayAdapter listAdapter;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter );
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
// a new collection to fill from response
newData = new ArrayList<String>();
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
//here you should create a corresponding object from JSON
// and add it to newData List
newData .add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
// here you will have a newData List filled so you should
// replace or add data from this List to ListView's used
items.add(newData);
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}

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