Click Listeners to RecyclerView [duplicate] - java

This question already has answers here:
RecyclerView: how to catch the onClick on an ImageView?
(2 answers)
Closed 4 years ago.
What I am trying to accomplish is to create a listener for the ImageView inside the row of RecyclerView.
This code is working already, but this is not the solution that I wanted to have, because you need to double click the ImageView before getting the desired result.
// row click listener
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
ImageView viewContent = (ImageView)view.findViewById(R.id.btnViewContent);
ImageView deleteContent = (ImageView)view.findViewById(R.id.btnDeleteContent);
viewContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "VIEW CONTENT", Toast.LENGTH_SHORT).show();
}
});
deleteContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "DELETE CONTENT", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onLongClick(View view, int position) {}
}));
Any idea how to translate this into single click solution? Advice or even a single comment would help me a lot.

This is not the right way as one of our friend suggested onBindViewHolder is caleed again and again during scrolling so it is not the best practice to add listener there.
Best way is to add it on ViewHolder as I suggested. Check my answer above.
Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.btnClassAddCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}

Then there is no need to implement recyclerView.addOnItemTouchListener , inside Viewholder just add clicklistener on the view(image) you want below is the example for reference.
` public static class HeaderViewHolder extends RootViewHolder {
#BindView(R.id.cardview)
CardView cardview;
#BindView(R.id.main_container)
LinearLayout main_container;
#BindView(R.id.music_cardview)
CardView music;
#BindView(R.id.shabad_cardview)
CardView shabadvaani;
#BindView(R.id.news_cardview)
CardView news;
#BindView(R.id.donate_cardview)
CardView donate;
#BindView(R.id.bs_cardview)
CardView bs;
#BindView(R.id.bl_cardview)
CardView bl;
#BindView(R.id.bng_cardview)
CardView bng;
#BindView(R.id.more_cardview)
CardView more;
#BindView(R.id.vid_cardview)
CardView vid;
#BindView(R.id.medi_cardview)
CardView medi;
//
// #BindView(R.id.ama_cardview)
// CardView ama;
public HeaderViewHolder(final View itemView,final OnItemClickListener mOnItemClickListener) {
super(itemView);
ButterKnife.bind(this, itemView);
news.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//Intent i= new Intent(ctx,);
//open drawer code
}
});
shabadvaani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, IndexActivity.class);
ctx.startActivity(i);
}
});
music.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, MainActivity.class);
i.putExtra("slug","audiobhajan");
ctx.startActivity(i);
//open drawer code
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent(ctx, stayrocks.jambh.vani.auth.MainActivity.class);
// ctx.startActivity(i);
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//open drawer code
}
});
bs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(ctx, AmaActivity.class);
ctx.startActivity(intent);
}
});
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, ItemListActivity.class);
ctx.startActivity(i);
//open drawer code
}
});
bng.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, WallpaperActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
medi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, stayrocks.jambh.vani.activities.jyot.MainActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
vid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, VideoListDemoActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
// ama.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//// String appPackage = "com.my.bishnoi.nextgen";
//// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
//// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent= new Intent(ctx, AmaActivity.class);
// ctx.startActivity(intent);
// //open drawer code
// }
// });
}
}
`

Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}

Related

Using multiple buttons within dialog box with intents to change text of main button

i am in a pickle at the moment to how to approach making 3 buttons within a single dialog box make the option selected change the text of the button used to show the dialog box, so far only managed to get option3 to work as i suppose its the last intent so the only button that works would be the button for option3
here is the code im trying to pass to the main button from the dialog
public class LabelDialog extends AppCompatDialogFragment {
private Button option1, option2, option3;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.label_dialog, null);
builder.setView(view);
//option 1 and 2
option3 = view.findViewById(R.id.label_lecturebtn);
option3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String option3 = "Lecture";
Intent intent3 = new Intent(getContext(), AddTask.class);
intent3.putExtra("lecture", option3);
startActivity(intent3);
dismiss();
}
});
and the main code
protected void onCreate(Bundle savedInstanceState) {
//...
label_button = findViewById(R.id.button_labels);
label_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
}
});
checkLabelResult();
}
public void openDialog() { //Labels dialog
//code to open dialog
}
public void checkLabelResult() {
//intents 1 and 2, same format as 3 but keys changed accordingly
Intent intent3 = getIntent();
String option3 = intent3.getStringExtra("lecture");
label_button.setText(option3);
}
Code for Option 1
option1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String option1 = "Important";
Intent intent = new Intent(getContext(), AddTask.class);
intent.putExtra("important", option1);
startActivity(intent);
dismiss();
}
Code for Option 2
option2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String option2 = "To Do";
Intent intent2 = new Intent(getContext(), AddTask.class);
intent2.putExtra("to do", option2);
startActivity(intent2);
dismiss();
}

