Items in listview not setting up using BaseAdapter and SimpleAdapter - android

I'm facing problem with setting up the items in ListView, I'm using an Async task for updating the items. Here is what I have done so far.
Async Task onPostExecute()
#Override
protected void onPostExecute(String result) {
notifyList = new ArrayList<HashMap<String, String>>();
try {
JSONObject rootObj = new JSONObject(result);
JSONObject jSearchData = rootObj.getJSONObject("notifications");
int maxlimit = 5;
for (int i = 0; i < maxlimit; i++) {
JSONObject jNotification0 = jSearchData.getJSONObject(""
+ i + "");
String text = jNotification0.getString("text");
String amount = jNotification0.getString("amount");
String state = jNotification0.getString("state");
System.out.println(text);
System.out.println(amount);
System.out.println(state);
HashMap<String, String> map = new HashMap<String, String>();
map.put("text", text);
map.put("amount", amount);
notifyList.add(map);
}
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is my CustomNotification class which extends BaseAdapter
public class CustomNotificationAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> notificationData = new ArrayList<HashMap<String, String>>();
public CustomNotificationAdapter(
ArrayList<HashMap<String, String>> notificationData) {
this.notificationData = notificationData;
}
#Override
public int getCount() {
return notificationData.size();
}
#Override
public Object getItem(int position) {
return notificationData.get(position).get("text").toString();
}
#Override
public long getItemId(int position) {
return notificationData.get(position).get("text").hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
LayoutInflater inflater = getLayoutInflater();
vi = inflater.inflate(R.layout.custom_notification_list, null);
TextView notificationText = (TextView) findViewById(R.id.notificationText);
TextView notificationAmount = (TextView) findViewById(R.id.notificationPoint);
notificationText
.setText(notificationData.get(position).get("text"));
notificationAmount.setText(notificationData.get(position).get(
"amount"));
return vi;
}
}
NotificationAdapter class which extends SimpleAdapter
public class NotificationAdapter extends SimpleAdapter {
List<Map<String, String>> cur_list = new ArrayList<Map<String, String>>();
public NotificationAdapter(Context context,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(context, data, resource, from, to);
}
}
I'm able to get all the data from JSONResponse but I'm not able to show it on the list. What am I missing?
Any kind of help will be appreciated.

Try replacing this:
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
with this:
notification_adapter = new CustomNotificationAdapter(notifyList);
notification_list.setAdapter(notification_adapter);
This will set the adapter to the new JSON data even if notification_adapter was previously null.

Call notification_adapter.notifyDataSetChanged() after updating your adapter's data or remove the if (notification_adapter != null) {if you want it easy and bad.
to update your data:
public void updateData(ArrayList<HashMap<String, String> notificationData){
this.notificationData = notificationData;
this.notifyDataSetChanged();
}
Inside your adapter, and call it like: notification_adapter.updateData(notifyList);

Related

Show the Elements from ArrayList of map ,in list form in Android

I have a A data stored in ArrayList< HashMap< String, String> > retrieved from JSON
in the form (i.e.)
[{price: =1685 name: =Monographie Der Gattung Pezomachus (Grv.) by Arnold F. Rster}]
And I need to show the all map elements into list form in Android.
I've tried many ways but I'm unable to do it .
Also help me to know about the layouts to use in it
EDITED:
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(myarr_list);
setListAdapter(adapter);
And in the MySimpleArrayAdapter Class, in Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
LayoutInflator inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
The control does not proceed after this,
MySimpleArrayAdapter Class
public class MySimpleArrayAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> ProductList = new ArrayList<HashMap<String, String>>();
LayoutInflater inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
this.ProductList = pl;
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
if (convertView == null) {
myview = inflater.inflate(R.layout.show_search_result, null);
}
TextView price = (TextView) myview.findViewById(R.id.price);
TextView name = (TextView) myview.findViewById(R.id.name);
HashMap<String, String> pl = new HashMap<String, String>();
pl = ProductList.get(position);
//Setting
price.setText(pl.get("price"));
name.setText(pl.get("name"));
return myview;
}
}
I am editing here a onPostExecute class from SearchResultsTask extended by AsyncTask
protected void onPostExecute(JSONObject json) {
if (json != null && json.length() > 0) {
try {
JSONArray json_results = (JSONArray)(json.get("results"));
String parsedResult = "";
System.out.println("-> Size ="+ json_results.length());
for(int i = 0; i < json_results.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_i = json_results.getJSONObject(i);
map.put("name: ",json_i.getString("name") + "\n");
map.put("price: ",json_i.getString("price") + "\n");
arr_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println("-> Size =====arr_llist ="+ arr_list.size());
// CustomListAdapter adapter = new CustomListAdapter (arr_list);
//final StableArrayAdapter adapter = new StableArrayAdapter(this, R.id.result, arr_list);
// listview.setAdapter(adapter);
MyListActivity obj1 = new MyListActivity();
Bundle icicle = null;
obj1.onCreate(icicle);
}
public class MyListActivity extends Activity {
public void onCreate(Bundle icicle) {
// System.out.println("In my list Activity");
// super.onCreate(icicle);
//populate list
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this,arr_list);
// System.out.println("in 2");
adapter.getView(0, listview, listview);
listview.setAdapter(adapter);
}
}
#Override
public int getCount() {
return ProductList.size() ;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl, Context c) {
this.ProductList = pl;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
getSystemService() is method of context, you are calling it on instance of adapter.

android- Dynamically add more items to custom gridview json

I have a gridview on my activity ,I get data via json and add them to my adapter .
this is the code:
gridView = (GridView) findViewById(R.id.gridView);
contactList = new ArrayList<HashMap<String, String>>();
new GetContacts().execute();
private class GetContacts extends AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url+page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
if(contacts.length()<20)
loadmore=false;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("url", new String(c.getString("url").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("text", new String(c.getString("text").getBytes("ISO-8859-1"), "UTF-8"));
dataC.add(contact);
}
} catch (JSONException e) {
goterr=true;
} catch (UnsupportedEncodingException e) {
goterr=true;
}
} else {
Log.v("this","mi;;");
goterr=true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if(!isCancelled() && goterr==false){
if(ladap==null){
ladap=new ListAdapter(FistActiivty.this,result);
gridView.setAdapter(ladap);
}else{
ladap.addAll(result);
}
}else{
MyToast.makeText(FistActiivty.this, DariGlyphUtils.reshapeText(getResources().getString(R.string.problemload)));
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String,String>> list;
public ListAdapter(Activity activity, ArrayList<HashMap<String, String>>list ) {
super();
this.activity=FistActiivty.this;
this.list=list;
}
public HashMap<String, String> geting(int position) {
return list.get(position);
}
public void addAll(ArrayList<HashMap<String, String>> result) {
if(this.list==null){
//this.list = new ArrayList<HashMap<String, String>>();
this.list =result;
}else{
this.list.addAll(result);
}
//list.addAll(result);
notifyDataSetChanged();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView Message;
ImageView img ;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_grid, null);
holder = new ViewHolder();
holder.Message = (TextView) convertView.findViewById(R.id.text);
holder.Message.setTypeface(typeface);
holder.img=(ImageView)convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = list.get(position);
String text = item.get("text");
Log.v("this","11"+ text);
holder.Message.setText(text);
String imgurl = item.get("url");
if(imgurl.length()>5)
imageLoader.displayImage(imgurl, holder.img,options, imageListener);
else
holder.img.setImageDrawable(getResources().getDrawable(R.drawable.noimage));
return convertView;
}
ok , at this step, I get data from internet via json , post it to ListAdapter and add them to my gridview and no problem .
in listview ,we can add ask for more data when we reach at the bottom of listview , But how can I call function to add more items whwen I reach at the end of gridview ?
The best way to implement this is via using PullToRefreshLibrary here. Import that library to your workspace and implement setOnRefreshListener with onPullUpToRefresh. This will indicate the end of the list. You can set a request to the server to get more data to view when the end of the list is reached.
On the server, you can implement pagination to load the next set of data every time you reach the end of the list.
I hope this will help you.

android-notifyDataSetChanged doesn't work on BaseAdapter

i've a listview on my activity , when I reach the end of listview , it calls async and it getting new data using json .
this is the async and baseAdaper codes :
ListAdapter ladap;
private class GetContacts AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected Void doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url + page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8");
String dates = new String(c.getString("dates").getBytes("ISO-8859-1"), "UTF-8");
String price = new String(c.getString("gheymat").getBytes("ISO-8859-1"), "UTF-8");
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", id);
contact.put("dates", dates);
contact.put("price", price);
dataC.add(contact);
}
}
} catch (JSONException e) {
goterr = true;
} catch (UnsupportedEncodingException e) {
goterr = true;
}
} else {
goterr = true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if (!isCancelled() && goterr == false) {
if(ladap==null){
ladap=new ListAdapter(MainActivity.this,result);
lv.setAdapter(ladap);
}else{
ladap.addAll(result);
ladap.notifyDataSetChanged();
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String, String>> list;
public ListAdapter(Activity activity,ArrayList<HashMap<String, String>> list) {
super();
this.activity = (Activity) activity;
this.list = list;
}
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
public int getCount() {
return contactList.size();
}
public Object getItem(int position) {
return contactList.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView title,price;
ImageView img ;
//RelativeLayout rl;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.price = (TextView) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = contactList.get(position);
holder.price.setText(item.get("price"));
return convertView;
}
}
I logged here , when I reach the end of listView , it calls addAll and it returns new 30 items buy it doesn't added to listview , I don't know why .
First of all you have already notify your list view when you call addAll() so this code no longer required please remove from your code :
ladap.notifyDataSetChanged();
Add new data to list view data holder instead of assign new data to list view data holder :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
Replace with :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
if(list==null){
list = new ArrayList<HashMap<String, String>>();
}
list.addAll(result)
notifyDataSetChanged();
}
Try to change this :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
To :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
for(int i = 0;i < result.size(); i++)
list.add(result.get(i));
//notifyDataSetChanged(); //no need to call again here
}
The point is, i think this.list = result; will delete the old items before adding a new item.

