Pass data in other activity - java

I have to pass my value from one activity to other one.
I download data from database with Json and it works propelly.
My First Activity:
public class ListAdapter extends BaseAdapter
{
Context context;
List<cources> valueList;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListAdapter(List<cources> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.list_adapter_view_test, null);
viewItem.txtTitle = (TextView)convertView.findViewById(R.id.nome_prodotto);
viewItem.txtDescription = (TextView)convertView.findViewById(R.id.descrizione_prodotto);
viewItem.txtPrice = (TextView)convertView.findViewById(R.id.prezzo);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.txtPrice.setText(valueList.get(position).prezzo_prodotto);
viewItem.txtTitle.setText(valueList.get(position).nome_prodotto);
viewItem.txtDescription.setText(valueList.get(position).descrizione_prodotto);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Intent intent = new Intent(context, Dettaglio_Prodotto.class);
// Pass all data country
intent.putExtra("nome_prodotto", "test");
// Start SingleItemView Class
context.startActivity(intent);
}
});
return convertView;
}
}
class ViewItem
{
TextView txtTitle;
TextView txtDescription;
TextView txtPrice;
}
I have to pass the value of:
viewItem.txtPrice.setText(valueList.get(position).prezzo_prodotto);
My Second Activity i have the code:
Intent i = getIntent();
nome_prodotto = i.getStringExtra("nome_prodotto");
How i can do it?
if i put:
intent.putExtra("nome_prodotto",viewItem.txtTitle.setText(valueList.get(position).nome_prodo‌​tto));
i have the error:
Variable is accessed within inner class. Needs to be declared final

Suggestion: Use an ArrayAdapter rather than BaseAdapter if you are using List data anyway.
As the IDE indicates, make a final variable.
...
else
{
viewItem = (ViewItem) convertView.getTag();
}
// This is the item in the current position
final cources item = (cources) getItem(position);
Then, you can use that instead of repeatedly calling valueList.get(position)
viewItem.txtPrice.setText(item.prezzo_prodotto);
viewItem.txtTitle.setText(item.nome_prodotto);
viewItem.txtDescription.setText(item.descrizione_prodotto);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Intent intent = new Intent(context, Dettaglio_Prodotto.class);
// Pass all data country
intent.putExtra("nome_prodo‌​tto", item.nome_prodo‌​tto);
// Start SingleItemView Class
context.startActivity(intent);
}
});

When you use valueList in a method that creates a new onTouchListener for an instance, that is an inner class.
Any variables accessed by that class has to be final or declared inside the class. Meanign if you create a new int inside the inner class, that doesn
t have to be final. But if the int is declared outside, it has to be final.
In your case, the variable position has to be marked as final

