Why AsyncTask is not execute in PostExecute method of another AsynkTask? - android

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.

Related

Android Listview does not refresh/redraw

Problem - I have list of in app purchases loaded from app store in a Listview.
When user purchases (taps on a button in listview) the item is purchased and the button should be now hidden and the list item purchased should show an image of tick.
What I have tried -
Refresh the listview after item is purchased by calling notifyDataSetChanged
Set the visibility of the button and image using View.GONE and View.VISIBLE
None of the above seems to work.
I am using this in app billing library
public class ListViewAdapter extends ArrayAdapter<Product> {
private ArrayList<Product> iapProducts= new ArrayList<>();
private final LayoutInflater inflater;
private final Activity activity;
public ArrayList<Product> getIapProducts() {
return iapProducts;
}
public void setIapProducts(ArrayList<Product> iapProducts) {
this.iapProducts = iapProducts;
}
public ListViewAdapter(final Activity context) {
super(context, 0);
inflater = LayoutInflater.from(context);
this.activity = context;
}
#Override
public int getCount() {
return this.iapProducts.size();
}
public String getItem(String position) {
return position;
}
#Override
public boolean hasStableIds(){
return true;
}
public void addAll(ArrayList<Product> iapProducts){
this.iapProducts.addAll(iapProducts);
notifyDataSetChanged();
}
public static class ViewHolder {
public TextView name;
public ImageView imageView;
public Button purchaseButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.names_filter_row, null);
holder = new ViewHolder();
holder.name = (TextView) vi.findViewById(R.id.languageName);
holder.imageView = (ImageView) vi.findViewById(R.id.imgTick);
holder.purchaseButton = (Button) vi.findViewById(R.id.iapProductPurchaseBtn);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
final Product product = iapProducts.get(position);
holder.name.setText(product.getTitle());
holder.purchaseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemPurchased(v);
}
});
holder.iapProductId.setText(product.getProductId());
holder.purchaseButton.setText(product.getPriceText());
holder.imageView.setVisibility(View.GONE);
if(product.isPurchased()){
holder.purchaseButton.setVisibility(View.GONE);
holder.imageView.setVisibility(View.VISIBLE);
}else{
holder.purchaseButton.setVisibility(View.VISIBLE);
holder.imageView.setVisibility(View.GONE);
}
return vi;
}
private void onItemPurchased(View v){
final RelativeLayout parentLayout = (RelativeLayout)v.getParent();
final TextView productId = (TextView)parentLayout.findViewById(R.id.iapProductId);
final ImageView languageCheck = (ImageView)parentLayout.findViewById(R.id.imgTick);
PurchaseActivity purchaseActivity = (PurchaseActivity) this.activity;
purchaseActivity.purchaseItem(productId.getText().toString(), v);
}
}
public class PurchaseActivity extends AppCompatActivity implements BillingProcessor.IBillingHandler {
private BillingProcessor bp;
boolean isOneTimePurchaseSupported;
private ArrayList<Product> productsToPurchase = new ArrayList<>();
private final static String TAG = PurchaseActivity.class.getName();
private ListViewAdapter adapter;
private ImageView imageTick;
private Button buttonPurchase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
bp = BillingProcessor.newBillingProcessor(this, "billingKey", this); // doesn't bind
bp.initialize(); // binds
adapter = new ListViewAdapter(this);
nameFilterListView.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onBillingInitialized() {
isOneTimePurchaseSupported = bp.isOneTimePurchaseSupported();
if(isOneTimePurchaseSupported){
loadIAPData(false);
}else{
Toast.makeText(this,"Billing not supported",Toast.LENGTH_LONG).show();
}
}
private void loadIAPData(boolean showProgressDialog){
bp.loadOwnedPurchasesFromGoogle();
final List<SkuDetails> productDetails = bp.getPurchaseListingDetails(productList);
if(productDetails!= null && !productDetails.isEmpty()){
//fetch products and add to the list
productsToPurchase.add(product);
}
//add all the products to adapter
adapter.addAll(productsToPurchase);
}
}
public void purchaseItem(#NonNull final String productId, final View imageTick, final View button){
this.imageTick = (ImageView) imageTick;
this.buttonPurchase = (Button) button;
bp.purchase(this,productId);
}
#Override
public void onProductPurchased(String productId, TransactionDetails details) {
//hide button show image
this.imageTick.setVisibility(View.VISIBLE);
this.buttonPurchase.setVisibility(View.GONE);
adapter.setIapProducts(new ArrayList<>(productsToPurchase));
adapter.notifyDataSetChanged();
}
}
(Moved comment into a post)
After a user purchases something, is that Product within productsToPurchase updated? The adapter looks okie so maybe the list you're using isn't being updated after a purchase.
I'm assuming you need to flip the isPurchased flag of the Product in onProductPurchased() using the provided productId.

