How to dynamically bind multiple json values in a single spinner? - android

I have a json array which has bullet1 and bullet 2 values to be binded in a single spinner.
[{"id":7,"description":"Height dusting","is_active":true,"createdBy":1,"CreatedOn":"2018-02-20T19:48:16","ModifiedBy":null,"ModifiedOn":null,"Bullet1":"Done","Bullet2":"Not Done"},
{"id":8,"description":"Cobwebs removed","is_active":true,"createdBy":1,"CreatedOn":"2018-02-20T19:48:17","ModifiedBy":null,"ModifiedOn":null,"Bullet1":"Yes","Bullet2":"No"},
{"id":9,"description":"Side walls cleaned","is_active":true,"createdBy":1,"CreatedOn":"2018-02-20T19:48:17","ModifiedBy":null,"ModifiedOn":null,"Bullet1":"Yes","Bullet2":"No"}],"token":null,"ActionName":"GetQuestionnairesByLocation"}]
So now dynamically there are 3 spinners and according to that only 2 values should be seen in respective spinners.
First Spinner - Done, Not Done.
Second Spinner - Yes, No.
Third Spinner - Yes, No.
But the problem i am facing is every spinner is getting binded with 6 values.(Done, Not Done, Yes, No, Yes, No)
Code :
ArrayList<UserFormModel> arrayList = new ArrayList<>();
List<String> list = new ArrayList<>();
JSONArray jsonArray = jsonObject.getJSONArray("ResponseArray");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 =
jsonArray.getJSONObject(i);
UserFormModel userFormModel = new
UserFormModel();
userFormModel.setId(jsonObject1.getInt("id"));
userFormModel.setDescription
(jsonObject1.getString("description"));
list.add(jsonObject1.getString("Bullet1"));
list.add(jsonObject1.getString("Bullet2"));
userFormModel.setBulletsList(list);
arrayList.add(userFormModel);
}
UserFormsAdapter locationMasterAdapter = new
UserFormsAdapter(GetQuestions.this, arrayList);
listView.setAdapter(locationMasterAdapter);
locationMasterAdapter.notifyDataSetChanged();
Adapter class :
private ArrayList<UserFormModel> userFormModelArrayList;
Activity home;
public UserFormsAdapter(Activity home, ArrayList<UserFormModel>
userFormModelArrayList) {
this.home = home;
this.userFormModelArrayList = userFormModelArrayList;
}
#Override
public View getView(final int position, View convertView, ViewGroup
parent) {
View grid;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)
home.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.get_questions_row, null);
} else {
grid = (View) convertView;
}
final UserFormModel userFormModel =
userFormModelArrayList.get(position);
TextView textDesc = (TextView) grid.findViewById(R.id.textDesc);
Spinner spinner = (Spinner) grid.findViewById(R.id.chooseBullets);
String desc = userFormModel.getDescription();
textDesc.setText(desc);
CustomDropdownAdapter customDropdownAdapter = new
CustomDropdownAdapter(home, userFormModel.getBulletsList());
spinner.setAdapter(customDropdownAdapter);
return grid;
}
what is it that i need to do for my above solution to run??

this is beacuase you are initialize your List outside of for loop. try to initialize your list in for loop.
ArrayList<UserFormModel> arrayList = new ArrayList<>();
List<String> list;\\don't initialize the list here just declare the list.
JSONArray jsonArray = jsonObject.getJSONArray("ResponseArray");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 =
jsonArray.getJSONObject(i);
list = new ArrayList<>();\\try to initialize your list here.
UserFormModel userFormModel = new
UserFormModel();
userFormModel.setId(jsonObject1.getInt("id"));
userFormModel.setDescription
(jsonObject1.getString("description"));
list.add(jsonObject1.getString("Bullet1"));
list.add(jsonObject1.getString("Bullet2"));
userFormModel.setBulletsList(list);
arrayList.add(userFormModel);
}
UserFormsAdapter locationMasterAdapter = new
UserFormsAdapter(GetQuestions.this, arrayList);
listView.setAdapter(locationMasterAdapter);
locationMasterAdapter.notifyDataSetChanged();

