I have a fragment which is present in Bottom Navigation Activity. The Fragments contain the custom recyclerview. There is a comment button when i press it opens another activity for comments. Below is in the RecyclerView adapter.
viewholder.commentlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//commenttofragment.clear();
Intent comment = new Intent(fp, com.fooddoof.fuddict.comment.class);
int id = dusers.get(position).getId();
int comcount = dusers.get(viewholder.getAdapterPosition()).getCommentcount();
comment.putExtra("id",id);
comment.putExtra("ownerid",userid);
comment.putExtra("maincommentposition",position);
comment.putExtra("commentcountonposition", comcount);
fp.startActivityForResult(comment,1);
}
});
In Comment activity after doing some tasks I need to send some values to this fragment. So I Override the OnBackPressed method. I have created a method in Fragment to receive it.
#Override
public void onBackPressed()
{
Bundle args = new Bundle();
args.putInt("maincommentcount",maincommentcount);
args.putInt("maincommentposition", maincommentposition);
FolowersPost f = new FolowersPost();
f.getdatafromcomment(args);
finish();
}
I receive it like below in Fragment.
public void getdatafromcomment(Bundle args)
{
int count = args.getInt("maincommentcount");
int p=args.getInt("maincommentposition",999999999);
Log.e("Shiva","count--->"+count+"p--->"+p);
}
The Values are received but I need to access the arraylist in Fragement which is passed in Adapter for displaying the recyclerView. But I am not able to access it while I am coming back to fragment which is present in the method under OnCreateView. I tried with OnResume to access it but works for some time only. I have declared the Arraylist as global variable also.
You are already using startActivityForResult. now you just need to use onActivityResult.
But you just need to start activity from fragment instead of from adapter.
onClick from fragment:
Intent comment = new Intent(getActivity(), com.fooddoof.fuddict.comment.class);
startActivityForResult(comment, 1);
onBackPressed in your comment activity:
#Override
public void onBackPressed() {
Intent returnIntent = new Intent();
returnIntent.putExtra("maincommentcount",10);
returnIntent.putExtra("maincommentposition",20);
setResult(Activity.RESULT_OK,returnIntent);
finish();
// super.onBackPressed();
}
onActivityResult in fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
int mMaincommentcount = data.getIntExtra("maincommentcount", 0);
int mMaincommentposition = data.getIntExtra("maincommentposition", 0);
System.out.println("mMaincommentcount = " + mMaincommentcount + ", mMaincommentposition = " + mMaincommentposition);
}
}
}
Related
The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here
I want to change the background color of Main activity by using spinner in second Activity. I have already created one button and it goes to second activity and in this second activity I have created spinner which consist of which color should be in the main activity. After choosing the color, the button I created will change the background color and will be back to first activity.
From what I understand, you need the ActivityForResult behavior.
You use startActivityForResult to fire the Intent from your first activity to your second, along with a request code.
You use an Intent and setResult to send data from your second activity back to your first.
You override onActivityResult in your fist activity to get and use your data.
Sample code:
public class FirstActivity extends Activity {
private static final int PICK_COLOR_REQUEST = 1001;
...
private void pickColor() {
Intent pickColorIntent = new Intent(this, SecondActivity.class);
startActivityForResult(pickColorIntent, PICK_COLOR_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_COLOR_REQUEST && resultCode == Activity.RESULT_OK) {
int color = data.getIntExtra("color");
/* use the color */
}
}
}
public class SecondActivity extends Activity {
...
private void onColorPicked(int color) {
Intent dataIntent = new Intent();
dataIntent.putExtra("color", color);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
}
my MainActivity is calling a second activity PopupWindow which contains a listview. when user clicks on listview I need to return that information to first activity (MainActivity). So in MainActivity I have this two methods. the first method calls the second activity the second gets result from second activity
//event listener for authors list menu (popup window)
authorListImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent popupWinIntent = new Intent(getBaseContext(), AuthorsPopup.class);
popupWinIntent.putExtra("allauthors", allAuthors);
startActivity(popupWinIntent);
}
});
//fetching result -- author from AuthorsPopup activity back
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String author = data.getStringExtra("author");
Log.v("author ", author);
}
}
}
this method is outside the onCreate() method. some tutorials suggest to create the avobe method just like onActivityResul() I'm assuming that case it would be inside the onCreate() method. mine is a method declaration. so obiously not executing. In my second activity. I have this
//event listener for authros listview
authorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paren, View view, int position, long id) {
// Log.v("author: ", authorsList[position]);
String author = authorsList[position];
Intent returnResultIntent = new Intent(getBaseContext(), MainActivity.class);
returnResultIntent.putExtra("author", author);
setResult(RESULT_OK, returnResultIntent);
finish();
}
});
what is the proper way to get data back from second activity?
You need to launch the second activity using startActivityForResult(popupWinIntent,1) rather than startActivity(popupWinIntent) and override the onActivityResult method in your first Activity, like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("author");
}
}
}
The first authorListImageView.setOnClickListener code you listed would go in onCreate
1st Activity
How to get value
SharedPreferences sharedPreferences;
sharedPreferences=getSharedPreferences("FileName",0);
sharedPreferences.getString("KEY","DefaultValue");
sharedPreferences.getBoolean("KEY",false);
2nd Activity
How to set or put the value from activity for getting on other activity
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
sharedPreferences=getSharedPreferences("FileName",0);
editor=sharedPreferences.edit();
editor.putString("KEY","Value");
editor.putBoolean("KEY",true);
editor.apply();
Let say I have two Activities, Activity A and Activity B.
Activity A displays a list of images using the Adapter Z.
When user clicks on any image in Activity A, they will be taken to Activity B to show the full image. I'm passing image path and grid position to Activity using Intent.
Now in Activity B, I place a delete button which should delete the imagepath from the gridview adapter.
Problem is:
How can I access the Activity A adapter in activity B to call remove(position) method in my adapter.
So I can call notifyDataSetChanged in onResume of Activity A to update the gridview images.
Activity A
MyGridView = (GridView) findViewById(R.id.gridview);
adapter = new MyAdapter(this);
MyGridView .setAdapter(adapter );
Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
fullImageActivity.putExtra("position", position);
fullImageActivity.putExtra("path", mediaPath);
startActivity(fullImageActivity);
Activity B
Intent i = getIntent();
// I'm getting position and path from setOnItemClickListener
position = i.getExtras().getInt("position");
path = i.getExtras().getString("path");
// I want to remove path from my adapter after clicking delete button in Activity B
Adapter
public ArrayList<String> images;
public void remove(int position){
images.remove(position);
}
use startActivityForResult.
Intent fullImageActivity = new Intent(getApplicationContext(), ActivityB.class);
fullImageActivity.putExtra("position", position);
fullImageActivity.putExtra("path", mediaPath);
startActivityForResult(fullImageActivity, 2);
check if deleted at particular position in Activity B . here I override onBackPressed() (For Ex.) method
public void onBackPressed(){
super.onBackPressed()
Intent intent=new Intent();
intent.putExtra("isdeleted",true);
intent.putExtra("pos",position);
setResult(2,intent);
finish();
}
Handle it in onActivityResult in Activity A.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
if(data.getBooleanExtra("isdeleted")){
remove from position array and notify dataset change. // pos = data.getIntExtra("pos")
}
}
}
Sorry for TYPO.
The key here is that you need to share the data and not really the adapter.
Using a singleton
You can use a singleton class to hold the image data and then access the same in both the activities. This ensures sync between both activities at all times.
Singleton Class
public class ImageData{
private ArrayList<ImageModel> mDataOfImages;
private ImageData mHelperInstance;
private ImageData(){
//private constructor to ensure singleton
}
public static ImageData getInstance(){
// return an ImageData instance according to your implementation
// of singleton pattern
}
private void setData(ArrayList<ImageModel> newData){
this.mDataOfImages = newData;
}
private void removeImage(int position){
if(this.mDataOfImages !=null && this.mDataOfImages.size() > position){
mDataOfImages.remove(position);
}
}
}
Activity A
private void saveImageData(ArrayList<ImageModel> data){
if(data !=null){
if(mAdapter !=null){
mAdapter.setData(data);
}
}
}
//Call notifydatasetchanged when activity is opened again
#Override
protected void onStart() {
if(mAdapter !=null){
mAdapter.notifyDataSetChanged();
}
}
MyAdapter
public void setData(ArrayList<ImageMode> newData){
if(newData !=null){
ImageDataSingleton.getInstance().setData(newData);
notifyDataSetChanged();
}
}
Activity B
Use the singleton class to display images in Activity B. Because you are using the model array list, you can easily implement right/left swipes and delete multiple images.
//Delete a image
private void deleteImage(){
ImageDataSingleton.getInstance().removeImage(getCurrentPosition());
// Rest of deletion handling like moving to right or left image
}
I think that you should build your remove method in activity A and be sure that it is static:
public static void remove(int position){
images.remove(position);
}
now you can call it from activity B like this:
ActivityA.remove(position);
I think this will work.
So i have an DataAdapter in onCreate method and i want to update it from another class.
main_spinList = (Spinner) findViewById(R.id.main_spinList);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
main_spinList.setAdapter(dataAdapter);
//=========================================Spinner==================
main_spinList.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
filepath = String.valueOf(main_spinList.getSelectedItem());
}
public void onNothingSelected(AdapterView<?> arg0) {
Log.e("klkl", "klkl");
}
});
I can update like this from AsyncTask but how can i update the adapter from another class with dataAdapter.notifyDataSetChanged(); ?
new FtpGet(){
public void onPostExecute(ArrayList<String> result) {
list.clear();
list.addAll(result);
dataAdapter.notifyDataSetChanged();
}
}.execute();
Another problem is that API 9 devices cant perform AsyncTask like from above in setOnSelectedItem method, it doesnt update the spinner.
I think you better look at "Getting a Result from an Activity" and "Retrieving result data from a sub-activity", because you don't need to refresh the adapter until you go back to it's activity.
onActivityResult() will allow you to get the status from the sub activity and you can refresh the adapter from the same activity when you are back to it.
In your adapter activity put this code where you start the other activity:
Intent i = new Intent(this, ActivityTwo.class);
startActivityForResult(i, REQUEST_CODE);
and add this method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("result")) {
ArrayList<String> result = data.getExtras().getSerializableExtra("result");
list.addAll(result);
dataAdapter.notifyDataSetChanged();
}
}
}
And when closing the sub activity and you want to refresh the adapter use this:
Intent data = new Intent();
data.putExtra("result", result);
setResult(RESULT_OK, data);
finish();
use interface in the activity you implement the interface and in the other class you just trigger it. and it it's method you use notify for the adapter.