How to send Items from one activity to another on item checked - java

I want to send all selected items from my first activity to another activity on item checked. There are three classes in my app First is Appetizer class,second class is ItemListBaseAdapter class and third class is Manage class I want to send the checked item from Appetizers class to Manage class.If you need to know any other information let me know.
This is my Appetizer class
public class Appetizers extends Activity{
Button manage;
public static final String[] titles = new String[] { "Aloo Chat",
"Paneer Tikka", "Spring Roll", "Paneer Chilly", "Veg Roll","Rice balls","Pasta", };
public static final String totalPrice="0";
public static final int[] quantities = new int[]{ 0 };
public static final String[] price={"20","10","30","40","50","60","10"};
public static final Integer[] images = { R.drawable.a39,
R.drawable.a40, R.drawable.a41, R.drawable.a42,R.drawable.a74,R.drawable.a75,R.drawable.a76 };
public ItemListBaseAdapter adapter;
ListView listView;
public List<RowItem> rowItems;
Button add,sub;
public static Appetizers apti;
public RowItem item;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
apti=this;
// LinearLayout layout = (LinearLayout) getWindow().findViewById(R.id.button1);
// layout.addView(new Button(this));
manage=(Button) findViewById(R.id.manage);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
item = new RowItem(images[i], titles[i], quantities[0],price[i],totalPrice);
rowItems.add(item);
Log.e("item in appetizer", ""+item);
manage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// intt.putParcelable("myclass",rowItems);
// intt.putStringArrayListExtra("key", rowItems);
Intent i=new Intent(Appetizers.this,Manage.class);
startActivity(i);
}
});
}
listView = (ListView) findViewById(R.id.list);
ItemListBaseAdapter adapter = new ItemListBaseAdapter(this,
R.layout.item_details_view, rowItems);
Log.e("Row items in appetizer",""+rowItems);
listView.setAdapter(adapter);
}
}
This is my ItemListBaseAdapter class
class ItemListBaseAdapter extends ArrayAdapter<RowItem> {
public static ItemListBaseAdapter adapter;
Context context;
int getPosition;
int rowItem;
String check1;
public List<RowItem> rowItems;
/*
* here we must override the constructor for ArrayAdapter the only variable
* we care about now is ArrayList<RowItem> objects, because it is the list
* of objects we want to display.
*/
public ItemListBaseAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
adapter=this;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle,txtPrice,ttprice;
TextView txtDesc;
Button add, sub,manage;
CheckBox check;
}
/*
* we are overriding the getView method here - this is what defines how each
* list item will look.
*/
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_details_view, null);
}
/*
* Recall that the variable position is sent in as an argument to this
* method. The variable simply refers to the position of the current
* object in the list. (The ArrayAdapter iterates through the list we
* sent it)
*
* Therefore, rowItem refers to the current RowItem object.
*/
RowItem rowItem = getItem(position);
if (rowItem != null) {
holder = new ViewHolder();
// This is how you obtain a reference to the TextViews
// Images,checkBox,Buttons.
// These TextViews are created in the XML files we defined.
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.ttprice=(TextView) convertView.findViewById(R.id.tPrice);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.check = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.add = (Button) convertView.findViewById(R.id.button1);
holder.sub = (Button) convertView.findViewById(R.id.button2);
// holder.manage = (Button) convertView.findViewById(R.id.manage);
// holder.check.setOnClickListener( new View.OnClickListener() {
// public void onClick(View v) {
// CheckBox cb = (CheckBox) v ;
// RowItem rowItem = (RowItem) cb.getTag();
// Toast.makeText(context,"Clicked on Checkbox: " + cb.getText() +" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
// rowItem.setSelected(cb.isChecked());
// }
// });
/*
* holder.check.setOnClickListener( new View.OnClickListener() {
* public void onClick(View v) { CheckBox cb = (CheckBox) v ;
* RowItem rowItem = (RowItem) cb.getTag(); Toast.makeText(context,
* "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(),
* Toast.LENGTH_LONG).show(); rowItem.setSelected(cb.isChecked()); }
* });
*/
} else
{
holder = (ViewHolder) convertView.getTag();
}
/*holder = (ViewHolder) convertView.getTag();
*rowItem = rowItems.get(position); holder.txtTitle.setText(" (" +
*rowItem.getTitle() + ")"); holder.check.setText(rowItem.getName());
*holder.check.setChecked(rowItem.isSelected());
* holder.check.setTag(rowItem);
*/
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.txtPrice.setText(rowItem.getPrice());
Log.e("title",""+rowItem.getTitle());
Log.d("description",""+rowItem.getDesc());
Log.e("Price",""+rowItem.getPrice());
holder.imageView.setImageResource(rowItem.getImageId());
holder.add.setTag(position);
holder.sub.setTag(position);
//holder.manage.setTag(position);
holder.check.setTag(position);
holder.add.setEnabled(false);
holder.sub.setEnabled(false);
final RowItem finalRowItem = rowItem;
final ViewHolder viewHolderFinal = holder;
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity();
if (quantity >= 0) {
finalRowItem.setQuantity(quantity + 1); // update it by adding 1
quantity=finalRowItem.getQuantity();
if (quantity>=1) {
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=quantity*x;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
}
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
} else {
viewHolderFinal.add.setEnabled(false);
viewHolderFinal.sub.setEnabled(false);
}
// get the quantity for this row item
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
String check =finalRowItem.getDesc()+finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getTotalPrice();
Toast.makeText(context,"Clicked on Checkbox check1: " +finalRowItem.getDesc()+finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getTotalPrice(), Toast.LENGTH_LONG).show();
Intent intt=new Intent(context,Manage.class);
intt.putExtra("allItem", check);
Log.d("final description in add", finalRowItem.getDesc());
// set the new description (that uses the updated qunatity)
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity();
if (quantity == 1) {
finalRowItem.setQuantity(quantity - 1);
Toast.makeText(context, "Item is unchecked", Toast.LENGTH_LONG).show();
viewHolderFinal.check.setChecked(false);
viewHolderFinal.add.setEnabled(false);
viewHolderFinal.sub.setEnabled(false);
} else {
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
}
// get the quantity for this row item
finalRowItem.setQuantity(quantity - 1);
quantity=finalRowItem.getQuantity();
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=quantity*x;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
//Toast.makeText(context, "898798",0).show();
// update it by subtracting 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
Log.d("final description in sub", finalRowItem.getDesc());
// set the new description (that uses the updated qunatity)
}
});
// the view must be returned to our activity
//Toast.makeText(context,"Quantity selected"+finalRowItem.getTotalPrice() ,Toast.LENGTH_SHORT).show();
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
Log.d("checkbox checked", "checkbox checked");
// RowItem finalRowItem = (RowItem) cb.getTag();
Toast.makeText(context,"Clicked on Checkbox: " +finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getDesc()+" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
// finalRowItem.setSelected(cb.isChecked());
viewHolderFinal.add.setEnabled(true);
viewHolderFinal.sub.setEnabled(true);
finalRowItem.quantity =finalRowItem.getQuantity();
finalRowItem.quantity = 1;
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
if (finalRowItem.quantity>=1) {
Log.e("checkbox checked-2", "checkbox checked-2");
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=finalRowItem.quantity*x;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
//Toast.makeText(context, "898798",0).show();
Toast.makeText(context,"Clicked on Checkbox check1: " +finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getTotalPrice()+" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}
} else {
if (finalRowItem.quantity>=1) {
Log.d("checkbox checked-3", "checkbox checked-3");
String p=finalRowItem.getPrice();
int x=Integer.parseInt(p);
int y=finalRowItem.quantity*x;
y=0;
String f=Integer.toString(y);
finalRowItem.setTotalPrice(f);
viewHolderFinal.ttprice.setText(finalRowItem.getTotalPrice());
//Toast.makeText(context, "898798",0).show();
}
finalRowItem.quantity = finalRowItem.getQuantity();
if (finalRowItem.quantity > 0) {
finalRowItem.quantity = 0;
}
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc());
Toast.makeText(context,"Clicked on Checkbox check2: " +finalRowItem.getTitle() +finalRowItem.getPrice()+finalRowItem.getDesc()+finalRowItem.getQuantity()+" is " + cb.isChecked(), Toast.LENGTH_LONG).show();
viewHolderFinal.add.setEnabled(false);
viewHolderFinal.sub.setEnabled(false);
}
}
});
return convertView;
}
}