Pass textview value between activity

i have a problem.
I have 2 textviews that are increased on button click, but i don't know how to pass textview's value to the next activity that also have the same 2 textviews. Like increasing the value by 1 on first activity then on the second activity on the same textview there will be the value 1 and so on...
I'm trying to pass the textview value to next activity, i tried a few methods with putextra methods, but it didn't worked.
There is the code
Button btnIncrement;
private CheckBox i1, i2, i3;
public Button bckbutton;
TextView rspCorecte;
TextView rspGresite;
int counterCorecte=0;
int counterGresite=0;
private void initialStates(Intent intent) {
i1=findViewById(R.id.q1_1);
i2=findViewById(R.id.q1_2);
i3=findViewById(R.id.q1_3);
}
Then...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intrebarea_1);
initialStates(getIntent());
final AlertDialog.Builder alert2=new AlertDialog.Builder(Intrebarea1.this);
LayoutInflater factry=LayoutInflater.from(Intrebarea1.this);
final View view2=factry.inflate(R.layout.raspuns_corect, null);
alert2.setView(view2);
alert2.setPositiveButton("", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
final AlertDialog.Builder alertadd = new AlertDialog.Builder(Intrebarea1.this);
LayoutInflater factory = LayoutInflater.from(Intrebarea1.this);
final View view = factory.inflate(R.layout.raspuns1, null);
alertadd.setView(view);
alertadd.setPositiveButton("", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
startActivity(new Intent(Intrebarea1.this,Intrebarea2.class));
finish();
}
});
// SEMNUL INTREBARII
//reference of button added in the main layout
final Button raspuns = findViewById(R.id.arataraspuns);
//setting click event listener to button
raspuns.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Intrebarea1.this);
View view = LayoutInflater.from(Intrebarea1.this).inflate(R.layout.raspuns1, null);
builder.setView(view);
builder.show();
}
});
bckbutton=(Button) findViewById(R.id.backbutton);
bckbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
btnIncrement=findViewById(R.id.btnIncrement);
rspCorecte=findViewById(R.id.rspCorecte);
rspGresite=findViewById(R.id.rspGresite);
btnIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(i1.isChecked() && !i2.isChecked() && !i3.isChecked()){
alert2.show();
counterCorecte++;
}
else if (i1.isChecked() && i2.isChecked() && i3.isChecked()){
alertadd.show();
counterGresite++;
}
else if(i2.isChecked() && i3.isChecked()){
alertadd.show();counterGresite++;
}
else if(i1.isChecked() && i2.isChecked()){
alertadd.show();counterGresite++;
}
else if(i1.isChecked() && i3.isChecked()){
alertadd.show();counterGresite++;
}
else if(i2.isChecked()){
alertadd.show();counterGresite++;
}
else if(i3.isChecked()){
alertadd.show();counterGresite++;
}
btnIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
raspuns.setVisibility(View.VISIBLE);
btnIncrement.setVisibility(View.GONE);
}
});
rspCorecte.setText(String.valueOf(counterCorecte));
rspGresite.setText(String.valueOf(counterGresite));
}
}); }
public void bckButton(){
Intent intent=new Intent(this, AlegeMediulDeInvatare.class);
startActivity(intent);
finish();
}
public void openMainMenu(){
Intent intent=new Intent(this, MainMenu.class);
startActivity(intent);
finish();
}
public void onBackPressed(){
AlertDialog.Builder inchiziteoria = new AlertDialog.Builder(Intrebarea1.this, R.style.AlertDialogStyle);
LayoutInflater inchizi=LayoutInflater.from(Intrebarea1.this);
View view=inchizi.inflate(R.layout.inchizi_teoria, null);
inchiziteoria.setView(view);
// Set the positive button
inchiziteoria.setPositiveButton("DA", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
openMainMenu();
}
});
// Set the negative button
inchiziteoria.setNegativeButton("NU", null);
// Create the alert dialog
AlertDialog dialog = inchiziteoria.create();
// Finally, display the alert dialog
dialog.show();
((Button)dialog.getButton(dialog.BUTTON_POSITIVE)).setTypeface(null, Typeface.BOLD);
((Button)dialog.getButton(dialog.BUTTON_NEGATIVE)).setTypeface(null, Typeface.BOLD);
// Change the alert dialog background color
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
}
public void openUrmatoarea(View v){
Intent intent=new Intent(this, Intrebarea2.class);
startActivity(intent);
finish();
}
}
Can someone tell me how to pass the textview value to the next activity?
Thanks in advance.
Intent intent = new Intent(getBaseContext(), MainActivity.class);
// change the MainActivity if you want to pass the value to another activity
intent.putExtra("text", text);
startActivity(intent);
And in the next activity where you want to get the value :
Intent intent = getIntent();
String text = intent().getStringExtra("text");