I guess you're trying to do something like this
intent.putExtra("nome_prodotto", valueList.get(position).prezzo_prodotto);
The method putExtra expects a key (String) and a value (in your case you're passing a string value).

Related

Android: Sending a cardview from one fragment to another

I need some help for a summer project
This is my Events fragment
This is my MyList fragment
I'm using a RecyclerView+Cardview to display the Events. The idea is that the user can click the big plus on the right side of each card, and the card would be displayed in the MyList fragment. I would like to ask if it's possible to transfer a card directly from one fragment to another? Also, both fragments are contained within the same activity, which makes it a little trickier(I haven't found any available solutions).
If that is not possible, another way is to transfer the reference type object contained in the CardView to the MyList fragment. However, this is even less straightforward. This is because the button is inflated in the adapter, but there is no reference type object created here. I have seen many tutorials on using the Parcelable interface, however, I don't know how to implement it here when I'm unable to even create the object in the adapter. The reference object is created in another activity and stored in Firebase before it is read and displayed.
I'm going to attach my EventsAdapter.java and EventsItem.java and EventsFragment.java code below, but please let me know if I should include more code to describe the problem.
Thanks for reading my very long post!!
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsViewHolder> implements Filterable {
private ArrayList<EventsItem> mEventsList;
private ArrayList<EventsItem> mEventsListFull;
private EventsAdapter.OnItemClickListener mListener;
private Context mContext;
private DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK);
public interface OnItemClickListener {
void onItemClick(int position);
}
//the ViewHolder holds the content of the card
public static class EventsViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ImageView mAddButton;
public TextView mTextView1;
public TextView mTextView2;
public TextView mTextView3;
public TextView mTextView4;
public TextView mTextView5;
public EventsViewHolder(Context context, View itemView, final EventsAdapter.OnItemClickListener listener) {
super(itemView);
final Context context1 = context;
mImageView = itemView.findViewById(R.id.imageView);
mAddButton = itemView.findViewById(R.id.image_add);
mTextView1 = itemView.findViewById(R.id.title);
mTextView2 = itemView.findViewById(R.id.event_description);
mTextView3 = itemView.findViewById(R.id.date);
mTextView4 = itemView.findViewById(R.id.location);
mTextView5 = itemView.findViewById(R.id.time);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str1 = mTextView1.getText().toString();
String str2 = mTextView2.getText().toString();
String str3 = mTextView3.getText().toString();
String str4 = mTextView4.getText().toString();
String str5 = mTextView5.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("title", str1);
bundle.putString("event description", str2);
bundle.putString("date", str3);
bundle.putString("location", str4);
bundle.putString("time", str5);
MylistFragment mlf = new MylistFragment();
mlf.setArguments(bundle);
}
});
}
}
//Constructor for EventsAdapter class. This ArrayList contains the
//complete list of items that we want to add to the View.
public EventsAdapter(Context context, ArrayList<EventsItem> EventsList) {
mEventsList = EventsList;
mContext = context;
mEventsListFull = new ArrayList<>(EventsList); // copy of EventsList for SearchView
}
//inflate the items in a EventsViewHolder
#NonNull
#Override
public EventsAdapter.EventsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_item, parent, false);
EventsAdapter.EventsViewHolder evh = new EventsAdapter.EventsViewHolder(mContext, v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventsAdapter.EventsViewHolder holder, int position) {
EventsItem currentItem = mEventsList.get(position);
holder.mImageView.setImageResource(currentItem.getProfilePicture());
holder.mTextView1.setText(currentItem.getTitle());
holder.mTextView2.setText(currentItem.getDescription());
holder.mTextView3.setText(df.format(currentItem.getDateInfo()));
holder.mTextView4.setText(currentItem.getLocationInfo());
holder.mTextView5.setText(currentItem.getTimeInfo());
}
#Override
public int getItemCount() {
return mEventsList.size();
}
public class EventsItem implements Occasion, Parcelable {
//fields removed for brevity
//constructor removed for brevity
}
public EventsItem() {
}
public EventsItem(Parcel in) {
profilePicture = in.readInt();
timeInfo = in.readString();
hourOfDay = in.readInt();
minute = in.readInt();
locationInfo = in.readString();
title = in.readString();
description = in.readString();
}
public static final Creator<EventsItem> CREATOR = new Creator<EventsItem>() {
#Override
public EventsItem createFromParcel(Parcel in) {
return new EventsItem(in);
}
#Override
public EventsItem[] newArray(int size) {
return new EventsItem[size];
}
};
//getter methods have been removed for brevity
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(profilePicture);
dest.writeString(timeInfo);
dest.writeString(locationInfo);
dest.writeString(title);
dest.writeString(description);
dest.writeString(df.format(dateInfo));
dest.writeInt(hourOfDay);
dest.writeInt(minute);
}
}
public class EventsFragment extends Fragment {
ArrayList<EventsItem> EventsItemList;
FirebaseDatabase mDatabase;
DatabaseReference mDatabaseReference;
ValueEventListener mValueEventListener;
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private EventsAdapter mAdapter;
private View rootView;
public FloatingActionButton floatingActionButton;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_events, container, false);
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference().child("Events");
createEventsList();
buildRecyclerView();
floatingActionButton = rootView.findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), EventsAdder.class);
startActivity(intent);
}
});
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
EventsItemList.add(snapshot.getValue(EventsItem.class));
}
EventsAdapter eventsAdapter = new EventsAdapter(getActivity(), EventsItemList);
mRecyclerView.setAdapter(eventsAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
mDatabaseReference.addValueEventListener(mValueEventListener);
setHasOptionsMenu(true);
Toolbar toolbar = rootView.findViewById(R.id.events_toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
return rootView;
}
public void createEventsList() {
EventsItemList = new ArrayList<>();
}
public void buildRecyclerView() {
mRecyclerView = rootView.findViewById(R.id.recyclerview);
mLayoutManager = new LinearLayoutManager(getContext());
mAdapter = new EventsAdapter(getActivity(), EventsItemList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
}
If you would like to see the same CardView within the MyListFragment, you could have the MyListFragment contain a RecyclerView, and reuse the same EventsAdapter and EventsViewHolder. The only difference is that rather than populating the adapter with all the children of the "Events" from your database, you would only populate it with the single Event that you want.
Also, since you have made your Event class implement parcelable, you do not need to manually create the bundle when clicking the plus button.
I am assuming you have a single Activity, and you simply want to replace the EventsFragment with the MyListFragment. Checkout the docs for replacing one fragment with another.
Step 1:
Extend your onItemClickListener to look like:
public interface OnItemClickListener {
void onItemClick(int position);
void onPlusButtonClick(int position);
}
and adjust the code in your EventsViewHolder constructor to look like this when the plus button is clicked:
mAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
// no need to manually create the bundle here
// you already have all the information you need
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onPlusButtonClick(position);
}
}
}
});
Step 2:
Implement our new method onPlusButtonClick. As per our discussion in the comments, it seems you do not implement this interface anywhere. You can implement it inside the constructor to your EventsAdapter:
public EventsAdapter(Context context, ArrayList<EventsItem> EventsList) {
mEventsList = EventsList;
mContext = context;
mEventsListFull = new ArrayList<>(EventsList); // copy of EventsList for SearchView
mListener = new OnItemClickListener() {
#Override
public void onItemClick() {
// handle clicking the entire view holder
// NOTE: inside your EventsViewHolder, it looks like you call this method on the entire itemView. This could 'swallow' the click on the plus button. You may need to adjust your code to handle this.
}
#Override
public void onPlusButtonClick(int position) {
MyListFragment myListFragment = new MyListFragment();
Event event = mEventsList.get(position);
Bundle bundle = new Bundle();
bundle.putExtra("event", event); // this will work due to implementing parcelable
myListFragment.setArguments(bundle);
// use mContext since im assuming we areinside adapter
// if in an Activity, no need to use context to get the fragment manager
FragmentTransaction transaction = mContext.getSupportFragmentManager().beginTransaction();
// Replace the EventsFragment with the MyListFragment
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, myListFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
Step 3:
Inside your MyListFragments onCreateView() method:
#Override
public View onCreateView (
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState
) {
Bundle bundle = getArguments();
Event event = bundle.getExtra("event"); // again, will work due to implementing parcelable
// from here you should bind to a recycler view, and you can even reuse your adapter like so:
List<EventsItem> singleEventList = new List<EventsItem>();
singleEventList.add(event);
EventsAdapter adapter = new EventsAdapter(getActivity(), singleEventList);
// be sure to inflate and return your view here...
}
and you should be good to go!
I have left out bits of code here and there for simplicity.. but I hope this is understandable.
As a side note.. in your firebase database listener, it is bad practice to create a new EventsAdapter every single time your data is updated. Instead, you should update the data in the adapter with the new values. Do this by creating a public method inside the adapter such as replaceEvents(List<EventsItem> newEvents), and inside, replace mEventsList with the new events, then call notifyDataSetChanged().

How to fix Android Java ListView Adapter

I need help to fix the following problem:
When i scroll down my ListView Adapter the list that contains the country change to only one country.
This is my Adapter:
public class Nraeby_ListViewAdapter extends BaseAdapter {
private String Liked;
Context mContext;
// Declare Variables
LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public Nraeby_ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.data = arraylist;
mContext = context;
imageLoader = new ImageLoader(mContext);
inflater = LayoutInflater.from(mContext);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
// Declare Variables
TextView rank;
TextView country;
TextView population;
test.Droidlogin.CircleImage flag;
test.Droidlogin.material.AnimateCheckBox checkBox;
ImageButton btnFavourite;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.nearby_listview_item, null);
// Get the position
resultp = data.get(position);
// Locate the TextViews in nearby_listview_item.xmltem.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
// Locate the ImageView in nearby_listview_item.xmltem.xml
holder.flag = (test.Droidlogin.CircleImage) view.findViewById(R.id.flag);
holder.checkBox = (test.Droidlogin.material.AnimateCheckBox) view.findViewById(R.id.checkbox);
holder.btnFavourite = (ImageButton) view.findViewById(R.id.like);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set results to the TextViews
holder.rank.setText(resultp.get(NearbyUsers.RANK));
holder.country.setText(resultp.get(NearbyUsers.COUNTRY));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(NearbyUsers.FLAG), holder.flag);
TinyDB tinydb = new TinyDB(mContext);
Liked = tinydb.getString("MyUsers");
//This handle and change icon when click on.
holder.btnFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TinyDB tinydb = new TinyDB(mContext);
holder.btnFavourite.setImageResource(R.drawable.icon_liked);
tinydb.putString("MyUsers",resultp.get(NearbyUsers.COUNTRY));
holder.btnFavourite.setImageResource(R.drawable.icon_liked);
}
});
// Capture ListView item click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
Intent intent = new Intent(mContext, SingleItemViewNearbyProfile.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(NearbyUsers.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(NearbyUsers.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(NearbyUsers.POPULATION));
// Pass all data flag
intent.putExtra("flag", resultp.get(NearbyUsers.FLAG));
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
}
pls i need help on how to fix the error
so that when scroll down it will show the list of all country and a button
You should move the line in getView to outside the if block. Like this
final ViewHolder holder;
resultp = data.get(position);
if (view == null) {
///
}
You are only updating the resultp when you create a new view. For a recycled view, you are using a stale data and that's the reason you see some incorrect country data after you scroll.

Android viewholder class wide scope

I have a list adapter using a viewholder pattern, my problem is I need to update a TextView from the viewholder in onpostexecute() of an AsyncTask contained within the same class, but this always returns a nullpointer on the TextView, how can give my textviews from the viewholder enough scope that I can change them in teh AsyncTask? I will include a code example below, thanks in adcvance
public class ListAdapter extends BaseAdapter {
TextView tvA1, tvA2;
Integer submitId;
String submitQuestion;
public ListAdapter() {
....
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
friendsViewHolder holder = null;
if (convertView == null) {
holder = new friendsViewHolder();
convertView = inflater.inflate(R.layout.list_item_status, null);
holder.tvA1 = (TextView) convertView
.findViewById(R.id.tvA1);
holder.tvA2 = (TextView) convertView
.findViewById(R.id.tvA2);
holder.btQ1 = (LinearLayout) convertView
.findViewById(R.id.btConfirm);
holder.btQ2 = (LinearLayout) convertView
.findViewById(R.id.btDeny);
convertView.setTag(holder);
} else {
holder = (friendsViewHolder) convertView.getTag();
}
tvA1 = holder.tvA1;
tvA2 = holder.tvA2;
holder.btQ1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitId = id;
submitQuestion = q1;
new UpdateAnswer().execute();
}
});
holder.btQ2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitId = id;
submitQuestion = q2;
new UpdateAnswer().execute();
}
});
return convertView;
}
static class friendsViewHolder {
TextView tvA1, tvA2;
LinearLayout btQ1, btQ2;
}
private class UpdateAnswer extends AsyncTask<Void, Void, ArrayList<Object>> {
#Override
protected ArrayList<Object> doInBackground(Void... params) {
return apiHelper.submitAnswer(submitId, submitQuestion);
}
#Override
protected void onPostExecute(ArrayList<Object> answers) {
super.onPostExecute(answers);
if (answers != null) {
Integer a1 = (Integer) answers.get(1);
Integer a2 = (Integer) answers.get(2);
//Error here
tvA1.setText(a1);
tvA1.setVisibility(View.VISIBLE);
//error here
tvA2.setText(a2);
tvA2.setVisibility(View.VISIBLE);
}
}
}
}
Lets change few things here and there :)
Lets make friendsViewHolder public, also i need to add that in java it is somehow custom to name classes with names starting with cammel case simply put FirstLetterOfEeachWordIsBig :)
Lets add constructor to Update task :)
private class UpdateAnswer extends AsyncTask<Void, Void, ArrayList<Object>> {
int submitId;
String submitQuestion;
friendsViewHolder holder;
public UpdateAnswer (int submitId, String submitQuestion, friendsViewHolder holder) {
this.submitId = submitId;
this.submitQuestion = submitQuestion;
this.holder = holder;
}
On click lets change to
final frendsViewHolder finalHolder = holder;
holder.btQ1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new UpdateAnswer(id, q1, finalHolder).execute();
}
});
We are no longer in need of global TvA1, tvA2, submitId, submitQuestion;
And lastly we need to edit onPostExecute, hovewer i think that want be so hard since you have holder value forwarded :)
holder.tvA1.setText(a1);
holder.tvA1.setVisibility(View.VISIBLE);
holder.tvA2.setText(a2);
holder.tvA2.setVisibility(View.VISIBLE);
In java you can create constructor to allow passing additional data to object, we use this to set id, question and holder for our task, and for passing that information to other object we should'nt be using global values (they can be changed by every process), think about situation when your call "apiHelper.submitAnswer(submitId, submitQuestion)" would take long to proceed (half a second for example), then user click within half a second on answer in first and answer c on 3 question, by passing values globally you cant determine wich answer to accept :)
Cheers :)
Java is pass by value, but you can send reference of an Object in the value. I have used the above, and sent reference of holder to AsyncTask.
public class ListAdapter extends BaseAdapter {
TextView tvA1, tvA2;
Integer submitId;
String submitQuestion;
public ListAdapter() {
....
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
friendsViewHolder holder = null;
if (convertView == null) {
holder = new friendsViewHolder();
convertView = inflater.inflate(R.layout.list_item_status, null);
holder.tvA1 = (TextView) convertView
.findViewById(R.id.tvA1);
holder.tvA2 = (TextView) convertView
.findViewById(R.id.tvA2);
holder.btQ1 = (LinearLayout) convertView
.findViewById(R.id.btConfirm);
holder.btQ2 = (LinearLayout) convertView
.findViewById(R.id.btDeny);
convertView.setTag(holder);
} else {
holder = (friendsViewHolder) convertView.getTag();
}
holder.btQ1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitId = id;
submitQuestion = q1;
new UpdateAnswer(holder).execute();
}
});
holder.btQ2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitId = id;
submitQuestion = q2;
new UpdateAnswer().execute();
}
});
return convertView;
}
static class friendsViewHolder {
TextView tvA1, tvA2;
LinearLayout btQ1, btQ2;
}
private class UpdateAnswer extends AsyncTask<Void, Void, ArrayList<Object>> {
friendsViewHolder holder;
UpdateAnswer(friendsViewHolder holder)
{
this.holder = holder;
}
#Override
protected ArrayList<Object> doInBackground(Void... params) {
return apiHelper.submitAnswer(submitId, submitQuestion);
}
#Override
protected void onPostExecute(ArrayList<Object> answers) {
super.onPostExecute(answers);
if (answers != null) {
Integer a1 = (Integer) answers.get(1);
Integer a2 = (Integer) answers.get(2);
//Error here
holder.tva1.setText(a1);
holder.tva1.setVisibility(View.VISIBLE);
//error here
holder.tva2.setText(a2);
holder.tva2.setVisibility(View.VISIBLE);
}
}
}
}

