i have created a list of ads in listview using BaseAdapter and i want to delete a single ad from list. To delete a single ad i have to request a web api using asynchronous task, so i have added the notifyDataSetChanged() in onPostExecute method. ads was deleted successfully but notifydatasetchnaged not working .my custom BaseAdapter class is given below please help to solve this problem.
public class AdsListAdapter extends BaseAdapter{
private Activity activity;
ArrayList<String> title;
ArrayList<Long> adsIds;
SessionManager sessions;
AlertDialogManager alert = new AlertDialogManager();
private static LayoutInflater inflater=null;
String MYTAG="AdLIst";
long userID=0;
public AdsListAdapter(Activity a,ArrayList<String> titlelist,ArrayList<Long> adsId,long userid) {
activity = a;
title=titlelist;
adsIds=adsId;
userID=userid;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
sessions=new SessionManager(activity.getApplicationContext());
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView titles,editicon,delicon;
}
#SuppressLint("NewApi") public View getView(int position, View convertView, ViewGroup parent) {
final int id=position;
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.adscustomlist, null);
holder = new ViewHolder();
holder.titles = (TextView) vi.findViewById(R.id.titles);
holder.editicon= (TextView) vi.findViewById(R.id.editicon);
holder.delicon= (TextView) vi.findViewById(R.id.delicon);
vi.setTag( holder );
}
else
{ holder=(ViewHolder)vi.getTag(); }
holder.titles.setText(title.get(position));
holder.delicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DeleteAd(userID,adsIds.get(id)).execute();
}
});
return vi;
}
class DeleteAd extends AsyncTask<String,Void,Void>
{
AlertDialogManager alert = new AlertDialogManager();
private String Error = null,Message=null;
long UserID =0,AdId=0;
boolean Status=false;
private ProgressDialog Dialog = new ProgressDialog(activity);
protected void onPreExecute() {
Dialog.setMessage("Loading ...");
Dialog.setCanceledOnTouchOutside(false);
Dialog.show();
}
public DeleteAd(long UserID,long AdId) {
this.UserID=UserID;
this.AdId=AdId;
}
#Override
protected Void doInBackground(String... arg0) {
JSONObject json;
try {
json = new JSONObject(postDataAdDelete());
Message=json.getString("Message");
Status = json.getBoolean("Status");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
alert.showAlertDialog(activity, "Ad Delete", Message, Status);
notifyDataSetChanged();
}
}
}
Try to call notifyDataSetChanged() method like this
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
you must remove value at position you want to delete in list title. Try title.remove(position)
AdsListAdapter adapter = new AdsListAdapter (Activity ,ArrayList<String> ,ArrayList<Long> ,long );//pass the value
adapter.notifyDataSetChanged();
Related
I have a activity which implements onitemlongclicllstener to a list view. I use parse.com as my back end for retrieving data into listvview. Everything works fine but onitemlongclicllstener don't work on list view. Nothing happens when list item is long clicked
my main activity
public class InterActivity extends Activity implements OnItemLongClickListener
{
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
FinalAdapter adapter;
List<CodeList> codelist = null;
SharedPreference shrdPreference;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.inter_layout);
shrdPreference = new SharedPreference();
//Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(InterActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Please wait loading ...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
codelist = new ArrayList<CodeList>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"InterActivity");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("_created_at");
ob = query.find();
for (ParseObject inter : ob) {
ParseFile video = (ParseFile) inter.get("demovideo");
// ParseFile downloadfile = (ParseFile) inter.get("download");
CodeList map = new CodeList();
map.setListHeading((String) inter.get("listheading"));
map.setSingleItemHeading((String) inter.get("heading"));
map.setDownloadCode((String) inter.get("download"));
map.setDailogdemovideo(video.getUrl());
// map.setDownloadCode(downloadfile.getUrl());
codelist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.inter_layoutListView);
// Pass the results into ListViewAdapter.java
adapter = new FinalAdapter(InterActivity.this,
codelist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemLongClickListener(InterActivity.this);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3)
{
ImageView fvrtebutton = (ImageView) view.findViewById(R.id.favbtn);
String tag = fvrtebutton.getTag().toString();
if (tag.equalsIgnoreCase("no")) {
shrdPreference.addFavorite(InterActivity.this, codelist.get(position));
Toast.makeText(InterActivity.this, getString(R.string.fav_added),
Toast.LENGTH_SHORT).show();
fvrtebutton.setTag("yes");
fvrtebutton.setImageResource(R.drawable.favorite);
} else {
shrdPreference.removeFavorite(InterActivity.this, codelist.get(position));
fvrtebutton.setTag("no");
fvrtebutton.setImageResource(R.drawable.unfavorite);
Toast.makeText(InterActivity.this,
getString(R.string.fav_removed),
Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
final adapter.java
public class FinalAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ImageLoader imgLoader;
private List<CodeList> codeList = null;
private ArrayList<CodeList> arraylist;
SharedPreference shrdprfrnce;
public FinalAdapter(Context context,
List<CodeList> codeList) {
this.context = context;
this.codeList = codeList;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<CodeList>();
this.arraylist.addAll(codeList);
shrdprfrnce = new SharedPreference();
imageLoader = new ImageLoader(context);
}
public class ViewHolder{
TextView listHeading;
TextView listHash;
ImageView alphabetList;
ImageView favariteImage;
}
#Override
public int getCount()
{
return codeList.size();
}
#Override
public Object getItem(int position)
{
return codeList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent)
{
final ViewHolder holder;
if(view == null){
holder = new ViewHolder();
view = inflater.inflate(R.layout.beg_list_item,null);
holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
//holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
holder.favariteImage = (ImageView) view.findViewById(R.id.favbtn);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
CodeList codes = (CodeList) getItem(position);
holder.listHeading.setText(codeList.get(position).getListHeading());
imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
holder.alphabetList);
if (checkFavoriteItem(codes)) {
holder.favariteImage.setImageResource(R.drawable.favorite);
holder.favariteImage.setTag("yes");
} else {
holder.favariteImage.setImageResource(R.drawable.unfavorite);
holder.favariteImage.setTag("no");
}
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return view;
}
public boolean checkFavoriteItem(CodeList checkCodes) {
boolean check = false;
List<CodeList> favorites = shrdprfrnce.getFavorites(context);
if (favorites != null) {
for (CodeList codes : favorites) {
if (codes.equals(checkCodes)) {
check = true;
break;
}
}
}
return check;
}
public void add(CodeList codes) {
(
codeList.add(codes);
notifyDataSetChanged();
}
public void remove(CodeList codes) {
codeList.remove(codes);
notifyDataSetChanged();
}
}
plz remove
view.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
Intent intent = new Intent(context, SingleItemView.class);
//intent.putExtra("listheading",
// (codeList.get(position).getListHeading()));
//intent.putExtra("alphabetimg",
// (codeList.get(position).getAlphabetimg()));
intent.putExtra("demovideo",
(codeList.get(position).getDailogdemovideo()));
intent.putExtra("download",
(codeList.get(position).getDownloadCode()));
// Start SingleItemView Class
context.startActivity(intent);
}
});
bcoz it Get Full view Click Thats y ur OnLongClick is not working yet
try with return true;
#Override
public boolean onItemLongClick(AdapterView < ? > arg0, View arg1,
int pos, long id) {
Log.v("long clicked", "pos: " + pos);
return true;
}
I have Like Button In Layout and set the text "like 0" , i Have Set in Base Adapter , When I click on Like Buttton, the text will increase without refresh the whole Activity Like in facebook app , I am stuck on three days , i have read and implements almost every answer of stackoverflow , but not get the solution. I hope i will get the answer. Here is My Base Adapter <------->
public class FeedAdaptorView extends BaseAdapter{
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
String UserID;
public FeedAdaptorView(Context context,
ArrayList<HashMap<String, String>> arraylist, String uSERid2) {
this.context = context;
data = arraylist;
}
public class ViewHolder {
TextView name,time,status,likecount;
ImageView userimage,postimage;
Button like,comment,share;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.feed_item, null);
holder=new ViewHolder();
pos=getItemViewType(position);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.status=(TextView)convertView.findViewById(R.id.txtStatusMsg);
holder.userimage=(ImageView)convertView.findViewById(R.id.profilePic);
holder.postimage=(ImageView)convertView.findViewById(R.id.feedImage1);
holder.like=(Button)convertView.findViewById(R.id.like);
holder.comment=(Button)convertView.findViewById(R.id.comment);
holder.pos=position;
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.like.setTag(pos);
/* inflater = (LayoutInflater) context
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
}); .getSystemService(Context.LAYOUT_INFLATER_SERVICE);*/
holder.comment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
holder.postimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
holder.like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Liked The Post", Toast.LENGTH_SHORT).show();
holder.like.setText("Like"+"4");
notifyDataSetChanged();
// here i am calling the web services for like button update
new likepost().execute();
}
});
<--------------------------------->
webservice callin method
class likepost extends AsyncTask<Void, Void, Void>
{
int flag=0;
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(context);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... args0) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String Status="1";
String ID=feedid;
params.add(new BasicNameValuePair("UserID",UserID));
params.add(new BasicNameValuePair("FeedId",ID));
params.add(new BasicNameValuePair("like_status",Status));
JSONObject json = jsonParser.makeHttpRequest(AppControllerClass.FeedLike,"POST", params);
Log.d("Create Response", json.toString());
try{
if(json!=null)
{
String status=json.getString("status");
if(status.equals("Success"))
{
flag=1;
// Toast.makeText(context, "You Liked The Post", Toast.LENGTH_SHORT).show();
}
else
{
flag=2;
//Toast.makeText(context, "Check The Connection", Toast.LENGTH_SHORT).show();
}
}
else{
flag=2;
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args)
{
mProgressDialog.dismiss();
if(flag==1)
{
Toast.makeText(context, "You Liked The Post", Toast.LENGTH_SHORT).show();
}
else if (flag==2)
{
Toast.makeText(context, "Check The Connection", Toast.LENGTH_SHORT).show();
}
}
Dynamically Increase the text count on click in BaseAdapter
Do it as using getTag/setTag:
#Override
public void onClick(View c) {
int count=0;
if(v.getTag()==null)
count=0;
else{
count=Integer.parseInt(v.getTag().toString());
}
count++;
((TextView)v).setText("Like"+count);
v.setTag(count);
}
Try this..
#Override
public Object getItem(int position) {
return data.get(position);
}
instead of
#Override
public Object getItem(int position) {
return null;
}
This is my first time answering questions on StackOverflow and I hope that my answer is able to help you solve your problem.
PROBLEM :
holder.like.setText("Like"+"4");
notifyDataSetChanged();
The problem is here. You have manually set it to setText("Like"+"4"). In BaseAdapter's notifyDataSetChanged() function, it refers to an ADAPTER of information.
In your case, it will be the reference of resulttp. It is referencing to the data ArrayList you have passed in. And when you call notifyDataSetChanged(), it will refer back to the resulttp and display WHAT is in the ArrayList.
SOLUTION :
1) Remove this line
holder.like.setText("Like"+"4");
2) Add in a new function called update() in your BaseAdapter class
public void updateAdapter(ArrayList<HashMap<String, String>> newData)
{
this.data.clear();
this.data = data;
notifyDataSetChanged();
}
3) On your like button / image onClickListener, call the function updateAdapter() and pass in an UPDATED ArrayList.
It should be alright already. Good Luck!
I am using Listview with ViewHolder, and setText in Textview then display error. How to setText in Textview in Listview? Whenever I click on Like Button then I get the total count for Like but I am not able to setText on TextView for every item. whenever click on selected item then Its TextView Increment by 1 Its Successfully. get strCount is Successfully but how to setText for Selected TextView when Click on Selected Image and My code is,
My Screenshot is which is Listview and set Multiple Items in Listview Like,
My Adapter Class,
public class Adapter1 extends BaseAdapter {
public ArrayList<HashMap<String, String>> arr = null;
Context context = null;
LayoutInflater layoutInflater = null;
HashMap<String, String> getData = new HashMap<String, String>();
String url = null, urlCount = null;
String strId = null, strCount = null;
ViewHolder viewHolder = null;
public Adapter1(Context context, ArrayList<HashMap<String, String>> arr) {
this.context = context;
this.arr = arr;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int position) {
return arr.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null);
/** initialize ViewHolder */
viewHolder = new ViewHolder();
/** Initialize Widgets */
/** Imageview */
viewHolder.img = (ImageView) convertView.findViewById(R.id.img);
/** TextView */
viewHolder.txtId = (TextView) convertView.findViewById(R.id.txtId);
viewHolder.txt = (TextView) convertView.findViewById(R.id.txt);
getData = arr.get(position);
viewHolder.txtId.setText(getData.get(Fragment1.TAG_ID));
viewHolder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
strId = arr.get(position).get(Fragment1.TAG_ID);
System.out.println("!!!!!!!!!! strId======"+ strId);
url = "http://example.com/createpost.php?id="+ strId + "&user_id="+ myDetail.getUserId();
new sendData().execute();
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
/** ViewHolder Class */
#SuppressLint("NewApi")
public class ViewHolder {
ImageView img = null,
TextView txtId = null
txt = null;
}
public class sendData extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(urlLike, ServiceHandler.GET);
System.out.println("!!!!!!!!!!!!!!!jsonStr in Do in===" + jsonStr);
Log.d("Response : Like", ">" + jsonStr);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
urlCount = "http://example.com/getalldata.php?id="+ strId;
new getCountData().execute();
};
}
/** Count the Total Like for Selected Items. */
private class getCountData extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonobject = JSONFunctions.getJSONfromURL(urlCount);
try {
strCount = jsonobject.getString("countdata");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
System.out.println("!!!!!!!!strCount====" + strCount);
viewHolder.txt.setText(String.valueOf(strCount));
}
}
}
Thanks in advance.
In onClick() function you have to get instance of textview and pass it to AsyncTask
// if text and img have same parent the you can find textview like this is
TextView tv =(TextView)v.getParent().findViewById(R.id.txt);
// if not then apply call getParent() function multiple time as per your layout
new sendData(tv).execute();
//Create constructor in sendData
public class sendData extends AsyncTask {
private TextView tv;
public sendData(TextView v){
tv=v;
}
...
protected void onPostExecute(Void result) {
super.onPostExecute(result);
urlCount = "http://example.com/getalldata.php?id="
+ strId;
new getCountData(tv).execute();
};
}
private class getCountData extends AsyncTask {
private TextView v;
public sendData(TextView v){
tv=v;
}
....
// in onPostExecute use
tv.setText(String.valueOf(strCount));
}
Edit: you can get correct position by tag position to view and get it inside onClick
// add this line before return
viewHolder.img.setTag(position);
// get position inside onClick()
int position =(Integer)v.getTag();
I am making a sectional listview in which to section first is pending request list and second is already friend there are two button accept and reject in first section of list view.
When I click on accept hit server and change stautus and now my List should be update and first section accepted list should showing in friendlist in second section of listview.
I am using following code:-
public class EntryAdapter extends ArrayAdapter<Item> {
private Context context;
private List<Item> items;
private LayoutInflater objlayoutinflator;
private PostJobImageLoader objimageLoader;
private ConnectionFriendListModle objmodle=null;
public EntryAdapter(Context context,List<Item> items) {
super(context, 0, items);
this.context = context;
this.items = items;
objlayoutinflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
objimageLoader = new PostJobImageLoader(context.getApplicationContext());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
final Item objitem = items.get(position);
if (objitem != null) {
if (objitem.isSection()) {
SectionItem objsection = (SectionItem) objitem;
myview = objlayoutinflator.inflate(R.layout.listviewsection,
null);
myview.setOnClickListener(null);
myview.setOnLongClickListener(null);
myview.setLongClickable(false);
final TextView sectionView = (TextView) myview
.findViewById(R.id.txtsection);
sectionView.setText(objsection.getTitle());
} else {
objmodle = (ConnectionFriendListModle) objitem;
myview = objlayoutinflator.inflate(R.layout.connectionlistrow,
null);
final TextView title = (TextView) myview
.findViewById(R.id.jobtitleinjobbidalert);
final TextView subtitle = (TextView) myview
.findViewById(R.id.jobsubtitle);
final ImageView objimageview = (ImageView) myview
.findViewById(R.id.user_image);
final Button objaccept = (Button) myview
.findViewById(R.id.btnaccept);
final Button objreject = (Button) myview
.findViewById(R.id.btnreject);
if (objmodle.getStatus().equalsIgnoreCase("pending")) {
objaccept.setVisibility(View.VISIBLE);
objreject.setVisibility(View.VISIBLE);
title.setText(objmodle.getUsername());
subtitle.setText(objmodle.getName());
String url = objmodle.getPicture();
objimageLoader.DisplayImage(AppConstants.IMAGE_BASE_URL
+ url, objimageview);
} else {
objaccept.setVisibility(View.INVISIBLE);
objreject.setVisibility(View.INVISIBLE);
title.setText(objmodle.getUsername());
subtitle.setText(objmodle.getName());
String url = objmodle.getPicture();
objimageLoader.DisplayImage(AppConstants.IMAGE_BASE_URL+url, objimageview);
}
objaccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AcceptFriendRequest().execute(objmodle.getId(),"accepted");
}
});
objreject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
}
});
}
}
return myview;
}
private class AcceptFriendRequest extends AsyncTask<String,Void,String>
{
ProgressDialog objprogress = new ProgressDialog(EntryAdapter.this.context);
AppRequestHandler objApprequest = new AppRequestHandler();
String objresponce="";
#Override
protected void onPreExecute() {
objprogress.setMessage("Please Wait While Loading...");
objprogress.show();
}
#Override
protected String doInBackground(String... params) {
objresponce = objApprequest.acceptRequest(params[0],params[1]);
return objresponce;
}
#Override
protected void onPostExecute(String result) {
if(objprogress.isShowing())
{
objprogress.dismiss();
}
if(result.equals("0"))
{
SharedPreferences myPrefs = EntryAdapter.this.context.getSharedPreferences(
AppConstants.MYPREF, EntryAdapter.this.context.MODE_WORLD_READABLE);
String userid = myPrefs.getString(AppConstants.USER_ID, "");
//but when controll reach this line not execute this asynctask and niether update listview
new GetAllConnectionDetail().equals("86");
}
}
}
private class GetAllConnectionDetail extends AsyncTask<String,Void,List<Item>>
{
ProgressDialog objprogress = new ProgressDialog(EntryAdapter.this.context);
AppRequestHandler objApprequest = new AppRequestHandler();
List<Item> objlistitem=null;
#Override
protected void onPreExecute() {
objprogress.setMessage("Please Wait While Loading...");
objprogress.show();
}
#Override
protected List<Item> doInBackground(String... params) {
objlistitem = objApprequest.connectionDetails(params[0]);
return objlistitem;
}
#Override
protected void onPostExecute(List<Item> result) {
if(objprogress.isShowing())
{
objprogress.dismiss();
}
items.clear();
items.addAll(result);
notifyDataSetChanged();
}
}
}
Is am going right way or wrong please any one help me why it is not working...
You have to start your GetAllConnectionDetail task by calling its execute method, seems you don't do that.
I am fairly new to Android development and I am trying to build a ListView which get data from web service using gson. I have a model class, a list class, an adapter class and the activity class.
The list works fine and it got the data, and now I want to integrate the OnItemClickListener to it and pass the data to the 2nd activity. And I'd like to get the item id (DistrictId) and pass it to the next Activity(listView) instead of the row id. It would be great if someone could show me the light... as the documentation is not as clear to understand and because I am new.
Below is my code.
The model class
package com.sample.myapp;
public class DistrictModel {
private String id;
private String districtName;
public String getDistrictId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDistrictName(){
return districtName;
}
public void setDistrictEN(String districtName){
this.districtName = districtName;
}
}
The List class
public class DistrictList {
private List<DistrictModel> districts;
public List<DistrictModel> getDistricts(){
return districts;
}
public void setDistrictList(List<DistrictModel> districts){
this.districts = districts;
}
}
The Adapter class
public class DistrictAdapter extends ArrayAdapter<DistrictModel>{
int resource;
String response;
Context context;
private LayoutInflater dInflater;
public DistrictAdapter(Context context, int resource, List<DistrictModel> objects) {
super(context, resource, objects);
this.resource = resource;
dInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView title;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
DistrictModel lm = (DistrictModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = dInflater.inflate(R.layout.item_district, null);
holder = new ViewHolder();
holder.title = (TextView) convertView
.findViewById(R.id.district_name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(lm.getDistrictName());
return convertView;
}
}
The activity class
public class DistrictListActivity extends Activity{
LocationManager lm;
ArrayList<DistrictModel> districtArray = null;
DistrictAdapter districtAdapter;
DistrictList list;
ListView lv;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.districtlist_layout);
lv = (ListView) findViewById(R.id.list_district);
districtArray = new ArrayList<DistrictModel>();
districtAdapter = new DistrictAdapter(DistrictListActivity.this, R.layout.item_district, districtArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(districtAdapter);
try {
new DistrictSync().execute("http://aws.something.com/service");
} catch(Exception e) {}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(DistrictListActivity.this);
adb.setTitle("LVSelectedItemExample");
adb.setMessage("Selected Item is = "+(lv.getItemIdAtPosition(position)));
adb.setPositiveButton("Ok", null);
adb.show();
}
}); **//i'd like to get the DistrictId from the json data.**
}
private class DistrictSync extends AsyncTask<String, Integer, DistrictList> {
protected DistrictList doInBackground(String... urls) {
DistrictList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, DistrictList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(DistrictList dislist) {
for(DistrictModel lm : dislist.getDistricts())
{
districtArray.add(lm);
}
districtAdapter.notifyDataSetChanged();
}
}
}
For testing purpose, now I click the row it will show me the row id, so I know the onclick listener works, but I just want it to grab me the DistrictId so I can use it to pass to the next activity.
Thank you so much.
(out of my head) Try this:
((DistrictModel)lv.getAdapter().getItem(position)).getDistrictId();
Generally when you want to pass data from one Activity to another, you just place it into the Intent that you use to create the new Activity.
For example (and here are some additional examples):
Intent i = new Intent(context, MyNewActivity.class);
i.putExtra("MyCurrentHealth", mCurrentHealth);
context.startActivity(i);
To retrieve the data do this:
Bundle extras = getIntent().getExtras();
if (extra != null) {
... // Do stuff with extras
}