Activity intent not working on button click

Hello Stackoverflow community!
Recently, a strange error occured to me. It is with a button in my app. When i press it there is nothing happening. No errors, or crashes but also Intent is not functioning. The transition to DeleteAccountActivity is not happening. I don't know why is this happening. The intent which I am using is very simple(passes nothing). Please help me
AccountSettingsActivity.java
public class AccountSettingsActivity extends AppCompatActivity {
private static final String TAG = "AccountSettingsActivity";
private static final int ACTIVITY_NUM = 4;
private String user_id;
private Context mContext;
public SectionsStatePagerAdapter pagerAdapter;
private ViewPager mViewPager;
private RelativeLayout mRelativeLayout;
private Button mDelete;
User mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
}
});
}
private void deleteAccounts(){
/* DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference("users").child(user_id);
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference("user_photos").child(user_id);
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference("comments").child(user_id);
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();*/
// getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_users))
// .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(mUser.getUser_id())
.removeValue();
/* FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_followers))
.child(mUser.getUser_id())
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.removeValue(); */
}
private void getIncomingIntent(){
Intent intent = getIntent();
if(intent.hasExtra(getString(R.string.selected_image))
|| intent.hasExtra(getString(R.string.selected_bitmap))){
//if there is an imageUrl attached as an extra, then it was chosen from the gallery/photo fragment
Log.d(TAG, "getIncomingIntent: New incoming imgUrl");
if(intent.getStringExtra(getString(R.string.return_to_fragment)).equals(getString(R.string.edit_profile_fragment))){
if(intent.hasExtra(getString(R.string.selected_image))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
intent.getStringExtra(getString(R.string.selected_image)), null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
null,(Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap)));
}
}
}
if(intent.hasExtra(getString(R.string.calling_activity))){
Log.d(TAG, "getIncomingIntent: received incoming intent from " + getString(R.string.profile_activity));
setViewPager(pagerAdapter.getFragmentNumber(getString(R.string.edit_profile_fragment)));
}
}
private void setupFragments(){
pagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new EditProfileFragment(), getString(R.string.edit_profile_fragment)); //fragment 0
pagerAdapter.addFragment(new SignOutFragment(), getString(R.string.sign_out_fragment)); //fragment 1
// pagerAdapter.addFragment(new DeleteAccountFragment(), "Delete Account");
}
public void setViewPager(int fragmentNumber){
mRelativeLayout.setVisibility(View.GONE);
Log.d(TAG, "setViewPager: navigating to fragment #: " + fragmentNumber);
mViewPager.setAdapter(pagerAdapter);
mViewPager.setCurrentItem(fragmentNumber);
}
private void setupSettingsList(){
Log.d(TAG, "setupSettingsList: initializing 'Account Settings' list.");
ListView listView = (ListView) findViewById(R.id.lvAccountSettings);
ArrayList<String> options = new ArrayList<>();
options.add(getString(R.string.edit_profile_fragment)); //fragment 0
options.add(getString(R.string.sign_out_fragment)); //fragement 1
// options.add("Delete Account");
ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, options);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: navigating to fragment#: " + position);
setViewPager(position);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, this,bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
DeleteAccountActivity.java
public class DeleteAccountActivity extends AppCompatActivity {
Button yesButton;
Button cancelButton;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_delete_account);
yesButton = (Button) findViewById(R.id.btnDelete2);
cancelButton = (Button) findViewById(R.id.btnDelete3);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteAllData();
Intent intent = new Intent(mContext, RegisterActivity.class);
startActivity(intent);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
}
});
}
public void deleteAllData(){
DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference()
.child("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference()
.child("user_photos")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference()
.child("user_account_settings")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowing = FirebaseDatabase.getInstance().getReference()
.child("following")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowers = FirebaseDatabase.getInstance().getReference()
.child("followers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();
deleteUserFollowing.removeValue();
deleteUserFollowers.removeValue();
}
}
Issue :
Press backarrow (But this will finish the activity)
Press mdelete to trigger the intent. (so no way to trigger intent)
Because when you press backarrow, you are setting the listener on mdelete which actually has the code to trigger intent and finish will kill the activity so no way to trigger intent
Solution : Separate the listeners
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
Please, change the lines with setting the clickListeners to this:
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
I think your onCreate() method should look like this:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
}
One simple thing i can see by skimming through is that the onClick listener for your button that should take you to delete activity is assigned inside the back arrow onClick listener.
So the only time your delete button is assigned a click listener is when you press the back button, and it wont still assign because you already called
finish();
On the activity
Change
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
} });
To
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
} });
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
Hope this helps.