ImageButton onclick in PagerAdapter. Need to go to another class/XML file. ERROR

Been researching around this for a while and can't seem to find any solutions.
I have a 5 images that is in a PagerLayout swipe format.
What I want to do is upon clicking an image, I want to go to another XML file/class.
Code: (I've commented out methods I have tried.)
public class CustomSwipeAdapter extends PagerAdapter {
Context context;
private int[] image_resources = {R.drawable.chestpress,R.drawable.deadlift,R.drawable.squat,R.drawable.pullups,R.drawable.dips};
private Context ctx; //Gets the context of a current state or application. Tells program what is going on somewhere else.
private LayoutInflater layoutInflater; //USed to instantiate layout XML files to View Objct.
private LayoutInflater inflater;
private String[] names = {"Dumbell Press","Deadlift","Squats","Pullups","Tricep Dips"};
public ImageView imageView;
Activity activity;
View views = null;
public CustomSwipeAdapter(Context ctx){
this.ctx = ctx;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view==(LinearLayout)o;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
imageView = (ImageView)item_view.findViewById(R.id.image_view);
TextView textView = (TextView)item_view.findViewById(R.id.image_count);
imageView.setImageResource(image_resources[position]);
textView.setText(names[position]);
container.addView(item_view);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(position == 0) {
Log.d("Exercise","Dumbell Press");
//Intent intent = new Intent(ctx,MyActivity.class);
//Intent intent = new Intent(CustomSwipeAdapter.this,MyActivity.class);
//Intent intent = new Intent(context,MyActivity.class);
//views = inflater.inflate(R.layout.main,null);
//context.startActivity(intent);
//MyActivity koo = new MyActivity(); (Tried just instantiating another class (Im so lost)
}
if(position == 1){
Log.d("Exercise","Deadlift!");
}
if(position == 2){
Log.d("Exercise","Squats");
}
}
});
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
Very new android/java programmer. Thanks for reading.
Try this:
Intent intent = new Intent(CustomSwipeAdapter.this.ctx, MyActivity.class);
CustomSwipeAdapter.this.ctx.startActivity(intent);
Also make sure to pass the correct context to your Adapter constructor. The context you will pass can be the activity itself.
So, on your Activity, when you need to create a new adapter, do it like:
CustomSwipeAdapter myAdapter = new CustomSwipeAdapter(this);
Where this is the Activity on which you are creating the adapter.
If you need to create the adapter inside a fragment, just get the activity with:
MyFragment.getActivity();
Lastly, if you are wondering: "why does that work? It expects a Context and I'm passing an activity!".
Here's a short answer:
Activity inherits context. Thus, if you are in an activity, you only
need to pass itself to use the context. It also contains a pointer to
getBaseContext(). You might occasionally need to reference that, if
you need the entire application context, but most likely you won't for
a while.
Hope this helps.
Let me know if you get any more errors (don't forget to post your logcat so we can help you better).
What you should ideally be doing is this,
1: Create an interface call it swipeAdapterCallback or something, declare a method for handling the onClick
2: Make sure you get the swipeAdapterCallback instance in the constructor.
3: Then all you have to do is invoke the onClick method in the callback instance.
I've posted the adapter code here:
public class CustomSwipeAdapter extends PagerAdapter {
Context context;
private int[] image_resources = {R.drawable.chestpress, R.drawable.deadlift, R.drawable.squat, R.drawable.pullups, R.drawable.dips};
private Context ctx; //Gets the context of a current state or application. Tells program what is going on somewhere else.
private LayoutInflater layoutInflater; //USed to instantiate layout XML files to View Objct.
private LayoutInflater inflater;
private String[] names = {"Dumbell Press", "Deadlift", "Squats", "Pullups", "Tricep Dips"};
public ImageView imageView;
Activity activity;
View views = null;
private swipeAdapterCallback mCallback;
public CustomSwipeAdapter(Context ctx,swipeAdapterCallback callback) {
this.ctx = ctx;
this.mCallback = callback;
}
#Override
public int getCount() {
return image_resources.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == (LinearLayout) o;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout, container, false);
imageView = (ImageView) item_view.findViewById(R.id.image_view);
TextView textView = (TextView) item_view.findViewById(R.id.image_count);
imageView.setImageResource(image_resources[position]);
textView.setText(names[position]);
container.addView(item_view);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onImageClick(position);
}
});
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
public interface swipeAdapterCallback {
void onImageClick(int position);
}
}
Then in your activity what you do is implement this interface and handle the onClick in the onImageClick function like so
#Override
public void onImageClick(int position) {
//handle intents and launching activities here.
switch(position){
case 0:
Log.d("Exercise","Dumbell Press");
Intent intent = new Intent(this,exampleAcitivity.class);
startActivity(intent);
break;
case 1:
Log.d("Exercise","Deadlift!");
break;
case 3:
Log.d("Exercise","Squats");
break;
}
}
Since this block of code will be inside your Activity class creating intents and starting new activities handling result from these actitivities become very simple