Related

android listview spinner when scroll

I have a custom ListView with Spinner that fill with a ListArray.
It works fine without ListView Scroll
But when I add some items to my custom ListView and I select one item of first or second on my Spinner and I scroll down my ListView (until that row disappear) I see another Spinner on bottom items will selected (like the upper)
My selection kept but another Spinner on bottom ListView be select
My code is :
public class SoundListView extends ArrayAdapter<String>{
List<String> DataList;
private final Activity context;
private ViewGroup vg;
int startTimer, stopTimer,rPosition;
String fileTagName = "",externalTagFileName = "",tagFileName= "",fileName = "";
public SoundListView (Activity context, ArrayList arrSubject, ArrayList arrDurationSplit, ArrayList ids,ArrayList arrFileName,ArrayList arrDuration,ArrayList arrIdTag,ArrayList arrTagName,ArrayList arrMainId,ArrayList arrStartTime, ArrayList arrStopTime) {
super(context, R.layout.activity_list, arrSubject);
this.context = context;
this.arrSubject = arrSubject;
this.arrDurationSplit = arrDurationSplit;
this.arrIdTag = arrIdTag;
this.arrDuration = arrDuration;
this.arrTagName = arrTagName;
this.arrMainId = arrMainId;
this.arrStartTime = arrStartTime;
this.arrStopTime = arrStopTime;
this.arrFileName = arrFileName;
this.ids = ids;
}
private ArrayList arrSubject = new ArrayList();
private ArrayList arrDurationSplit = new ArrayList();
private ArrayList ids = new ArrayList();
private ArrayList arrIdTag = new ArrayList();
private ArrayList arrTagName = new ArrayList();
private ArrayList arrMainId = new ArrayList();
private ArrayList arrStartTime = new ArrayList();
private ArrayList arrStopTime = new ArrayList();
private ArrayList arrDuration = new ArrayList();
private ArrayList arrFileName = new ArrayList();
final private ArrayList<String> arrayTasPath = new ArrayList<String>();
static class ViewHolder {
ImageView imgPlaySound,imgShareList;
TextView txtCaption,txtDynamicTimer,txtDurationSplit,txtTotalTimer,txtHiden;
Spinner spTags;
SeekBar seekBar1;
LinearLayout linearSeek;
int position;
}
#Override
public View getView(final int position,View convertView, final ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
vg = parent;
final ArrayList arrTagNameTemp = new ArrayList();
final ArrayList arrStartTimeTemp = new ArrayList();
final ArrayList arrStopTimeTemp = new ArrayList();
arrTagNameTemp.add("all");
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview, null);
viewHolder = new ViewHolder();
viewHolder.position = position;
viewHolder.txtCaption = (TextView) convertView.findViewById(R.id.txtCaption);
viewHolder.txtDynamicTimer = (TextView) convertView.findViewById(R.id.txtDynamicTimer);
viewHolder.txtDurationSplit = (TextView) convertView.findViewById(R.id.txtTotalTimer);
viewHolder.imgPlaySound = (ImageView) convertView.findViewById(R.id.imgPlaySound);
viewHolder.imgShareList = (ImageView) convertView.findViewById(R.id.imgShareList);
viewHolder.linearSeek = (LinearLayout) convertView.findViewById(R.id.linearSeek);
viewHolder.spTags = (Spinner) convertView.findViewById(R.id.spTags);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, arrTagNameTemp);
viewHolder.spTags.setAdapter(adapter);
viewHolder.spTags.setSelection(0);
final int duration = Integer.valueOf(arrDuration.get(position).toString());
for(int i = 0; i < arrMainId.size(); i++)
{
if (Integer.valueOf(arrMainId.get(i).toString()) == Integer.valueOf(ids.get(position).toString()))
{
arrTagNameTemp.add(arrTagName.get(i));
arrStartTimeTemp.add(arrStartTime.get(i));
arrStopTimeTemp.add(arrStopTime.get(i));
}
}
//////////////////////////////////////////////////////////////////////////////
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txtCaption.setText(arrSubject.get(position).toString());
return convertView;
}
Can anybody help me?
First of all just tell me why are you using that much arraylists, can't you just use a single one with custom data type. In that single array all your values will be associated to each other and it will easy to manage them.
The solution for your issue that I can suggest is to create a single ArrayList with custom data type including all your values of all arraylists given above. And don not initialize your Array in Adapter. Initialize and add values where you are setting Adapter (In your Activity). you have to add a parameter in your main array let's say "selectedValue", by default it will be "all" but when user will select some value you will update the value of item on that specific position.
And then in your getView method you will check the value of "selectedValue" for each item, if it is equals to "all" then you will set it otherwise you will set the value of "selectedValue" to your spinner. Just keep one thing in mind you have to set a value to spinner of each item in both if and else clause.