How to wire up a delete button to delete one item on a listview?

I know there are lots of threads with more or less same topic but none of them covers my situation:
I am trying to get my delete button to delete one row on the list view and the delete button appear in each row I got this part to work but I can't get it to work in my Main Activity. The code keeps breaking every time I put this part in my code:
ImageButton removeButton = (ImageButton) findViewById(R.id.btnDel);
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRemoveButtonClick();
}
private void onRemoveButtonClick() {
ToDoItem item = (ToDoItem) v.getTag();
notifyDataSetChanged();
}
my MainActivity works fine without this bit of code. I don't know if it is the code or if it is where I am placing it in my MainActivity if someone would please tell that would much appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(this, listManager.getList());
todoList.setAdapter(adapter);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Add item to list
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
Log.i(LOG_TAG, input.getText().toString());
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int Which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(Context context, List<ToDoItem> items){
super(context,-1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
textView.setText(items.get(position).getDescription());
checkBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
ToDoListManager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if (json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit =savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
ToDoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem (String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return description;
}
}
enter image description here
1.) Add a button to your to_do_item_layout first
2.) Now add this code to add a button to each item
Button btn = (Button) convertView.findViewById(R.id.my_btn);
3.) Add a listener to it
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.remove(items.get(position));
}
});

how to send all the data of array list to another activity?