How to use CustomAdapter with ListView from XML Async Task

I achieved populate a ListView using StringBuilder from a Internet XML Source.
With this code the listView is populated with only one String but I want populate the listview by elements: getIdLine and getTimeLeft (With CustomAdapter) for customize the layout of the listView items in separated Strings.
How to achieve this?
EDITED CODE
FragmentActivity.class
private ListView listViewEMT;
private ArrayList<HashMap<String, String>> yourList;
... AsyncTask
protected void onPostExecute(String string) {
super.onPostExecute(string);
CustomAdapter adapter = new CustomAdapter(getActivity(), yourList);
listViewEMT.setAdapter(adapter);
this.progressDialog.dismiss();
}
/** RSS HANDLER CLASS */
class RSSHandler extends DefaultHandler {
StringBuffer chars;
private Arrival currentArrival;
RSSHandler() {
this.currentArrival = new Arrival();
this.chars = new StringBuffer();
}
public void characters(char[] arrc, int n, int n2) {
this.chars.append(new String(arrc, n, n2));
}
public void endElement(String string, String string2, String string3) throws SAXException {
super.endElement(string, string2, string3);
if ((string2.equalsIgnoreCase("idStop")) && (this.currentArrival.getIdStop() == null)) {
this.currentArrival.setIdStop(this.chars.toString());
}
if ((string2.equalsIgnoreCase("idLine")) && (this.currentArrival.getIdLinea() == null)) {
this.currentArrival.setIdLinea(this.chars.toString());
}
if ((string2.equalsIgnoreCase("TimeLeftBus")) && (this.currentArrival.getTimeLeft() == 0)) {
int n = Integer.valueOf((String)(this.chars.toString()));
this.currentArrival.setTimeLeft(n);
}
if (!(string2.equalsIgnoreCase("Arrive"))) return;
yourList.add((HashMap<String, String>)(currentArrival.getMap()));
this.currentArrival = new Arrival();
}
public void startElement(String string, String string2, String string3, org.xml.sax.Attributes attributes) throws SAXException {
super.startElement(string, string2, string3, attributes);
this.chars = new StringBuffer();
string2.equalsIgnoreCase("Arrive");
}
}
Arrival.class
...getters and setters
public HashMap<String, String> getMap() {
HashMap<String, String> map;
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("KEY1", idLinea);
map.put("KEY2", String.valueOf(timeLeft));
return map;
}
CustomAdapter.class Thanks to Nabin
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
private List<String> listString;
public CustomAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.emt_item, null);
TextView tv1 = (TextView) vi.findViewById(R.id.itemLine);
TextView tv2 = (TextView) vi.findViewById(R.id.itemTime);
HashMap<String, String> map;
map = data.get(position);
tv1.setText(map.get("KEY1"));
tv2.setText(map.get("KEY2"));
return vi;
}
}
Create a custom adapter as following:
public class ArrayAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
private List<String> listString;
public ArrayAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//your getView method here
}
GetView Method
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.custom, null);
TextView tv1 = (TextView) vi.findViewById(R.id.tvone);
TextView tv2 = (TextView) vi.findViewById(R.id.tvtwo);
HashMap<String, String> map = new HashMap<String, String>();
map = data.get(position);
tv1.setText(map.get("KEY1"));
tv2.setText(map.get("KEY2"));
return vi;
}
Make array list as:
ArrayList<HashMap<String, String>> yourList;
And fill yourList as
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("KEY1", value1);
map.put("KEY2", value2);
yourList.add(map);
And while making object of the custom adapter
CustomAdapter adapter = new CustomAdapter(YourActivity.this, yourList);
list.setAdapter(adapter);
For list you can do
list = (ListView) getView().findViewById(android.R.id.list);

