ive implented a searchbar into my ListView and so far it works correctly except
that the adapter is acting weird. Everytime i call its clear function my listview still shows the "old" content.
public abstract class MYLISTITEM extends BaseAdapter {
private Context activity;
private List<String> data;
private static LayoutInflater inflater=null;
private int ItemIcon;
private boolean moreVis;
public MYISTITEM(Context a, int IconID,boolean vis) {
activity = a;
data = new ArrayList<String>();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ItemIcon = IconID;
moreVis = vis;
}
public void add(String object)
{
data.add(object);
notifyDataSetChanged();
}
public void replace(int index,String object)
{
data.set(index, object);
notifyDataSetChanged();
}
public void clear()
{
data.clear();
notifyDataSetChanged();
}
public void remove(Object object)
{
data.remove(object);
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public void insert(String object,int c)
{
data.set(c, object);
notifyDataSetChanged();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
if(position >= 0 && position < data.size())
{
return data.get(position);
}
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public static class ViewHolder{
public TextView text;
public ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.item,parent, false);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(data.get(position));
holder.image.setImageDrawable(activity.getResources().getDrawable(ItemIcon));
ImageButton btn_more = (ImageButton) vi.findViewById(R.id.more);
if(moreVis)
{
btn_more.setOnClickListener(new OnMoreClickListener(btn_more,position));
}
else
{
btn_more.setVisibility(View.GONE);
}
vi.setOnClickListener(new OnRowClickListener(vi,position));
return vi;
}
public abstract void OnRowClick(View mView, int position);
public abstract void OnMoreClick(View mView, int position);
private class OnRowClickListener implements OnClickListener{
private int mPosition;
private View mView;
OnRowClickListener(View view,int position){
mPosition = position;
mView = view;
}
#Override
public void onClick(View arg0) {
OnRowClick(mView,mPosition);
}
}
private class OnMoreClickListener implements OnClickListener{
private int mPosition;
private View mView;
OnMoreClickListener(View view,int position){
mPosition = position;
mView = view;
}
#Override
public void onClick(View arg0) {
OnMoreClick(mView,mPosition);
}
}
}
the debugger shows that only the size of data has been changed but none of its content. Do i miss something here???
some additional code:
public abstract class MYSCREEN extends ListView{
public abstract void Init();
public abstract void OnLoadFinished();
public abstract void OnRowClicked(int position);
public abstract void onCreateQuickAction(MYQUICKACTION action,int position);
public abstract void CreateOptionMenu(Menu menu);
public abstract boolean OptionsItemSelected(MenuItem item);
public MYLISTITEM adapter = null;
public static void StartupScreen(Activity current,Class<?> next)
{
Intent myIntent = new Intent(current,next);
current.startActivity(myIntent);
}
public MYSCREEN(Activity context,int Icon) {
super(context);
boolean moreisvis = true;
MYQUICKACTION canarybirdybirdy = new MYQUICKACTION(new View(context));
onCreateQuickAction(canarybirdybirdy,0);
if(canarybirdybirdy.anchor.getVisibility() != View.VISIBLE)
{
moreisvis = false;
}
adapter = new MYLISTITEM(context,Icon,moreisvis){
#Override
public void OnRowClick(View mView, int position) {
// TODO Auto-generated method stub
OnRowClicked(position);
}
#Override
public void OnMoreClick(View mView, int position) {
// TODO Auto-generated method stub
final MYQUICKACTION mQuickAction = new MYQUICKACTION(mView);
final ImageButton mMoreImage = (ImageButton) mView.findViewById(MY.views.R.id.more);
mMoreImage.setImageResource(MY.views.R.drawable.ic_list_more_selected);
onCreateQuickAction(mQuickAction,position);
mQuickAction.setAnimStyle(MYQUICKACTION.ANIM_AUTO);
mQuickAction.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss() {
mMoreImage.setImageResource(MY.views.R.drawable.ic_list_more);
}
});
mQuickAction.show();
}
};
final ProgressDialog dialog = new ProgressDialog(context);
dialog.setMessage("loading...");
dialog.show();
new LOADER(){
#Override
public void RunThread() {
Init();
}
#Override
public void FinishLoad() {
dialog.dismiss();
OnLoadFinished();
}
}.Start();
}
public abstract class MYTHREAD extends AsyncTask<Void, Void, Void> {
public abstract void InitThread();
public abstract void RunThread();
public abstract void FinishThread();
#Override
protected Void doInBackground(Void... params) {
RunThread();
// TODO Auto-generated method stub
return null;
}
//ui stuff allowed
#Override
protected void onPreExecute() {
InitThread();
}
//ui stuff allowed
#Override
protected void onProgressUpdate(Void... value) {
super.onProgressUpdate(value);
}
//ui stuff allowed
#Override
protected void onPostExecute(final Void unused) {
FinishThread();
}
public void Start()
{
this.execute();
}
}
public abstract class LOADER extends MYTHREAD{
public abstract void FinishLoad();
#Override
public void InitThread() {
// TODO Auto-generated method stub
}
#Override
public void FinishThread() {
// TODO Auto-generated method stub
FinishLoad();
}
}}
and here is the function that gives me the headache.Its from one of MYSCREEN derived classes , oh and its also called from the search-buttons clickevent.
#Override
public void OnLoadFinished() {
// TODO Auto-generated method stub
SelectedTable = TabController.Instance.Clients[TabController.Instance.selectedtab ? 1 : 0].DbTablename;
adapter.clear();
TabController.Instance.Clients[TabController.Instance.selectedtab ? 1 : 0].MetaEntities(SelectedTable, true, new ClientCallBackHandler(){
#Override
public void StartCallBack() {
// TODO Auto-generated method stub
prgdialog.setMessage("connecting service...");
prgdialog.show();
}
#Override
public void EndCallBack(boolean success) {
// TODO Auto-generated method stub
if(success)
{
try{
ExceptionResponse except = (ExceptionResponse) this.response;
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>" + except.Message));
ab.setPositiveButton("ok", null);
ab.show();
success = false;
}catch(Exception e)
{
MetadataEntitiesResponse resp = (MetadataEntitiesResponse) response;
if(resp.Entities[0] != null)
{
Ent = resp.Entities[0];
int i = 0;
//search for the first string in our database ...
for(AttributeMetaData Att : Ent.Attributes)
{
if(Att.Type.contentEquals("string"))
{
SelectedAttribute = i;
break;
}
i++;
}
StartQuery(0); //here the adapter gets filled with info
}
}
}
}
});
}
private void StartQuery(int page)
{
if(currentpage != -1)
{
nextpage = page;
return;
}
Query query = new Query();
query.EntityName = Ent.Name;
if(SearchFilter != null)
{
query.Filter = new Filter();
query.Filter.Filters = SearchFilter;
query.Filter.FilterOperator = Filter.E_FilterOperator.And;
}
query.Columns = new AllColumns();
query.Limit = new Limit();
query.Limit.Count = 15;
Order order = new Order();
order.OrderType = Order.OrderTypeE.Ascending;
order.AttributeName = Ent.Attributes[SelectedAttribute].Name;
query.Orders = new Order[] {order};
currentpage = query.Limit.Page = page;
TabController.Instance.Clients[TabController.Instance.selectedtab ? 1 : 0].RetrieveMultiple(query, new ClientCallBackHandler(){
#Override
public void StartCallBack() {
// TODO Auto-generated method stub
}
#Override
public void EndCallBack(boolean success) {
// TODO Auto-generated method stub
try{
ExceptionResponse except = (ExceptionResponse) this.response;
ab.setMessage(Html.fromHtml("<b><font color=#ff0000>" + except.Message));
ab.setPositiveButton("ok", null);
ab.show();
success = false;
}catch(Exception e)
{
RetrieveMultipleResponse rmResp = (RetrieveMultipleResponse) this.response;
if(adapter.getCount() == 0)
{
for(int i = 0; i< rmResp.TotalRecords;i++)
{
prgdialog.setMessage( ((int) (i/rmResp.TotalRecords * 100)) + "%");
adapter.add("connecting...");
}
prgdialog.dismiss();
}
int i = 0;
for(Entity ent : rmResp.Entities)
{
adapter.replace(currentpage*15+i, ent.Properties[SelectedAttribute].ToString());
i++;
}
if(currentpage == nextpage)
{
nextpage = -1;
}
else
{
StartQuery(nextpage);
}
currentpage = -1;
}
}
});
}
i tried this code..
in oncreate() of where we are creating the CustomListView Adapter, call a function.
adapter.clear();
on the CustomListViewAdapter class create a function as clear
public void clear() {
// TODO Auto-generated method stub
movieItems.clear();
}
where movieItems is the name of the ListView
Call notifyDataSetChanged() instead.
In general you use notifyDataSetInvalidated() if item properties change, and notifyDataSetChanged() if items themselves change (i.e. items are removed or added).
Related
I have a listview with a custom adapter, and Im trying to use SearchView with a CustomFilter. But the search is not "fully" working.
When I search for something that is on the viewable area of the listview, it is able to search, and all nonviewable area is not being included in the search.
Here is a video on whats going on:
https://youtu.be/2Z9FZMlNmGw
main
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_board_game_list, container, false);
this.listView = (ListView) view.findViewById(R.id.listView);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this.getContext());
databaseAccess.open();
List<String> boardgamesNames = databaseAccess.getNames();
List<String> urls = databaseAccess.getUrls();
adapter = new bgAdapter(getContext(), R.layout.row_layout);
adapterOriginal = new bgAdapter(getContext(), R.layout.row_layout);
databaseAccess.close();
listView.setAdapter(adapter);
int i = 0;
for(String name: boardgamesNames) {
boardgameListRow data = new boardgameListRow(urls.get(i), boardgamesNames.get(i));
i++;
adapter.add(data);
adapterOriginal.add(data);
}
listView.setDivider(null);
listView.setDividerHeight(0);
searchView = (SearchView)view.findViewById(R.id.searchId);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
adapter.getFilter().filter(newText);
}
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
BoardGameListFragment fragment= new BoardGameListFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
//adapter = adapterOriginal;
return true;
}
});
// Inflate the layout for this fragment
return view;
}
}
Here is the Adapter:
https://github.com/Shank09/AndroidTemp/blob/master/bgAdapter.java
I think you need to call notifyDataSetChanged() in onQueryTextChange
I fixed it, I was using the wrong variable in bgAdapter. Please remove this question if possible.
public class Listbyoperator extends Activity {
ListView lstdetail;
Activity act;
EditText search;
ArrayList<DetailModel> detail=new ArrayList<DetailModel>();
DetailaAdapter dadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listbyoperator);
act=this;
lstdetail=(ListView) findViewById(R.id.Listbyoperator_detaillist);
search=(EditText) findViewById(R.id.editsearch);
search.setPadding(10, 0, 0, 0);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
DetailModel d=new DetailModel("1","HARDIP","saahi");
detail.add(d);
DetailModel d1=new DetailModel("2","jalpa","sadfsadf");
detail.add(d1);
dadapter=new DetailaAdapter(act, detail);
lstdetail.setAdapter(dadapter);
dadapter.notifyDataSetChanged();
lstdetail.setEnabled(true);
}
}
/*Detail Model*/
public class DetailModel
{
public String d_id,d_name,d_decription;
public String getD_id() {
return d_id;
}
public void setD_id(String d_id) {
this.d_id = d_id;
}
public String getD_name() {
return d_name;
}
public void setD_name(String d_name) {
this.d_name = d_name;
}
public String getD_decription() {
return d_decription;
}
public void setD_decription(String d_decription) {
this.d_decription = d_decription;
}
public DetailModel(String s1,String s2,String s3)
{
this.d_id=s1;
this.d_name=s2;
this.d_decription=s3;
}
}
/*detail adapter */
public class DetailaAdapter extends BaseAdapter{
Context mContext;
private List<DetailModel> data=null;
private ArrayList<DetailModel> arraylist;
private static LayoutInflater inflater=null;
private static String String=null,valid;
public boolean flag=true;
public DetailaAdapter(Context context,List<DetailModel> data)
{
mContext = context;
this.data = data;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<DetailModel>();
this.arraylist.addAll(data);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_detail, null);
final TextView t1,t2,t3,t4,t5;
t1=(TextView)vi.findViewById(R.id.list_detail_text1);
t2=(TextView)vi.findViewById(R.id.list_detail_textview2);
t3=(TextView)vi.findViewById(R.id.list_detail_text2);
DetailModel da =new DetailModel(String, String,String);
da=data.get(position);
final String a1,a2,a3;
a1=da.d_id;
a2=da.d_name;
a3=da.d_decription;
t2.setText(a3);//description
t3.setText(a2);//name
return vi;
}
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll(arraylist);
}
else
{
for (DetailModel wp : arraylist)
{
if (wp.getD_decription().toLowerCase(Locale.getDefault()).contains(charText) || wp.getD_name().toLowerCase(Locale.getDefault()).contains(charText))
{
data.add(wp);
}
}
}
notifyDataSetChanged();
}
}
I've custom adapter that populates custom listview with data fetched from server. What I want is check if adapter is empty and append data to listview if it is empty else fill the listview with data and notifyDataSetChanged. I'm implementing OnScrollListener to load more data from server. But adapter never is empty and always notifyDataSetChanged is called.
My List Activity
public class ListResultActivity extends Activity implements OnScrollListener{
private ArrayList<BusinessListData> businesses;
private ListView businessList;
private LayoutInflater layoutInflator;
private BusinessListIconTask imgFetcher;
BusinessListDataAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.businesslist);
this.businessList = (ListView) findViewById(R.id.lvBusinesslist);
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
getData();
businessList.setOnScrollListener(this);
}
#Override
public Object onRetainNonConfigurationInstance() {
Object[] myStuff = new Object[2];
myStuff[0] = this.businesses;
myStuff[1] = this.imgFetcher;
return myStuff;
}
/**
* Bundle to hold refs to row items views.
*
*/
public static class MyViewHolder {
public TextView businessName, businessAddress, phoneNo;
public Button btnProfile;
public ImageView icon;
public BusinessListData business;
}
public void setBusinesses(ArrayList<BusinessListData> businesses) {
this.imgFetcher = new BusinessListIconTask(this);
this.layoutInflator = LayoutInflater.from(this);
this.businesses = businesses;
if(adapter !=null){
this.adapter.notifyDataSetChanged();
}else{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
}
private void getData() {
// TODO Auto-generated method stub
Intent myIntent = getIntent();
// gets the arguments from previously created intent
String metroTxt = myIntent.getStringExtra("key");
String metroLoc = myIntent.getStringExtra("loc");
String metroId = myIntent.getStringExtra("qt");
BusinessListApiTask spTask = new BusinessListApiTask(
ListResultActivity.this);
try {
spTask.execute(metroTxt, metroLoc, metroId);
} catch (Exception e) {
spTask.cancel(true);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (businessList.getLastVisiblePosition() == totalItemCount - 1) {
getData();
adapter.notifyDataSetChanged();
Log.d("test count", "abc"+totalItemCount);
}
}
}
Class to fetch data from server and set to adapter
public class BusinessListApiTask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private ListResultActivity activity;
private static final String debugTag = "sodhpuch";
HashMap<String, String> queryValues;
/**
* Construct a task
*
* #param activity
*/
public BusinessListApiTask(ListResultActivity activity) {
// TODO Auto-generated constructor stub
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_business), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
// Log.d(debugTag, "Background:" +
// Thread.currentThread().getName());
String result = BusinessListHelper.downloadFromServer(params);
// try {
//
// updateSQLite(result);
//
// } catch (Exception e) {
// return result;
// }
Log.d("result", result);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<BusinessListData> businessData = new ArrayList<BusinessListData>();
progDialog.dismiss();
try {
JSONObject respObj = new JSONObject(result);
int success = respObj.getInt("success");
Log.d("Success", "abc"+success);
if (success == 1) {
JSONArray tracks = respObj.getJSONArray("idioms");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String businessName = track.getString("name");
String businessAddress = track.getString("address");
String phone = track.getString("phone");
String id = track.getString("id");
String deals_in = track.getString("deals_in");
businessData.add(new BusinessListData(businessName,
businessAddress, id, phone, deals_in));
}
} else {
Log.d("Success", "first"+success);
// Log.d(debugTag, "Background:" + result);
// DBController controller = new DBController(context);
// businessData = controller.getBusinessList();
return ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
this.activity.setBusinesses(businessData);
}
My Adapter
public class BusinessListDataAdapter extends BaseAdapter implements
OnClickListener {
private static final String debugTag = "BusinessListDataAdapter";
private ListResultActivity activity;
private BusinessListIconTask imgFetcher;
private LayoutInflater layoutInflater;
private ArrayList<BusinessListData> businesses;
BusinessListData business;
public BusinessListDataAdapter(ListResultActivity a,
BusinessListIconTask i, LayoutInflater l,
ArrayList<BusinessListData> data) {
this.activity = a;
this.imgFetcher = i;
this.layoutInflater = l;
this.businesses = data;
}
#Override
public int getCount() {
return this.businesses.size();
}
public void clear()
{
businesses.clear();
notifyDataSetChanged();
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.trackrow, parent,
false);
holder = new MyViewHolder();
holder.businessName = (TextView) convertView
.findViewById(R.id.tvBusinessName);
holder.businessAddress = (TextView) convertView
.findViewById(R.id.tvAddress);
holder.phoneNo = (TextView) convertView.findViewById(R.id.tvPhone);
holder.icon = (ImageView) convertView.findViewById(R.id.album_icon);
holder.btnProfile = (Button) convertView
.findViewById(R.id.btnProfile);
holder.btnProfile.setTag(holder);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
convertView.setOnClickListener(this);
business= businesses.get(pos);
holder.business = business;
holder.businessName.setText(business.getName());
holder.businessAddress.setText(business.getAddress());
holder.phoneNo.setText(business.getPhone());
holder.btnProfile.setOnClickListener(this);
// if(track.getImageUrl() != null) {
// holder.icon.setTag(track.getImageUrl());
// Drawable dr = imgFetcher.loadImage(this, holder.icon);
// if(dr != null) {
// holder.icon.setImageDrawable(dr);
// }
// } else {
holder.icon.setImageResource(R.drawable.filler_icon);
// }
return convertView;
}
#Override
public void onClick(View v) {
String deals_in = business.getDeals().toString();
Log.d("name", deals_in);
MyViewHolder holder = (MyViewHolder) v.getTag();
if (v instanceof Button) {
Intent profile = new Intent(activity,
ProfileActivity.class);
profile.putExtra("deals_in", deals_in);
profile.putExtra("phone", holder.business.getPhone());
profile.putExtra("address", holder.business.getAddress());
profile.putExtra("name", holder.business.getName());
this.activity.startActivity(profile);
} else if (v instanceof View) {
Log.d("test","call testing");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" +holder.business.getPhone()));
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
Try this way,hope this will help you to solve your problem.
public void setBusinesses(ArrayList<BusinessListData> businesses) {
imgFetcher = new BusinessListIconTask(this);
layoutInflator = LayoutInflater.from(this);
if(this.businesses == null || adapter==null){
this.businesses = new ArrayList<BusinessListData>();
adapter= new BusinessListDataAdapter(this,imgFetcher,layoutInflator,this.businesses);
businessList.setAdapter(adapter);
}
this.businesses.addAll(businesses);
adapter.notifyDataSetChanged();
}
You have the adapter object in your setBusinesses Method. You just need to check the size of the adapter too as follows which is solve your problem.
if(adapter !=null && adapter.getCount()>0)
{
this.adapter.notifyDataSetChanged();
}
else
{
this.adapter= new BusinessListDataAdapter(this,
this.imgFetcher, this.layoutInflator, this.businesses);
businessList.setAdapter(adapter);
}
this will check the size of your BusinessListData object in the adapter and this will not initialize the adapter again and again.
Hope this Solves your problem.
Thank You!
Change use of OnScrollListener. Use Asynctask class and onPreExecute() set adapter as null. Load data in doInBackground() method and call custom adapter in onPostExecute(). I hope it 'll work fine.
Here i am getting data on Console :
DataBaseManager dbManager = new DataBaseManager(context);
ArrayList<Notify> notifies = dbManager.getNotificationList();
System.out.println("today " + notifies.size());
for (int i = 0; i < notifies.size(); i++) {
System.out
.println("Valueeeeeeeeeeeeeeeee:"
+ notifies.get(i).getNotificationStatus()
+ "\n"
+ notifies.get(i).getNotificationServerId() + "\n" +
notifies.get(i).getNotificationDatetime());
}
Here is my datamodelclass:
public class Notify {
private String notificationId;
private String notificationServerId;
private String notificationSenderID;
private String notificationRecieverID;
private String notificationType;
private String notificationDescrpiton;
private String notificationStatus;
private String notificationDatetime;
private String notificationIsRead;
public String getNotificationId() {
return notificationId;
}
public void setNotificationId(String notificationId) {
this.notificationId = notificationId;
}
public String getNotificationServerId() {
return notificationServerId;
}
public void setNotificationServerId(String notificationServerId) {
this.notificationServerId = notificationServerId;
}
public String getNotificationSenderID() {
return notificationSenderID;
}
public void setNotificationSenderID(String notificationSenderID) {
this.notificationSenderID = notificationSenderID;
}
public String getNotificationRecieverID() {
return notificationRecieverID;
}
public void setNotificationRecieverID(String notificationRecieverID) {
this.notificationRecieverID = notificationRecieverID;
}
public String getNotificationType() {
return notificationType;
}
public void setNotificationType(String notificationType) {
this.notificationType = notificationType;
}
public String getNotificationDescrpiton() {
return notificationDescrpiton;
}
public void setNotificationDescrpiton(String notificationDescrpiton) {
this.notificationDescrpiton = notificationDescrpiton;
}
public String getNotificationStatus() {
return notificationStatus;
}
public void setNotificationStatus(String notificationStatus) {
this.notificationStatus = notificationStatus;
}
public String getNotificationDatetime() {
return notificationDatetime;
}
public void setNotificationDatetime(String notificationDatetime) {
this.notificationDatetime = notificationDatetime;
}
public String getNotificationIsRead() {
return notificationIsRead;
}
Here is my adapter:
public class RowItem extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return null;
}
}
I want tp Print value In List i have 3 text view for
notifies.get(i).getNotificationStatus()
notifies.get(i).getNotificationStatus()
notifies.get(i).getNotificationStatus()
But i am unable to Print data please help how to set value in adapter.
As you sending the ArrayList while creating Object of Notifcationadapter (inside Activity or Fragment) no need to fill data in Notifcationadapter. You should only declare the arraylist ArrayList<Notify> notifies;
Code
Context context;
ViewHolder holder;
//LinearLayout linear2;
ArrayList<Notify> notifies;
public Notifcationadapter(Context context,ArrayList<Notify> notifies) {
super();
this.context = context;
this.notifies = notifies;
}
You can use ViewHolder Class for that
Why are you returning 0 to getCount();
fix your adapter-
#Override
public int getCount() {
// TODO Auto-generated method stub
return notifies.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return notifies.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public class EpisodeScreen extends Activity implements OnClickListener,OnItemClickListener,IServerResponse {
private String image;
private String episodediscription;
private String video;
private ListView episodelist=null;
private ArrayList<Object> _EpisodeList=new ArrayList<Object>();
private EpisodeAdapter mAdapter=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.episode_list);
episodelist=(ListView)findViewById(R.id.listview1);
episodelist.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.play:
Log.i("click","sucess");
break;
default:
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
getEpisode();
}
public void getEpisode() {
if (NetworkAvailablity.checkNetworkStatus(EpisodeScreen.this)) {
ArrayList<NameValuePair> requestParaList = new ArrayList<NameValuePair>();
requestParaList.add(new BasicNameValuePair("issue_id","1"));
WebServiceCommunicator.getInstance().registerForServerResponse(
(IServerResponse) EpisodeScreen.this);
WebServiceCommunicator.getInstance().callGetAppWebService(
Constant.showDialog, this, WebServiceConstants.getMethodUrl(WebServiceConstants.METHOD_NAME_GET_EPISODE_DETAILS),
EpisodeScreen.this, Constant.PID_EPISODE, false,
requestParaList);
} else {
Constant.showAlertDialog(Constant.errorTitle,
Constant.MSG_CHECK_INTERNET_SETTING,
EpisodeScreen.this, false);
}
}
#Override
public void serverResponse(String response, int processid) {
// TODO Auto-generated method stub
Message msg = new Message();
msg.obj = response;
msg.arg1 = processid;
_handler.sendMessage(msg);
}
private Handler _handler = new Handler() {
public void handleMessage(Message msg) {
String respons=msg.obj.toString();
switch (msg.arg1) {
case Constant.PID_EPISODE:
if(respons!=null ){
try{
JSONObject jsonObj=new JSONObject(respons);
JSONArray jArray=jsonObj.optJSONArray("Episode Detail");
if(jArray!=null){
for(int i =0;i<jArray.length();i++){
JSONObject jsonObject=jArray.getJSONObject(i);
episodebean bean=new episodebean();
bean.setEpisode_image(jsonObject.getString("Episode-image"));
bean.setEpisode_discription(jsonObject.getString("Episode-description"));
bean.setEpisode_video(jsonObject.getString("Episode-video"));
_EpisodeList.add(bean);
}
mAdapter=new EpisodeAdapter(EpisodeScreen.this, _EpisodeList);
episodelist.setAdapter(mAdapter);
/**/
/*if(_EpisodeList.size()!=0){
mAdapter=new EpisodeAdapter(EpisodeScreen.this, _EpisodeList);
episodelist.setAdapter(mAdapter);
}*/
}
}
catch (JSONException e) {
}
}
break;
default:
break;
}
}
};
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "ok........", Toast.LENGTH_LONG).show();
}
}
here is adapter
public class EpisodeAdapter extends BaseAdapter {
private LayoutInflater _mInflater = null;
private ArrayList<Object> _EpisodeList=null;
private Context ctx = null;
private UserImageLoaderWithCache imageLoader=null;
public EpisodeAdapter(Context context,
ArrayList<Object> _episodeList) {
// TODO Auto-generated constructor stub
this.ctx = context;
this._EpisodeList = _episodeList;
imageLoader=new UserImageLoaderWithCache(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return _EpisodeList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return _EpisodeList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
static class ViewHolder {
public TextView txtViewTitle;
public ImageView pic;
public TextView tvurl;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater linf = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = linf.inflate(R.layout.episode_screen, null);
// view.imgViewFlag.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.tv_episode);
holder.tvurl=(TextView)convertView.findViewById(R.id.tv_url);
holder.pic = (ImageView) convertView.findViewById(R.id.iv_episode);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final episodebean bean=(episodebean)_EpisodeList.get(position);
holder.txtViewTitle.setText(bean.getEpisode_discription());
holder.tvurl.setText(bean.getEpisode_video());
imageLoader.display(bean.getEpisode_image(), holder.pic, R.drawable.ic_launcher);
return convertView;
}}
I am using ListView in which I have to show data, which is coming from server. My ListView is not showing anything while response is coming (although it is showing in logcat) What do I do? Please help.
Thank you.
try to change some code on your adapter at method: getItemId
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
let us know if this work.
It may be help u..replace your handler
private Handler _handler = new Handler() {
public void handleMessage(Message msg) {
switch (id) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
I have a BaseAdapter in that, I have a Button. When a user clicks on that button, I need to call a Service and I need to set the data to that button in onpostExecute()
public class MenuTagsAdapter extends BaseAdapter {
View v;
#Override
public int getCount() {
// TODO Auto-generated method stub
return BaseApp.getTagsAroundMeList().size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.menutaglistitem, null);
TextView textViewName = (TextView) v
.findViewById(R.id.textViewName);
final Button buttonAction = (Button) v
.findViewById(R.id.buttonAction);
textViewName.setText("#"
+ BaseApp.getTagsAroundMeList().get(position).name);
buttonAction
.setText(BaseApp.getTagsAroundMeList().get(position).action);
buttonAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (buttonAction.getText().toString()
.equalsIgnoreCase("follow")) {
buttonAction.setBackgroundResource(R.drawable.followbutton);
if (appUtils.getNetworkInfo(AmgonnaHome.this)) {
new FollowInterestAsyTask().execute();
} else {
NetworkDialogClass.createDAlertDialog(
AmgonnaHome.this,
getString(R.string.network_error));
}
} else {
buttonAction.setBackgroundResource(R.drawable.unfollowbutton);
if (appUtils.getNetworkInfo(AmgonnaHome.this)) {
new UnfollowInterestAsyTask().execute();
} else {
NetworkDialogClass.createDAlertDialog(
AmgonnaHome.this,
getString(R.string.network_error));
}
}
}
});
return v;
}
}
public class FollowInterestAsyTask extends AsyncTask<Void, Void, Void> {
boolean progressDialogStatus = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(AmgonnaHome.this,
"Please Wait", "Connecting to Server");
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
progressDialogStatus = false;
}
});
}
#Override
protected Void doInBackground(Void... params) {
TaskUrl = BaseApp.baseUrl + BaseApp.followInterest;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("user_id=" + amgonnaUserId);
// stringBuilder.append("&interestName="+);
stringBuilder.append("&interestName=");
ConnectionManager connectionManager = new ConnectionManager();
String response = connectionManager.setUpHttpPost(TaskUrl,
stringBuilder.toString());
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
errStatus = jsonObject.getInt("errStatus");
status = jsonObject.getString("status");
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialogStatus) {
progressDialog.dismiss();
if (errStatus == 0) {
// here i need to set the status message to button on adapter list item
}
}
}
}
Just save the string you want to show in button in a variable.
eg :
String temp=btnText;
Then call your list adapter again.
And make a change in your getView() as
buttonAction.setText(temp);