Listview displaying only last item

I have written a code to display json items into listview , when i debug the code i can see the data properly , when i am setting the list to the listview i am only seeing the last item
Code i tried :
try {
foodintervallist.clear();
final String result = response.body().string();
JSONObject jsonObject = new JSONObject(result);
String data = jsonObject.getString("data");
JSONArray foodintervalarray = new JSONArray(data);
HashMap<String, String> menuMap =
new HashMap<String, String>();
for (int j = 0; j < foodintervalarray.length(); j++) {
String key1 = "";
JSONObject jsonObject1 =
foodintervalarray.getJSONObject(j);
final String food_interval =
jsonObject1.getString(FOOD_INTERVAL);
if (jsonObject1.isNull(ITEM_NAME)) {
item_name = "";
} else {
item_name = jsonObject1.getString(ITEM_NAME);
}
if (!menuMap.containsKey(food_interval)) {
menuMap.put(food_interval, item_name);
} else {
String key = menuMap.get(food_interval);
key1=key+","+item_name;
menuMap.put(food_interval, key1);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
foodintervallist.add(menuMap);
listViewAdapter = new ListViewAdapter(Diet_Order_Activity_New.this, foodintervallist);
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
}
});
}
My BaseAdapter class
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater)
activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.table_row, parent,
false);
resultp = fooditervallist.get(position);
txtFoodInterval = (TextView)
itemView.findViewById(R.id.foodInterval);
txtFoodItem = (TextView) itemView.findViewById(R.id.foodItems);
for (Map.Entry<String, String> entry : resultp.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
txtFoodInterval.setText(key);
Toast.makeText(activity, "" + key, Toast.LENGTH_LONG).show();
txtFoodItem.setText(value);
// do what you have to do here
// In your case, an other loop.
}
return itemView;
}
I am declaring the foodintervallist globally in my main activity class and also the listviewadapter i am initializing inside oncreate method
I am getting the data inside my arraylist , but i am able to display only the last item , what to do ?
Thanx
I would recommend to check your implementation of Adapter's getCount(). As it is not provided how it looks, I would looked there...
it should be like:
public int getCount (){ return fooditervallist.get(0).size() }
As you provide a list with only one item. Also I see there some issues in getView() :
fooditervallist.get(position); --> don't use position there, your list has always only one item therefore use 0 instead otherwise you'll get null pointer
your for loop is setting the txtFoodInterval and txtFoodItem with the all values in the Map.Set which might result in all list items having the same value ... instead of for loop you should use a "position" parameter here which is not possible with HashMap as order is not predicable. Use LinkedHashMap instead to have correct order and logic needs to be adjusted
Nevertheless I would implement it differently:
JSON parsing - I would create a new object model for holding the data
class FoodItem { int interval; String name; // getters and setters
here }
I would put these items in the list you put your map
In adapter you can then use this object quite easily like without any for loop like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater)
activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.table_row, parent, false);
FoodItem item = fooditervallist.get(position);
txtFoodInterval = (TextView) itemView.findViewById(R.id.foodInterval);
txtFoodItem = (TextView) itemView.findViewById(R.id.foodItems);
txtFoodInterval.setText(item.interval) ;
txtFoodItem.setText(item.name);
return itemView;
}
Also I would recommend to have a look on Retrofit library. It will make your life easier...
put your Hashmap inside the for loop. Because when you use globally the data will be overrided and you get only last item.
Put the below code outside the loop // set adapter outside the loop
listViewAdapter = new ListViewAdapter(Diet_Order_Activity_New.this,foodintervallist);
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();