How to update image in fragment when selecting an image in an Activity?

Hello I'm trying to select an Image in an activity page and that selected image to update in my Fragment page. I've tried what I've learnt previously, but it's not working at all. Below is what I've attempted. I'm still new to android development, so please bear with me.
ProfileSettingsActivity.java:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
profileImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Below is the Fragment that contains the page I start on from and go to the ProfileSettingsActivity page
PeopleFragment.java:
public class PeopleFragment extends Fragment {
ImageButton settingsButton;
PieChart pieChart;
ImageButton profileImage;
private FirebaseAuth mAuth;
TextView fullName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_people2, container,
false);
profileImage = (ImageButton) view.findViewById(R.id.imageButton4);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
getActivity().startActivityForResult(settingsClick,0);
}
});
fullName = (TextView) view.findViewById(R.id.userProfileFullName);
mAuth = FirebaseAuth.getInstance();
return view;
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
/**
* Updates the view according to the authentication status.
* #param user the current FirebaseUser
*/
private void updateUI(FirebaseUser user) {
if (user != null) {
fullName.setText(user.getDisplayName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) return;
//Getting the Avatar Image we show to our users
ImageView avatarImage =
(ImageView)getView().findViewById(R.id.imageButton4);
//Figuring out the correct image
String drawableName = "profile1";
switch (data.getIntExtra("imageID",R.id.teamid00)) {
case R.id.teamid00:
drawableName = "profile1";
break;
case R.id.teamid01:
drawableName = "profile2";
break;
case R.id.teamid02:
drawableName = "profile3";
break;
case R.id.teamid03:
drawableName = "profile4";
break;
case R.id.teamid04:
drawableName = "profile5";
break;
case R.id.teamid05:
drawableName = "profile6";
break;
default:
drawableName = "profile1";
break;
}
int resID = getResources().getIdentifier(drawableName, "drawable",
getActivity().getPackageName());
avatarImage.setImageResource(resID);
}
}
Currently with what I have above, I can move from the fragment page to the activity page and I can press on the buttons to select the images and then the activity closes for me. But when I'm back on the fragment page, the profile image isn't updated at all, and displays the default one.
Try to use startActivityForResult() instead of getActivity().startActivityForResult(). So, change your Fragment code to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
startActivityForResult(settingsClick,0);
}
});
...
return view;
}
Note: This is not related to your problem.
You can simplify you activity code to this:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
};
profileImage1.setOnClickListener(clickListener);
profileImage2.setOnClickListener(clickListener);
profileImage3.setOnClickListener(clickListener);
profileImage4.setOnClickListener(clickListener);
profileImage5.setOnClickListener(clickListener);
profileImage6.setOnClickListener(clickListener);
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Probably you've got some problems with your onActivityResult method. Check these answers.
Also there is a solution that is going to work:
1. Tag your fragments when you create them:
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.main_layout, new PeopleFragment(), "PeopleFragmentTag"));
fTrans.commit();
2. Write method in PeopleFragment, which could setImage:
public void updateProfileImage(int profileImgID){
/* Update your image here */
}
3. Get a fragment by tag and call the method:
public void setProfilePicture(View view) {
/* Your code */
PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentByTag("PeopleFragmentTag");
peopleFragment.updateProfileImage(selectedImage.getId());
}
Hope, I helped you somehow. Good luck!

How to have multiple intents on the same java program

public class FullscreenActivity extends AppCompatActivity {
private ImageButton act;
private ImageButton sat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
act = (ImageButton) findViewById(R.id.act);
sat = (ImageButton) findViewById(R.id.sat);
sat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(FullscreenActivity.this, sat.class);
startActivity(intent);
act.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(FullscreenActivity.this, act.class);
startActivity(intent);
}
});
}}
What am I doing worng. I have a main UI with six imagebuttons, each one linking to a different activity. How can I link then all in the main activity which is called fullscreen activity
I think you want to bring the FullScreenActivity to front so you only have to finish the front Activity because you didn't finish it
just do finish(); on your sat.class or act.class
or....
You can do this too on your sat.class or act.class:
Intent i = new Intent(this, FullScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
act.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(FullscreenActivity.this, act.class);
startActivity(intent);
}
});
why is the above part inside some other button's click listener? Move it outside the anonymous inner method like
sat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(FullscreenActivity.this, sat.class);
startActivity(intent);
}
});
act.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(FullscreenActivity.this, act.class);
startActivity(intent);
}
});

Categories