There are two easier ways by which you can send the item from one class to another:
1. Save the items in SharedPrefernces and access them in another class.
2. Send them as part of intent using putExtra() api.

Write your class which implements Parcelable. Pass its instance over the intent.
See this for usage.

You could implement Parcelable interface on your item.
First of all, your RowItem should implement Parcelable interface (ex: http://developer.android.com/reference/android/os/Parcelable.html)
Then you should use not List but ArrayList, and put this object in intent:
Intent i = ...;
i.putParcelableArrayListExtra(rowItems);

In your MainActivity or the activity where you the values , which you want to send to another activity, write below code.
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("Username", YOUR STRING);
editor.putString("EMAIL", YOUR STRING);
editor.commit();
its a key value pair, where username and EMAIL are key and value will be your string which you have to send to other activity.
Then in other activity where you want to retrieve the data add below code.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String text = preferences.getString("Username", "null");
String Email1=preferences.getString("EMAIL", "null");
String Email=Email1.toString();
Hope this helps.

Related

Firebase RecylcerView Adapter Not Getting Accurate View Position

I am using the Firebase UI and am experiencing a unique issue. When I load the RecyclerView, there are no issues. I click an item on the RecyclerView and get the .push() value of the item that was clicked. It then takes data from that Firebase .push() value, which is stored in the Firebase database, and sends it to another activity. See images below:
The second image is the activity that receives data via an intent. When I click back to the RecyclerView, I click "8" again and I am loading a different number (right now it appears to be 1).
Ultimately, I am concerned that I do not have the RecyclerView set up correctly. Here is my code:
Create Poll object (POJO) and write to Firebase:
mSubmitPollCreation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: Need to check if poll requirements are added, i.e. Question, Answer, ......
//check if image has been loaded first
if (resultImageURL == null) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_image_selected), Toast.LENGTH_LONG).show();
return;
}
//capture answers
if (mNumberOfPollAnswersCreatedByUser > 5) {
Toast.makeText(getApplicationContext(), getResources().getText(R.string.poll_answers_greater_than_five), Toast.LENGTH_LONG).show();
mNumberOfPollAnswersCreatedByUser = 5;
}
for (int i = 0; i < mNumberOfPollAnswersCreatedByUser; i++) {
EditText editText = (EditText) mEditTextAnswerLayout.findViewWithTag(getResources().getString(R.string.created_answer_editText_id) + String.valueOf(i + 1));
String editTextInputForAnswer = String.valueOf(editText.getText());
mPollAnswers.add(0, editTextInputForAnswer); Toast.makeText(getApplicationContext(),editTextInputForAnswer,Toast.LENGTH_SHORT).show();
}
Poll poll = new Poll(mCreatePollQuestion.getText().toString(), resultImageURL, mPollAnswers);
Map<String, Object> pollMap = poll.toMap();
final String key = mBaseRef.child("Polls").push().getKey();
Map<String, Object> childUpdates = new HashMap<String, Object>();
childUpdates.put("/Polls/" + key, pollMap);
mBaseRef.updateChildren(childUpdates);
Collections.reverse(mPollAnswers);
for (int i = 0; i < mPollAnswers.size(); i++) {
mBaseRef.child("Polls").child(key).child("answers").child(String.valueOf(i + 1)).updateChildren(poll.answerConvert(mPollAnswers, i));
}
Intent toHomeActivity = new Intent(CreateActivity.this, HomeActivity.class);
toHomeActivity.putExtra("viewpager_position", 2);
startActivity(toHomeActivity);
}
});
Where I read from Firebase and populate a RecyclerView:
public class LiveFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView mRecyclerview;
private DatabaseReference mBaseRef;
private DatabaseReference mPollsRef;
private LinearLayoutManager mLayoutManager;
private FloatingActionButton mFloatingActionAdd;
private FirebaseRecyclerAdapter<Poll, PollHolder> mFireAdapter;
private RecyclerView.ItemAnimator mItemAnimator;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public LiveFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static LiveFragment newInstance(String param1, String param2) {
LiveFragment fragment = new LiveFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBaseRef = FirebaseDatabase.getInstance().getReference();
mPollsRef = mBaseRef.child("Polls");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_new, container, false);
Log.v("TAG", "ON CREATE CALLED FROM NEW");
mRecyclerview = (RecyclerView) v.findViewById(R.id.list);
mRecyclerview.setItemAnimator(new SlideInLeftAnimator());
mLayoutManager = new LinearLayoutManager(getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mFloatingActionAdd = (FloatingActionButton) getActivity().findViewById(R.id.myFAB);
mFloatingActionAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent I = new Intent(getActivity().getApplicationContext(), CreateActivity.class);
startActivity(I);
}
});
mRecyclerview.setLayoutManager(mLayoutManager);
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
scrollToPosition();
}
#Override
public void onStart() {
super.onStart();
mFireAdapter = new FirebaseRecyclerAdapter<Poll, PollHolder>(Poll.class, R.layout.latest_item, PollHolder.class, mBaseRef.child("Polls")) {
#Override
protected void populateViewHolder(PollHolder viewHolder, final Poll model, final int position) {
viewHolder.mPollQuestion.setText(model.getQuestion());
Picasso.with(getActivity().getApplicationContext())
.load(model.getImage_URL())
.fit()
.into(viewHolder.mPollImage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("TAG", model.toString());
Log.v("TAG","ONCLICKED");
Intent toPoll = new Intent(getActivity(), PollHostActivity.class);
toPoll.putExtra("POLL_ID", mFireAdapter.getRef(position).getKey());
startActivity(toPoll);
}
});
Log.v("TAG", mFireAdapter.getRef(position).getKey());
Log.v("TAG", String.valueOf(position));
Log.v("TAG", model.getQuestion());
Log.v("TAG", model.getImage_URL());
}
};
mRecyclerview.setAdapter(mFireAdapter);
scrollToPosition();
}
#Override
public void onStop() {
super.onStop();
if (mFireAdapter != null) {
mFireAdapter.cleanup();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public static class PollHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mPollQuestion;
ImageView mPollImage;
View mView;
public PollHolder(View itemView) {
super(itemView);
mPollQuestion = (TextView) itemView.findViewById(R.id.latest_item_question);
mPollImage = (ImageView) itemView.findViewById(R.id.pollThumbNailImage);
this.mView = itemView;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.v("TAG", "CLICKED");
}
}
private void scrollToPosition(){
mFireAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int pollCount = mFireAdapter.getItemCount();
int lastVisiblePosition = mLayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
// to the bottom of the list to show the newly added message.
if (lastVisiblePosition == -1 ||
(positionStart >= (pollCount - 1) && lastVisiblePosition == (positionStart - 1))) {
mRecyclerview.scrollToPosition(positionStart);
}
}
});
}
}
My thoughts:
am I calling mFireAdapter.cleanup() in the right location?
The issue with clicking "8" and seeing "1" does not appear on the first load of the RecyclerView, it only happens when I go from the activity (second image) and the navigate back to the RecyclerView.
I call .setStackFromEnd(true) and .setReverseLayout(true) to reverse the data as it is stored in the FirebaseDatabase, which could be contributing to the issue.
I set up the .setOnClickListener() in the .populateViewHolder() method, and use the following to pass the .push() key in an intent to the next activity:
toPoll.putExtra("POLL_ID", mFireAdapter.getRef(position).getKey());
This method could be getting the incorrect key.
Finally, Firebase Database:
Any help would be appreciated!
You should not use position outside of populateViewHolder as it value may differ. Instead, make your viewHolder final and use viewHolder.getAdapterPosition() to replace it.