Custom listview not displaying the right content

Hellow there i've made a custom adapted for my listview but i dont know the reason why its displaying it in this way:
Display
This is how i generate the list that i use on listview:
final ArrayList<String> list = db_query.get_marks();
final ArrayList<String> list_trim = db_query.get_trim();
final ArrayList<String> list_merged = new ArrayList<String>();
for (int i=0; list.size()>i; i++){
list_merged.add(list.get(i));
list_merged.add(list_trim.get(i));
}
String[] list_final = new String[list_merged.size()];
this.size = list.size();
list_merged.toArray(list_final);
ListAdapter adapter = new Custom_Adapter(this, list_final);
So what i should be displaying is : AB AB but its actually displaying AA BB
7 values in the image are A
1 values in the image are B
The custom view code:
LayoutInflater inflater = LayoutInflater.from(getContext());
View customView = inflater.inflate(R.layout.custom_row, parent, false);
TextView text1 = (TextView) customView.findViewById(R.id.textView4);
TextView text2 = (TextView) customView.findViewById(R.id.textView5);
text1.setText((String) getItem(position));
text2.setText((String) getItem(position));
return customView;
Hope you can help me
public Custom_Adapter(Context context, ArrayList<Model> list) {
super(context, R.layout.custom_row, list);
}
You're setting the same value twice
text1.setText((String) getItem(position));
text2.setText((String) getItem(position));
Make a model file Model.java:
public class Model {
public String a;
public String b;
}
Replace this code:
final ArrayList<String> list = db_query.get_marks();
final ArrayList<String> list_trim = db_query.get_trim();
final ArrayList<Model> list_merged = new ArrayList<Model>();
for (int i = 0; i < list.size(); i++){
Model model = new Model();
model.a = list.get(i);
model.b = list_trim.get(i);
list_merged.add(model);
}
ListAdapter adapter = new Custom_Adapter(this, list_final);
And finally this:
text1.setText((String) ((Model)getItem(position)).a);
text2.setText((String) ((Model)getItem(position)).b);
Change you adapter to accept the Model object.

Android : get the view position by a <key,value> pair