Daily Screen :-
public class DailyScreen extends AppCompatActivity implements AdapterView.OnItemClickListener {
ImageView add, edit;
MyCustomAdapter adapter1;
Button ok;
Button next2;
final Context context = this;
ListView listView;
private ArrayAdapter<String> adapter;
List<Milk> items=new ArrayList();
public List<Milk> getItems() {
return items;
}
public void setItems(List<Milk> items) {
this.items = items;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_listview);
add = (ImageView) findViewById(R.id.add);
edit = (ImageView) findViewById(R.id.edit);
listView = (ListView) findViewById(R.id.list);
next2 = (Button) findViewById(R.id.next2);
Milk milkDefault=new Milk("Toned Milk",0);
items.add(milkDefault);
//this.setArrayList((ArrayList<String>) Arrays.asList(items));
adapter1 = new MyCustomAdapter(items, this);
listView.setAdapter(adapter1);
listView.setOnItemClickListener(this);
registerForContextMenu(listView);// to set context menu in list view
}
#Override
protected void onResume() {
super.onResume();
next2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DailyScreen.this, SupplierActivity.class);
intent.putExtra("LIST_ITEMS",List,items);//
startActivity(intent);
}
});
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(DailyScreen.this);
dialog.setTitle("Enter new Milk");
dialog.setContentView(R.layout.dialog_box);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
final EditText editText = (EditText) dialog.findViewById(R.id.pro);
String data = editText.getText().toString();
//button initialization
Button ok = (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = editText.getText().toString();
if (!data.isEmpty()) {
items.add(new Milk(data,0));
adapter1.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "product name is :" + data, Toast.LENGTH_LONG).show();
dialog.cancel();
}
else{
Toast.makeText(DailyScreen.this, "Please enter the data", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
MyCustomAdapter class
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private List<Milk> list = new ArrayList<Milk>();
private Context context;
public MyCustomAdapter(List<Milk> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_layout, null);
}
TextView name = (TextView) view.findViewById(R.id.text);
name.setText(list.get(position).getNsme());
final TextView milkCount = (TextView) view.findViewById(R.id.milkcount);
milkCount.setText(""+list.get(position).getAmount());
ImageView increment = (ImageView) view.findViewById(R.id.add);
ImageView decrement = (ImageView) view.findViewById(R.id.sub_item);
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
a = a + 1;
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(milkCount.getText().toString().trim());
if (a == 0) {
a = 0;
} else {
a = a - 1;
}
milkCount.setText("" + a);
list.get(position).setAmount(a);
}
});
return view;
}
Milk class
public class Milk {
private String nsme ;
private int amount ;
public Milk(String nsme, int amount) {
this.nsme = nsme;
this.amount = amount;
}
public String getNsme() {
return nsme;
}
public void setNsme(String nsme) {
this.nsme = nsme;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
i have tried all thing to send all the data of list view to another activty please suggest me how can i do it ??
Make the list static and u can then access it in any activity. Make sure u initialise the list
milk class extends serializable firstly
then u do
make object of milk class in mainactivity class
Milk milk=new Milk(this);
Intent i=new Intent(getApplicationContext(),Update.class);
i.putExtra("emnumber",(Serializable)milk);
startActivity(i);
then u can pick the value in update class
if(getIntent().getSerializableExtra("emnumber")!=null) {
con = (ArrayList<Contact>) getIntent().getSerializableExtra("emnumber");
email_mobile = contactList.get(0).nsme;
pass__word = contactList.get(0).amount;
you can implement as:
public class Milk implements Parcelable{
......
}
Send arraylist as:
intent.putExtra("files", "your arraylist");
obtain arraylist as:
Intent inIntent = getIntent();
list=inIntent.getParcelableArrayListExtra("files");
Try this. May be it help.
Send arraylist to activity through extras.
intent.putStringArrayListExtra("ARRAY_LIST", arrayList);
Retrieve arraylist in activity.
arrayList= i.getStringArrayListExtra("ARRAY_LIST");
If u have to send arraylist other than string then.
intent.putParcelableArrayListExtra("ARRAY_LIST", (ArrayList<Milk>) milkArrayList);
Milk class must be parcellable

How to set Text in Textview when Click on selected item in Listview?

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();

Cannot see listview in fragment

I am currently modifying an android app that I need to add a listview to an existing fragment. As I am new to android, I am just imitating the code from the apps. I created a new arrayadapter, a new class of data and made some modifies to the existing fragment class. The problem is I cannot see my list in the app. Below are my codes.
Adapter
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRec;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRec)
{
super(context, resourceId, checkInRec);
this.resourceId = resourceId;
this.context = context;
this.checkInRec = checkInRec;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_name);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkindate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_points);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
CheckInRecord.CheckInRec checkInrec = checkInRec.get(position);
textViewName.setText(checkInrec.providerName);
textViewCheckInDate.setText(checkInrec.checkInDate);
textViewPoints.setText(checkInrec.providerPoints);
ImageLoader.getInstance().displayImage(checkInrec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRec.get(position).isPrize);}
}
Data type
public class CheckInRecord {
public int userPoints;
public String userName;
public String gender;
public String birthDate;
public String location;
public String userIcon;
public List<CheckInRec> checkInRecList = new ArrayList<CheckInRec>();
public void addCheckInRec(String providerName, String providerLocation, String providerIcon,
String checkInDate, int providerPoints, int isPrize){
CheckInRec checkInRec = new CheckInRec();
checkInRec.providerName = providerName;
checkInRec.providerLocation = providerLocation;
checkInRec.providerIcon = providerIcon;
checkInRec.checkInDate = checkInDate;
checkInRec.providerPoints = providerPoints;
checkInRec.isPrize = isPrize;
checkInRecList.add(checkInRec);
}
public List<String> recImages(){
List<String> resultList = new ArrayList<String>();
if (this.checkInRecList == null){
return resultList;
}
for (CheckInRec rec : this.checkInRecList){
resultList.add(rec.providerIcon);
}
return resultList;
}
public class CheckInRec{
public String providerName;
public String providerLocation;
public String providerIcon;
public String checkInDate;
public int providerPoints;
public int isPrize;
}
}
Fragment
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRec = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppDataManager.getInstance().setAllowCheckIn(true);
progressDialog = ProgressDialog.show(getActivity(), "", "");
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) view.findViewById(R.id.tv_name);
textViewPoints = (TextView) view.findViewById(R.id.tv_points);
ListView listViewCheckInRec = (ListView) view.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity().getApplicationContext(), R.layout.row_record, checkInRec);
listViewCheckInRec.setAdapter(recordArrayAdapter);
return view;
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
refreshName();
}
}
public void refreshName() {
progressDialog = ProgressDialog.show(getActivity(), "", "");
AppDataManager dataManager = AppDataManager.getInstance();
ApiManager.getInstance().checkInHistories(dataManager.getUserToken(), dataManager.getUserPhone(), Utility.getPictureSize(), this);
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
// this.checkInRec.clear();
// this.checkInRec.addAll(checkInRecord.checkInRecList);
//
// recordArrayAdapter.notifyDataSetChanged();
}
}
}
The problem is I cannot see my list in the app.
That is because checkInRec does now have any elements inside of it.
I can really tell that it is empty because you commented this out:
// this.checkInRec.clear(); //clear the old data from the list
// this.checkInRec.addAll(checkInRecord.checkInRecList); //add all the data inside the checkInRecord.checkInRecList
//
// recordArrayAdapter.notifyDataSetChanged(); //refreshing the ListView to display the new data
now what are those doing is that clearing the old list array and adding the new set of data from checkInRecord.checkInRecList and refreshing the ListView so those new data are implemented/shown in your ListView.

Categories

Resources