Wrong item position into ListView

I need to open a frameLayout details into a listView, but when I press the buttonDetails, it opens a wrong frameLayout.
here is the code of my adapterView
public class SitesAdapter extends ArrayAdapter<AtlantisSite> {
ImageLoader imageLoader;
DisplayImageOptions options;
FrameLayout frameLayout;
public SitesAdapter(Context ctx, int textViewResourceId, List<AtlantisSite> sites) {
super(ctx, textViewResourceId, sites);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
}
/*
* (non-Javadoc)
* #see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*
* This method is responsible for creating row views out of a AtlantisSite object that can be put
* into our ListView
*/
#Override
public View getView(final int pos, final View convertView, final ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("AtlantisSites", "getView pos = " + pos);
//ViewHolder mainViewHolder = null;
final ViewHolder viewHolder;
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
viewHolder = new ViewHolder();
viewHolder.btnDownload = (Button) row.findViewById(R.id.btnDownload);
viewHolder.btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer pos=(Integer)v.getTag();
Log.i("AtlantisSites", "getView pos = " + pos);
//String url = getItem(pos).getLink();
DownloadZip zipActivity = new DownloadZip();
zipActivity.DownloadFromUrlZip();
//Intent i = new Intent(Intent.ACTION_VIEW);
//i.setData(Uri.parse(url));
//Intent zipActivity = new DownloadZip();
//zipActivity.start...;
//Toast.makeText(getContext(), "Downloading " + pos, Toast.LENGTH_SHORT).show();
}
});
viewHolder.btnDetails = (Button) row.findViewById(R.id.btnDetails);
viewHolder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Integer pos = (Integer) v.getTag();
//Log.i("AtlantisSites", "getView pos = " + pos);
getItemId(pos);
if(frameLayout.getVisibility()==View.GONE){
showFrameLayout();
} else {
hideFrameLayout();
}
}
});
row.setTag(viewHolder);
} else{
viewHolder = (ViewHolder) row.getTag();
}
//Get our View References
final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
TextView nameTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView titleTxt = (TextView)row.findViewById(R.id.titleTxt);
//Button btnDownload = (Button)row.findViewById(R.id.btnDownload);
TextView summaryIta = (TextView)row.findViewById(R.id.textViewSummaryItaRow);
TextView summaryEng = (TextView)row.findViewById(R.id.textViewSummaryEngRow);
TextView priceItaTxt=(TextView)row.findViewById(R.id.txtViewPriceIta);
TextView priceEngTxt=(TextView)row.findViewById(R.id.txtViewPriceEng);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
frameLayout = (FrameLayout)row.findViewById(R.id.frame_layout_listview);
//Set the relavent text in our TextViews
nameTxt.setText(getItem(pos).getName());
titleTxt.setText(getItem(pos).getTitle());
summaryIta.setText(getItem(pos).getSummaryIta());
summaryEng.setText(getItem(pos).getSummaryEng());
viewHolder.btnDetails.setTag(pos);
return row;
}
public class ViewHolder{
Button btnDownload;
Button btnDetails;
}
private void showFrameLayout(){
frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
frameLayout.setVisibility(View.VISIBLE);
}
private void hideFrameLayout(){
frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
frameLayout.setVisibility(View.GONE);
}
}
Something goes wrong with the position.
please help me to find error o solutions.
thanks
in the method showFrameLayout() you dont have any reference to the current frame layout you want to show, remove the methods show/hide frameLayout and inside the listener for the details btn
viewHolder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Integer pos = (Integer) v.getTag();
//Log.i("AtlantisSites", "getView pos = " + pos);
getItemId(pos);
FrameLayout detailsFrame = row.findViewById(R.id.frame_layout_listview);
if(detailsFrame.getVisibility()==View.GONE){
detailsFrame.setVisibility(View.VISIBLE);
} else {
detailsFrame.setVisibility(View.GONE);
}
}
});
As a general suggestion i would put my FrameLayout inside the viewholder, wich is exactly whats for.
I found the solution . I have to declare the Frame Layout final. It works
final FrameLayout detailsFrame = (FrameLayout)row.findViewById(R.id.frame_layout_listview);

