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 });
Related
I am facing a problem, i have a listView that i fill using a custom array adapter, the issue is that when i use the custom array adapter, the data stored in the ArrayList won't show but if i use a normal ArrayAdapter the data will be shown. I need to use a custom array adapter to style the listview since i can't style it in the normal ArrayAdapter
here is the code:-
CustomAdapter adapter;
Context context;
ArrayList<String> data;
ListView listView;
private static String newline = System.getProperty("line.separator");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_production_comments);
//defining list view
listView = (ListView)findViewById(R.id.listView);
//defining data array list to store retrieved data from database
data = new ArrayList<String>();
adapter = new CustomAdapter(this,android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
context = this;
Toast.makeText(this,"Loading Please Wait..",Toast.LENGTH_LONG).show();
new AsyncLoadProdComments().execute();
}
protected class AsyncLoadProdComments extends AsyncTask<Void, JSONObject,
ArrayList<ProductionCommentsTable>> {
ArrayList<ProductionCommentsTable> ProductionCommentsTable = null;
#Override
protected ArrayList<ProductionCommentsTable> doInBackground(Void... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.GetProductionComments();
JSONParser parser = new JSONParser();
ProductionCommentsTable = parser.parseProductionComments(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadProdDetails", e.getMessage());
}
return ProductionCommentsTable;
}
#Override
protected void onPostExecute(ArrayList<ProductionCommentsTable> result) {
// TODO Auto-generated method stub
for (int i = 0; i < result.size(); i++) {
//Log.d("Data1", String.valueOf(result));
data.add("Date: " + result.get(i).getDate().substring(0, 10) + newline + newline +
"Item: " + result.get(i).getItem() + newline + newline +
result.get(i).getComments());
}
adapter.notifyDataSetChanged();
Toast.makeText(context,"Loading Completed", Toast.LENGTH_SHORT).show();
}
}
private class CustomAdapter extends ArrayAdapter {
private Context mContext;
private int id;
private List <String>items ;
public CustomAdapter(Context context, int textViewResourceId , ArrayList<String> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
if(position % 2 == 0){
mView.setBackgroundColor(Color.CYAN);
}else{
mView.setBackgroundColor(Color.YELLOW);
}
return mView;
}
}
Your using of array adapter is wrong. It has own array to store data, so instead of adding your data to data array list you shoud add it to adapter. It has method add (T object)
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.
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.
Its a really complicated question, but I hope someone can help me.
I want to make a custom adapter that can handle
Array List mentioned in the title
Currently I am doing this, but its not even going into getView(...) method.
public class EventsAdapter extends BaseAdapter{
ArrayList<HashMap<String, List<String>>> eventList;
private Context context;
private int resource;
private static final String TAG_TITLE = "e_title";
public EventsAdapter(Context context, int resId,ArrayList<HashMap<String, List<String>>> eventList)
{
this.context = context;
this.resource = resId;
this.eventList = eventList;
Log.v("chk", "1");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View event = convertView;
TextView title, desc, date, time, venue;
HashMap<String, List<String>> hm = eventList.get(position);
List<String> items = hm.get(TAG_TITLE);
Typeface font = Typeface.createFromAsset(context.getAssets(), "Ubahn.ttf");
if( event == null )
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
event = inflater.inflate( resource , parent, true );
event.setTag(items.get(position));
}
title = (TextView) event.findViewById( R.id.etitle);
desc = (TextView) event.findViewById( R.id.edesc );
date = (TextView)event.findViewById(R.id.edate);
time = (TextView)event.findViewById(R.id.etiming);
venue = (TextView)event.findViewById(R.id.elocation);
title.setTypeface(font);
System.out.print(items.get(0).toString());
title.setText(items.get(0).toString());
desc.setText(items.get(1).toString());
date.setText(items.get(2).toString());
time.setText(items.get(3).toString());
venue.setText(items.get(4).toString());
return event;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return eventList.get(position).get(position).get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
Any help would be greatly appreciated.
Here is how I am filling the data in the Array List
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String description = c.getString(TAG_DESC);
String date = c.getString(TAG_DATE);
String time = c.getString(TAG_TIME);
String venue = c.getString(TAG_VENUE);
// creating new HashMap
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> el = new ArrayList<String>();
el.add(title);
el.add(description);
el.add(date);
el.add(time);
el.add(venue);
// adding each child node to HashMap key => value
map.put(TAG_TITLE, el);
// map.put(TAG_DESC, description);
//muap.put(TAG_DATE, date);
// adding HashList to ArrayList
eventList.add(map);
}
and then here I am setting the adapter
EventsAdapter adapter = new EventsAdapter(getActivity(), R.layout.events_list_item, eventList);
lv.setAdapter( adapter);
I think it would be useful to consider when you are filling that list.
a good design pattern is to create the data as an empty hashmap, establish the adapter with that map, declare the listview( or whatever ) and then assign the adapter with the empty data set. later, fill the hashmap, and then adapter.notifydatasetchanged
I declare these feilds:
//array of places filtered by keyword
List<Place> places = new ArrayList<Place>( );
//spinner of places filtered by keyword
Spinner placesSpinner;
//adapter for spinner
private PlacesSpinnerAdapter placesSpinnerAdapter;
in onCreate:
//this is for a spinner, but same difference
placesSpinner = (Spinner)findViewById( R.id.placesSpinner );
placesSpinnerAdapter = new PlacesSpinnerAdapter( this,
android.R.layout.simple_spinner_dropdown_item, places );
placesSpinner.setAdapter( placesSpinnerAdapter );
and somewhere in the onPostExecute method of an AsyncTask you have no interest in
places.clear( );
places.addAll( result.results );
placesSpinnerAdapter.notifyDataSetChanged( );
placesSpinner.performClick( );
and lastly, here's a difference I see: adapters do Lists, I've never had a good time passing them hashmaps... do a map.keySet() or map.values(); as you hand the data over to the adapter; I know for certain the very standard pattern I just described does not work if the data set is hashmaps
gl hf
return list size from getCount method
#Override
public int getCount() {
return eventList.size();
}
As the array list inside the adapter does not have 5 items(it has only one item) so try return the size of the list
simply use this code for custom adapter java
public class CustomAdapter extends SimpleAdapter {
ArrayList<HashMap<String,String>> arrayList;
Context context;
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> arrayList, int resource, String[] from ,int[] to) {
super(context, arrayList, resource, from, to);
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
View view = super.getView(position,convertView,parent);
RelativeLayout container = (RelativeLayout)
view.findViewById(R.id.container);
return view;
}
}
and this is WelcomeActivity
ArrayList<HashMap<String, String>> userList = "Define your list here"
String[] from = new String[]{"name","phone"};
int[] to = new int[]{R.id.name,R.id.phone};
ListView lv = (ListView) findViewById(R.id.list);
CustomAdapter customAdapter = new CustomAdapter(this,userList,R.layout.user_list_f,from,to);
lv.setAdapter(customAdapter);
it has been working for me perfectly
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);