In my app application i have an API that parsing JSON updating 500 rows is the list view. In a row I have id,name,number and status. Through the pushnotification am getting an id out of the 500 and I want update the status of that id having row.
Am using getter/setter method here so if getting the view position i can update the row.
This is the way am parsing
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String phone = c.getString("phone");
String subDistributorStatus = c.getString("status");
String name = c.getString("firstName");
subDistributerId = c.getString("subDistributerId");
SubdistributorItem item = new SubdistributorItem();
item.setSubDistributorName(name);
item.setSubDistributorNumber(phone);
item.setSubDistributorStatus(subDistributorStatus);
item.setSubDistributorId(subDistributerId);
}
This is the way am updating single row
SubdistributorItem subdistributorItem = subdistributorItemList.get(Integer.parseInt(getFromPreference("Sub_position")));
String phone= subdistributorItem.getSubDistributorNumber();
String id= subdistributorItem.getSubDistributorId();
String status= subdistributorItem.getSubDistributorStat
Here am getting the position by clicking the view.
Now if i get one of the id in the row is there any chance to get the position in the view.
I tried HashMap.
**HashMap newmap = new HashMap(); // in global
newmap.put(subDistributerId,i); // in loop
Log.e("Tag ","hash map positon "+ newmap.get(43)); // in onResume**
But failed.
can any please help to get the position of the row ,if get id of the row.
You can use ArrayList along with the getter/setter class. You also have to extend the BaseAdapter class to get the string values of a particular position and map it to the view.
You can check the following example --
The below code will loop through the JSON and set the values using Setter methods and then it will add them to the ArrayList.
ArrayList<SubdistributorItem> listitem = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String phone = c.getString("phone");
String subDistributorStatus = c.getString("status");
String name = c.getString("firstName");
subDistributerId = c.getString("subDistributerId");
SubdistributorItem item = new SubdistributorItem();
item.setSubDistributorName(name);
item.setSubDistributorNumber(phone);
item.setSubDistributorStatus(subDistributorStatus);
item.setSubDistributorId(subDistributerId);
listitem.add(item);
}
Then extend the BaseAdapter class to get the individual position and the values associated with it.
public class MyBaseAdapter extends BaseAdapter {
public Context ba_context;
public ArrayList<SubdistributorItem> listitem = new ArrayList<>();
public LayoutInflater inflater;
ListRowItem currentlistitem;
public MyBaseAdapter(Context ma_context, ArrayList<SubdistributorItem> ma_listitem) {
super();
this.ba_context = ma_context;
this.listitem = ma_listitem;
inflater = (LayoutInflater) ba_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.listitem.size();
}
#Override
public Object getItem(int position) {
return this.listitem.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_item_layout, parent, false);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
currentlistitem = listitem.get(position);
String str_carrier = currentlistitem.getCarrier();
carrier.setText(str_carrier);
return vi;
}
}
Finally call this class and set the adapter in the listview somewhere in your code as per your requirement.
baseAdapter = new MyBaseAdapter(context,listitem);
listView.setAdapter(baseAdapter);
Hope this helps!!

Android add items to arraylist using custom class

I'm trying to add items to an arraylist using this class template:
public class Template {
public String username;
public String email;
}
Here's the whole code:
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<Template> arrayAdapter = new ArrayAdapter<Template>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
The problem is, instead of filling my listview with nice username and email strings, it's filling up with items like this:
com.android.ninjaarchives.
Template#40585690
I think somewhere along the line I have become lost, but I've been trying all sorts for ages now and getting nowhere. Can anyone point me in the right direction?
Thanks for any help.
Note: not really sure what's going on with the code; it doesn't appear to be pasting correctly.
Use below code, it can be a solution for you
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
String listItemString[] = new String[myJsonArray.length];
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItemString[i] = tem.username +" - " + tem.email; // u can change it according to ur need.
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItemString);
lv.setAdapter(arrayAdapter);
}
But better to write Custom adapter by extending BaseAdapter, and do listItem handling in getView method here is one simple tutorial
Take a class extending Base
private class CustomAdapter extends BaseAdapter
{
LayoutInflater inflater;
public CustomAdapter(Context context)
{
inflater = LayoutInflater.from(context);
}
public int getCount()
{
return listItems.size();
}
public Object getItem(int position)
{
return listItems.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(final int position, View convertView,ViewGroup parent)
{
//if(convertView==null)
//convertView = inflater.inflate(R.layout.listlayout, parent, false);
Template data = (Template) getItem(position);
TextView v=new TextView(context);
v.setText(data.name);
return v;
}
}
and set adapter to your listview
lv.setAdapter(new CustomAdapter(this));
In this case you have to use a custom adapter (that extends from ArrayAdapter) and override the getView method to display in a custom layout the username and the email.

Categories

Resources