Checkbox data not passing in other activity

I am trying to pass the position of checkbox present in my listview to another activity with the help of an intent. But it shows me null at another activity. Or can someone tell me how can i pass the selected checkbox data to another activity using the code below?
I want to store value in an array from the listview of the respective check box. and then transfer to another activity
public class MyAdapter extends ArrayAdapter<Model> {
int getPosition;
Intent in;
private final List<Model> list;
public final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView
.findViewById(R.id.check);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getPosition = (Integer) buttonView.getTag(); // setTag.
}
});
convertView.setTag(viewHolder);
convertView.setOnClickListener(new MyCustomItemClickListener(getPosition));
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.check, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
class MyCustomItemClickListener implements OnClickListener {
MyCustomItemClickListener(int getPositionx) {
/*
* Whatever initialization you need can be done here. You can pass
* values in constructor when calling it from getview and use with
* intent extras
*/
in = new Intent(context, YourActivity.class);
in.putExtra("aa", getPositionx);
}
#Override
public void onClick(View arg0) {
// Launch Activity
context.startActivity(in);
}
}
}
try it out as Below way. No Need to Pass getPositionx inside Constructor as you have already define it globally in your class.
class MyCustomItemClickListener implements OnClickListener {
MyCustomItemClickListener() {
/*
* Whatever initialization you need can be done here. You can pass
* values in constructor when calling it from getview and use with
* intent extras
*/
}
#Override
public void onClick(View arg0) {
// Launch Activity
in = new Intent(context, YourActivity.class);
in.putExtra("aa", getPositionx);
context.startActivity(in);
}
}
and Change your Initialization to
convertView.setOnClickListener(new MyCustomItemClickListener());
Declear getPosition as a static variable and you can access
the value MyAdapter.getPosition to the another activity
public static getPosition;
and the activity where you want to access this variable
MyAdapter.getPosition use this.
but the way you are passing the value that is also wright but before passing
it to the intent check weather your value is not null,in this case
getPosition = (Integer) buttonView.getTag();
is not able to get the values.

Categories

Resources