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!!
Related
I'm Very new to Java and android... I'm Try to create an ListView using BaseAdapter List being created successfully i have a EditText along with button for each list item but the real problem is when i put some data into editText Field and scroll down to change value of last list item then i go back to the top it refreshes the data to default value it doesn't contain the value which was entered by user before scrolling down
My BaseAdaper Code
class CoustomAdptr extends BaseAdapter{
String[] dates;
Integer[] inventory;
Integer totalrooms;
public CoustomAdptr(RoomFragment roomFragment, String[] dates, Integer[] inventory, Integer totalrooms) {
this.dates = dates;
this.inventory = inventory;
this.totalrooms = totalrooms;
}
#Override
public int getCount() {
return dates.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.inventory_listview,null);
TextView textView = (TextView) view.findViewById(R.id.roomListViewText);
final EditText editText = (EditText) view.findViewById(R.id.roomListInventory);
final Button updateButton = (Button) view.findViewById(R.id.roomListViewInventoryUpdateButton);
if(inventory[i] == 0){
editText.setBackgroundColor(getResources().getColor(R.color.SoldOut));
editText.setTextColor(getResources().getColor(R.color.SoldOutTextColor));
} else if(inventory[i] < totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.invetory));
editText.setTextColor(getResources().getColor(R.color.invetoryTextColor));
} else if(inventory[i] == totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.fullInventory));
editText.setTextColor(getResources().getColor(R.color.fullInventoryTextColor));
}
editText.setText(String.valueOf(inventory[i]));
textView.setText(dates[i]);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String name = editText.getText().toString();
//String name1 = dates[i];
//String name2 = getArguments().getString("room_id");
updateButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_done_black_24dp,0,0,0);
//updateButton.setBackgroundColor(getResources().getColor(R.color.SoldOut));
updateButton.setText("Updated");
updateButton.setEnabled(false);
Toast.makeText(getContext(), "Update Inventory Button Clicked", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is How Im Passing Data to My Adapter
JSONObject jObj = parentObject.getJSONObject("success");
JSONObject jObj2 = jObj.getJSONObject("data");
JSONArray arrajson = jObj2.getJSONArray("inventories");
String arrayCount = Integer.toString(arrajson.length());
String[] dates = new String[arrajson.length()];
Integer[] inventory = new Integer[arrajson.length()];
Integer totalrooms = new Integer(jObj2.getInt("total_room"));
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
dates[i] = jsonObject.getString("date");
inventory[i] = jsonObject.getInt("inventory");
}
CoustomAdptr coustomAdptr = new CoustomAdptr(RoomFragment.this,dates,inventory,totalrooms);
listView.setAdapter(coustomAdptr);
Help Needed :- I Want to retain same visible and Value of edittext as users enters on scroll up or down... i hope i was able to explain my problem clearly
After clicking a button, save it's state in a boolean array or somewhere else. And inside getView method, check if this button was previously clicked or not then setup your view accordingly.
It would be better if you create a model class for rows.
I would like to use Picasso library to download and show images that are in URL's inside JSON data from my server.
I've lost all hope, I saw something about custom adapter but to no avail.
I need help here.
Here's how I do stuff now to show data from json inside onPostExecute:
protected void onPostExecute(JSONObject objdanejson){
pDialog.dismiss();
try {
android = objdanejson.getJSONArray(TAG_ZAWARTOSC);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
final String akt_tytul = c.getString(TAG_TYTUL);
final String akt_skrot = c.getString(TAG_SKROT);
final String akt_tresc = c.getString(TAG_TRESC);
final String akt_id = c.getString(TAG_ID);
final String akt_IMG = c.getString(TAG_IMG);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TYTUL, akt_tytul);
map.put(TAG_SKROT, akt_skrot);
map.put(TAG_ID, akt_id);
map.put(TAG_TRESC, akt_tresc);
map.put("http://www.apirest.poligon.webimpuls.pl/"+TAG_IMG, akt_IMG);
oslist.add(map);
lista_aktualnosci = (ListView)findViewById(R.id.lista_aktualnosci);
final ListAdapter adapter = new SimpleAdapter(aktualnosci.this, oslist,
R.layout.aktualnosc_item,
new String[]{TAG_TYTUL, TAG_SKROT, TAG_IMG}, new int[]{R.id.aktTytul, R.id.aktSkrot, R.id.aktIMG});
lista_aktualnosci.setAdapter(adapter);
lista_aktualnosci.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(aktualnosci.this, "Kliknąłeś na " + oslist.get(+position).get("akt_tytul"),Toast.LENGTH_SHORT).show();
Intent czytaj = new Intent(aktualnosci.this, aktualnosc_czytaj.class);
czytaj.putExtra("tytuł",oslist.get(+position).get("akt_tytul"));
czytaj.putExtra("tresc",oslist.get(+position).get("akt_tresc"));
czytaj.putExtra("id",oslist.get(+position).get("akt_id"));
startActivity(czytaj);
}
});
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
EDIT:
How my custom controler looks:
oslist.add(map);
lista_aktualnosci = (ListView)findViewById(R.id.lista_aktualnosci);
/* final ListAdapter adapter = new SimpleAdapter(aktualnosci.this, oslist,
R.layout.aktualnosc_item,
new String[]{TAG_TYTUL, TAG_SKROT}, new int[]{R.id.aktTytul, R.id.aktSkrot});
*/
class ListAdapter extends ArrayAdapter<ClipData.Item> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ListAdapter(Context context, int resource, List<ClipData.Item> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.aktualnosc_item, null);
}
ClipData.Item p = getItem(position);
if (p != null) {
aktTytul = (TextView)findViewById(R.id.aktTytul);
aktSkrot = (TextView)findViewById(R.id.aktSkrot);
aktIMG = (ImageView)findViewById(R.id.aktIMG);
}
return v;
}
}
lista_aktualnosci.setAdapter(adapter);
Create a class that extends Simple Adapter or Base Adapter. In getView() the adapter will ask you to create a list item when this is needed. As you create the item you can use Picasso to display the image in whatever image view you've selected for this purpose.
That being said you should ditch ListView and use RecyclerView instead - for which you can find all the information you need here
Other stuff that may improve your code are things like Retrofit and Gson.
Does that help?
you can get your image from listview. You can this code your activity after set adapter then you can set your imageview.
for(int i = 0; i < this.listView.getChildCount(); i ++) {
View view = this.listView.getChildAt(i);
ImageView img= (ImageView)view.findViewById(R.id.yourimage);
//do something your image
}
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();
I am populating a ListView using remote JSON data in the following format:
{"nodes":[{"node":{"title":"Article#1","id":"4"}},{"node":{"title":"Article#2","id":"3"}}]}
My ListView is constructed with the following code:
ArrayList<String> articles = new ArrayList<String>();
try{
for(int i=0; i < data.length(); i++){
JSONObject dataObj = (JSONObject)data.get(i);
JSONObject record = dataObj.getJSONObject("node");
title = (record.getString("title"));
nid = (record.getString("nid"));
Log.i("FOUND", "title: " + title);
Log.i("FOUND", "nid: " + nid);
articles.add(title);
}
}catch(JSONException j){
Log.e("CHECK", "Attempting to read data returned from JSONReader: " + j.toString());
}
ListView articlesList = (ListView)findViewById(R.id.articlesList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ArticlesActivity.this, R.layout.article_item, R.id.articleItem, articles);
articlesList.setAdapter(adapter);
The entire process works and successfully lists my Article titles. But, I am trying to follow tutorials which will help me enable onSelectListeners on each list item. The ID element associated to each article title is all I need to remotely fetch the article content.
Is it possible to setup my ArrayList to contain both title and id data and use it to setup my dynamic OnSelectListener enabled ListView?
The proper way to do it is to create a class that will hold the article name and id and whatever info you need. In your custom adapter you setTag() method when you create the view.
Then in your onClickListener use getTag() method. Below I'll give you some code snipsetss hope they will help you.
public class Article{
private String name;
private String id;
public Article(String name, String id) {
this.name =name;
this.id = id;
}
public String getName() {
return name;
}
public String getID() {
return id;}
}
In you custom adapter class use setTag method when you create the view
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.group_list, null);
TextView title = (TextView) v.findViewById(R.id.group_title);
...//rest of my code
Article article = getItem(position);
title.setText(article.getName());
title.setTag(article);
v.setTag(article);
return v;
}
In your click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Article article= (Article ) view.getTag();
String articleID= article.getID();
}
}
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.