How to set Assets json file data in two spinner + android? - 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) {
}
});

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 :

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

Display selected value in spinner first

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

Refreshing screen which uses json in android

I have a module in my application which uses json.
The json gets updated always.
Here i want to refresh the screen as new data arrives.
Is there any method for this ?
I want to refresh the screen as new data arrives or once in every 5 seconds or something(a fixed amount of time).How to do this ?
I simply used a local json file to test this.
I just need the code for refreshing.
This is my code for json parsing :
public class MainActivity extends Activity
{
String myjsonstring;
ArrayList<Data> web = new ArrayList<Data>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JsonParser();
// Try to parse JSON
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
}
final customtest1 adapter = new customtest1(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "Test.........", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void JsonParser()
{
// Reading text file from assets folder
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"main.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
myjsonstring = sb.toString();
}
}
Do this.
create a class
public class Data
{
String name ="";
String viewers ="";
public Data(String n,String v)
{
name = n;
viewers=v;
}
}
then in MainActivity create only single arraylist with type Data
ArrayList<Data> web = new ArrayList<Data>();
and then parse your json like
// Creating JSONObject from String
JSONObject jsonObjMain = new JSONObject(myjsonstring);
// Creating JSONArray from JSONObject
JSONArray jsonArray = jsonObjMain.getJSONArray("pgm");
// JSONArray has four JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
// Creating JSONObject from JSONArray
JSONObject jsonObj = jsonArray.getJSONObject(i);
// Getting data from individual JSONObject
Data data = new Data(jsonObj.getString("name") , jsonObj.getString("viewers"));
web.add(data);
now instead of passing two array list to your custom adapter , pass only single arraylist i.e web
customtest adapter = new customtest(MainActivity.this,R.layout.list_single,web);
ListView list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);
in your customtest class , inside getview when you will bind data, you will do
Data dt = web.get(position);
String name = dt.name;
String viewers = dt.viewers;
and then do what you were doing before.
and after all this, now ehnever you want to update your list simply call
adapter.notifyDataSetChanged();
your customtest class now will be like
public class customtest extends ArrayAdapter<Data>{
Context context;
int layoutResourceId;
ArrayList<Data> data = null;
public customList(Context context, int layoutResourceId, ArrayList<Data> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CustomHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CustomHolder();
holder.txtName = (TextView)row.findViewById(R.id.txtName); //this is id of textview where you want to set name
holder.txtViewers = (TextView)row.findViewById(R.id.txtViewers); //this is id of textview where you want to set viewers
row.setTag(holder);
}
else
{
holder = (CustomHolder)row.getTag();
}
Data dt = data.get(postition);
holder.txtName.setText(dt.name);
holder.txtViewers.setText(dt.viewers);
return row;
}
static class CustomHolder
{
TextView txtName;
TextView txtViewers;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
new Thread(){
public void run()
{
While(true)
{
Thread.sleep(3000);
jsonParse(); //this is your method for parsing json
}
}
}.start();

Displaying a string into a listview

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

Categories

Resources