Android ListView items disappear when scrolling

I've loaded some pictures into a ListView using an adapter. When a user clicks on any row of the list I'm showing a checkmark at the end:
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
List<String> names,facebookbid;
String sent;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, List<String> n,List<String> fid,String s) {
activity = a;
names=n;
facebookbid=fid;
sent=s;
inflater = (LayoutInflater)activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),"p");
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
public int getCount() {
return facebookbid.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public class ViewHolder{
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
convertView=null;
final ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = inflater.inflate(R.layout.planners_friends_listrow, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView)convertView.findViewById(R.id.planner_friend_image);
holder.checkmark=(ImageView)convertView.findViewById(R.id.checkmark);
holder.friendsrow=(RelativeLayout)convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag( holder );
}
else
holder=(ViewHolder)convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if(sent.equals("planners"))
{link=facebookbid.get(position);
}
else
{
link="https://graph.facebook.com/"+facebookbid.get(position)+"/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a=isNetworkConnected();
if(a==true)
{
if(sender.equals("settings"))
{
}
else if(sender.equals("savethedate"))
{
if(sid.contains(facebookbid.get(position)))
{
if(sid.contains("_"))
{
sid=sid.replace("_"+facebookbid.get(position), "");
}
else
{
sid=sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size()-1);
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.GONE);
}
else
{
if(sid.isEmpty())
{
sid=sid+facebookbid.get(position);
}
else
{
sid=sid+"_"+facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.VISIBLE);
}
}
else
{
String friendname=names.get(position);
String friendid=facebookbid.get(position);
String friendgender=gender.get(position);
Intent resultIntent = new Intent(Friends.this,Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if(sender.equals("planner"))
{
resultIntent.putExtra("plannerid",friendid);
resultIntent.putExtra("imageurl","https://graph.facebook.com/"+friendid+"/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
else
{
resultIntent.putExtra("plannerid","");
resultIntent.putExtra("imageurl","");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet connection",Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The problem is: When the ListView is scrolled, the checkmark icon simply disappears. What am I doing wrong?
Looking at your code you set the Visibility of the checkmark when the user clicks on one of the items which then shows / hides the item. Now when the user scrolls the items are recycled and you dont have any code to check if the item has been checked or not.
So in short you need something that basically says
if (checked) {
//set visibility of the checkmark to visible
} else {
//set visibility of the checkmark to gone
}
First you need to change getView method as don't reinitialize convertView as null remove below line from getView
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
List<String> names, facebookbid;
String sent;
public ImageLoader imageLoader;
private int size = 0;
private HashMap<String, Boolean> mapClickStatus;
public LazyImageLoadAdapter(Activity a, List<String> n, List<String> fid, String s) {
activity = a;
names = n;
facebookbid = fid;
sent = s;
mapClickStatus = new HashMap<String, Boolean>();
if (facebookbid != null)
size = facebookbid.size();
// Give total size of the list item to getCount method
imageLoader = new ImageLoader(activity, "p");
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
/*********
* Create a holder Class to contain inflated xml file elements
*********/
public class ViewHolder {
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// convertView=null;
//It should not be null every time
final ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView) convertView.findViewById(R.id.planner_friend_image);
holder.checkmark = (ImageView) convertView.findViewById(R.id.checkmark);
holder.friendsrow = (RelativeLayout) convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if (sent.equals("planners")) {
link = facebookbid.get(position);
} else {
link = "https://graph.facebook.com/" + facebookbid.get(position) + "/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
// set the visibility of CheckMark ImageView based on the click status.
if (mapClickStatus.get(facebookbid.get(position)))
holder.checkmark.setVisibility(View.VISIBLE);
else
holder.checkmark.setVisibility(View.GONE);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a = isNetworkConnected();
/// I dont know about the unique ID field in this so i took facebookbid.get(position) as a key
// To set click status of row item in hashmap.
mapClickStatus.put(facebookbid.get(position),
mapClickStatus.containsKey(facebookbid.get(position)) ? false : true);
if (a == true) {
if (sender.equals("settings")) {
} else if (sender.equals("savethedate")) {
if (sid.contains(facebookbid.get(position))) {
if (sid.contains("_")) {
sid = sid.replace("_" + facebookbid.get(position), "");
} else {
sid = sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size() - 1);
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.GONE);
} else {
if (sid.isEmpty()) {
sid = sid + facebookbid.get(position);
} else {
sid = sid + "_" + facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.VISIBLE);
}
// TO refresh view with updated checkmark status
notifyDataSetChanged();
} else {
String friendname = names.get(position);
String friendid = facebookbid.get(position);
String friendgender = gender.get(position);
Intent resultIntent = new Intent(Friends.this, Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if (sender.equals("planner")) {
resultIntent.putExtra("plannerid", friendid);
resultIntent.putExtra("imageurl", "https://graph.facebook.com/" + friendid + "/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
} else {
resultIntent.putExtra("plannerid", "");
resultIntent.putExtra("imageurl", "");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
} else {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Suggestions
Inflate layout with parent attaching like below
.
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
Avoid mantaining status by using multiple collection(Arraylist or
like that to display data) use Model Class or JSON or Arraylist of
map etc.

delete item in listview using the delete button when checkbox is checked using cursoradapter

I'm having a problem with this. I am using cursor adaptor. What my problem is when the checkbox is checked it will get the value and then when a button is clicked the data will be deleted. By the way I am displaying the checkbox with listview.
public class ListViewAdapter extends CursorAdapter {
SparseBooleanArray sba = new SparseBooleanArray();
public ListViewAdapter (Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.custom_dialog_box, parent, false);
ViewHolder holder = new ViewHolder();
holder.textView = (TextView) retView.findViewById(R.id.number);
holder.cb = (CheckBox) retView.findViewById(R.id.checkBox1);
retView.setTag(holder);
return retView;
}
private static class ViewHolder {
TextView textView;
CheckBox cb;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
final int position = cursor.getPosition();
final CheckBox CheckBoxPersonName = (CheckBox) view.findViewById(R.id.checkBox1);
CheckBoxPersonName.setTag(cursor);
CheckBoxPersonName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
sba.put(position, true);
}
else {
sba.put(position, false);
}
}
});
CheckBoxPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view.findViewById(R.id.number);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}
}
Here is my mainActivity where the button will be clicked.
public class TemplateActivity extends Activity {
CheckBox cb;
Button btnSort, btnDel;
private ListViewAdapter listAdapter;
private RetailerDatabaseHelper dbHelper;
private ListView listView;
private static final String TAG = TemplateActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_template);
btnSort = (Button) findViewById(R.id.btnSort);
btnDel = (Button) findViewById(R.id.btnDelete);
dbHelper = new RetailerDatabaseHelper(this);
listView = (ListView) findViewById(R.id.listViewData);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Control: " + listView.getCheckedItemPositions());
Cursor c = (Cursor) parent.getAdapter().getItem(position);
String name = c.getString(1);
String number = c.getString(2);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(TemplateActivity.this);
alertDialog.setTitle("RETAILER");
alertDialog.setMessage("Are you sure you want to send " + name + " load to " + number + " ?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//insertData(textVal, value);
dialog.dismiss();
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
btnDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = listView.getAdapter().getCount();
SparseBooleanArray array = listView.getCheckedItemPositions(); /* 11/07/15 */
System.out.println("Count: "+ count);
/* 11/07/15 */
for(int x = 0; x < array.size(); x++)
{
if(array.get(x)) /* 11/07/15 */
{
Log.d(TAG, "Checked: " + listView.getTag());
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
listAdapter.notifyDataSetChanged();
}
}
});
It is working but when the listview data is not clicked the checkbox value is not displaying.
You are declaring SparseBooleanArray as null here:
SparseBooleanArray array = null;
and no assignment to array.. and you are using it in for loop, then it will definitely give you null reference error.

Android custom list view data is not updating while using shared preference

I am trying to get the value from shared preference and display it in customized list view. But the problem is list view is not getting updated with second value, means first time it's perfectly working fine but second time it overwrites the first value or may be it is opening another screen and displaying over there.
I want to add all the shared preferences data in list view one by one. please help me to solve this. Following is my code.
ListModel.java
public class ListModel {
private String Title = "";
private String Description = "";
/*********** Set Methods ******************/
public void setTitle(String Title) {
this.Title = Title;
}
public void setDescription(String Description) {
this.Description = Description;
}
/*********** Get Methods ****************/
public String getTitle() {
return this.Title;
}
public String getDescription() {
return this.Description;
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList<?> data;
private static LayoutInflater inflater = null;
public Resources res;
ListModel tempValues = null;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList<?> d, Resources resLocal) {
/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView textViewTitle;
public TextView textViewDescr;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.displaydata, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.textViewTitle = (TextView) vi.findViewById(R.id.title);
holder.textViewDescr = (TextView) vi.findViewById(R.id.description);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
if (data.size() <= 0) {
holder.textViewTitle.setText("No Data");
} else {
/***** Get each Model object from Arraylist ********/
tempValues = null;
tempValues = (ListModel) data.get(position);
/************ Set Model values in Holder elements ***********/
holder.textViewTitle.setText(tempValues.getTitle());
holder.textViewDescr.setText(tempValues.getDescription());
// holder.image.setImageResource(res.getIdentifier(
// "com.androidexample.customlistview:drawable/"
// + tempValues.getImage(), null, null));
/******** Set Item Click Listner for LayoutInflater for each row *******/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked=====");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener {
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View arg0) {
Assignment sct = (Assignment) activity;
sct.onItemClick(mPosition);
}
}
}
Class Which reads shared preferencedata
public class Assignment extends Activity {
ListView list;
ImageView imageView;
CustomAdapter adapter;
public Assignment CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment);
imageView = (ImageView) findViewById(R.id.createassignment);
list = (ListView) findViewById(R.id.displaydata);
CustomListView = this;
setListData();
Resources res = getResources();
adapter = new CustomAdapter(CustomListView, CustomListViewValuesArr,
res);
list.setAdapter(adapter);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Assignment.this,
Assignment_Create.class);
startActivity(intent);
}
});
}
public void setListData() {
final ListModel sched = new ListModel();
/******* Firstly take data in model object ******/
sched.setTitle("Title : "
+ PreferenceConnector.readString(this,
PreferenceConnector.TITLE, null));
sched.setDescription("Description : "
+ PreferenceConnector.readString(this,
PreferenceConnector.DESC, null));
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
}
public void onItemClick(int mPosition) {
ListModel tempValues = (ListModel) CustomListViewValuesArr
.get(mPosition);
Toast.makeText(
CustomListView,
"" + tempValues.getTitle() + "" + ""
+ tempValues.getDescription(), Toast.LENGTH_LONG)
.show();
}
}
This function shows how i am writing data in shared Preference
public void sharedPrefernces() {
if (Code.title != null)
PreferenceConnector.writeString(this, PreferenceConnector.TITLE,
Code.title);
if (Code.description != null)
PreferenceConnector.writeString(this, PreferenceConnector.DESC,
Code.description);
}
In setListData() you're only adding 1 item to the Adapter, so the listView is not going to have the 2nd item shown.

Categories