How can display the selected item first in spinner list?
Assume Rainy was retrieved from MySQL and now it should display the Rainy item first. How do I achieve this ?
Spinner Weather;
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String weather = c.getString(Config.TAG_WEATHER);
RetrieveWeather(weather);
// what should add here
} catch (JSONException e) {
e.printStackTrace();
}
}
public void RetrieveWeather(String a)
{
String[] arr = new String[]{"Sunny","Cloudy","Rainy","Thunderstorm"};
List<String> list = new ArrayList<String>();
String weather = a;
list.add(weather);
for(String s:arr){
if(!list.contains(s)){
list.add(s);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Weather.setAdapter(adapter);
}
Try the following:
Spinner Weather;
String weather;
int pos = 0;
String[] arr = new String[]{"Sunny","Cloudy","Rainy","Thunderstorm"};
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
weather = c.getString(Config.TAG_WEATHER);
RetrieveWeather(weather);
// what should add here
Weather.setSelection(pos);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void RetrieveWeather(String a)
{
List<String> list = new ArrayList<String>();
String weather = a;
list.add(weather);
for(String s:arr){
if(!list.contains(s)){
list.add(s);
}
}
for(int i=0;i<list.size();i++)
{
if(weather.equals(list.get(i)))
{
pos = i;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Weather.setAdapter(adapter);
}
Related
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 :
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) {
}
});
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");
}
How do i pass from a listview when clicked to another listview in the next activity? I retrieved my data in my database, i am trying to filter the selection by their ID and show everything from the same id when i click an item from my listview.
Here is my onclick listview in my first activity
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent (this, Sample.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String s_id = map.get(Config.TAG_s_id).toString();
String s_name = map.get(Config.TAG_s_name).toString();
String s_gender = map.get(Config.TAG_s_gender).toString();
String teamone = map.get(Config.TAG_teamone).toString();
String teamonepts = map.get(Config.TAG_teamonepts).toString();
String teamtwo = map.get(Config.TAG_teamtwo).toString();
String teamtwopts = map.get(Config.TAG_teamtwopts).toString();
intent.putExtra(Config.S_id,s_id);
intent.putExtra(Config.S_name,s_name);
intent.putExtra(Config.S_gender,s_gender);
intent.putExtra(Config.Teamone,teamone);
intent.putExtra(Config.Teamonepts,teamonepts);
intent.putExtra(Config.Teamtwo,teamtwo);
intent.putExtra(Config.Teamtwopts,teamtwopts);
startActivity(intent);
}
Here is my second activity
editTextId = (EditText) findViewById(R.id.editTextId);
title1ID = (TextView) findViewById(R.id.s_genderID);
contentID = (TextView) findViewById(R.id.s_nameID);
dateID = (TextView) findViewById(R.id.teamone);
teamoneptsID = (TextView) findViewById(R.id.teamonepts);
teamtwoID = (TextView) findViewById(R.id.teamtwo);
teamtwoptsID = (TextView) findViewById(R.id.teamtwopts);
listview = (ListView) findViewById(R.id.listView);
Typeface font = Typeface.createFromAsset(getAssets(), "arial.ttf");
title1ID.setTypeface(font);
contentID.setTypeface(font);
dateID.setTypeface(font);
editTextId.setText(id);
title1ID.setText(titl);
contentID.setText(cont);
dateID.setText(date);
teamoneptsID.setText(teamonepts);
teamtwoID.setText(teamtwo);
teamtwoptsID.setText(teamtwopts);
getResult();
private void getResult() {
class GetResult extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
showResult(s);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_Sport1, id);
return s;
}
}
GetResult ge = new GetResult();
ge.execute();
}
private void showResult(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
JSONObject c = result.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showResult(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY2);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String teamone = jo.getString(Config.TAG_teamone);
String teamonepts = jo.getString(Config.TAG_teamonepts);
String teamtwo = jo.getString(Config.TAG_teamtwo);
String teamtwopts = jo.getString(Config.TAG_teamtwopts);
String s_name = jo.getString(Config.TAG_s_name);
String s_gender = jo.getString(Config.TAG_s_gender);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_teamone, teamone);
match.put(Config.TAG_teamonepts,teamonepts);
match.put(Config.TAG_teamtwo,teamtwo);
match.put(Config.TAG_teamtwopts,teamtwopts);
match.put(Config.TAG_s_name,s_name);
match.put(Config.TAG_s_gender,s_gender);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
Sample.this, list, R.layout.gamesadapterlayout,
new String[]{Config.TAG_teamone,Config.TAG_teamonepts, Config.TAG_teamtwo, Config.TAG_teamtwopts, Config.TAG_s_name, Config.TAG_s_gender},
new int[]{ R.id.team1, R.id.score1, R.id.team2, R.id.score2, R.id.Type, R.id.s_gender});
listview.setAdapter(adapter);
}
I am trying to put everything from my first activity into the next in a listview by taking all of the same id with the clicked item. What im getting instead is a textview of the same id with only 1 result and not in a listview.
Can someone help me please.
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();
}
}