not able to populate list from json android

I am trying to populate list object from an api.
This is one method jsonresult.
protected void onPostExecute(String result)
{
JSONArray con;
//String tag_name="tests";
//String tag_id="ID";
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try
{
JSONObject jsonObject = new JSONObject(result);
if("success".equals(jsonObject.getString("result")))
{ Toast.makeText(getBaseContext(),jsonObject.getString("tests"),Toast.LENGTH_SHORT).show();
//String nKey=jsonObject.getString("nKey");
// switchActivity(nKey);
//Toast.makeText(getBaseContext(),nKey,Toast.LENGTH_SHORT).show();
try{
con = jsonObject.getJSONArray("tests");
for(int i = 0; i < con.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = con.getJSONObject(i);
map.put("EXAM", "" + c.getString("exam"));
map.put("ID", "" + c.getString("id"));
mylist.add(map);
}}catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
else
{
Toast.makeText(getBaseContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
giving error at
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });
ERROR:
The constructor SimpleAdapter(examlist.ReadJSONResult, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined
Create a Custom Adpater for inflating the ListView.
public class MyListAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> data;
Activity a;
private static LayoutInflater inflater=null;
public MyListAdapter(Activity act, ArrayList<HashMap<String, String>> UserAndMessage)
{
data = UserAndMessage;
inflater = (LayoutInflater)act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
a = act;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup parent) {
View vi = convertview;
if(null == vi)
{
vi = inflater.inflate(R.layout.listitem, null);
TextView ID= (TextView) vi.findViewById(R.id.ID);
TextView Exam= (TextView) vi.findViewById(R.id.exam);
HashMap<String,String> item = data.get(position);
ID.setText(item.get("name"));
EXAM.setText(item.get("message"));
}
return vi;
}
}
from onPostExecute() set ListView's Adapter as below:
myList = (ListView) findViewById(R.id.listView1);
myList.setAdapter(new MyListAdapter(this, UserAndMessage));
It's because there's not such constructor for ListAdapter as you use it. As a Context (first parameter) you're passing examlist.ReadJSONResult and you should pass a Context of a Activity in which the View which uses this ListAdapter is placed.
If the class in which you're setting ListAdapter is not an Activity, then you should pass the Activity's Context to this class and store it for example as a member field for further use.
For example your class is named ReadJSONResult. Create a constructor which takes Context as a parameter:
public ReadJSONResult(Context context) {
m_context = context; // There needs to be a field member in ReadJSONResult class called m_context
}
Thanks to that, in the Activity where you create ReadJSONResult object, you pass the Activity's Context to constructor and then you can create your ListAdapter like this:
ListAdapter adapter = new SimpleAdapter(m_context, mylist , R.layout.textview,new String[] { "exam", "id" },new int[] { R.id.exam, R.id.id });

Categories

Resources