How to get data from 2nd Activity to 1st Activity - java

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

Related

How do I pass the number of clicks and reset the count in another activity?

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

Activity to Fragment sending data and access arraylist in Fragment

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

How can I change the background color of a Main Activity by using spinner while clicking a button in the Second Activity?

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

Serial scan using Zxing library - android

i'm developing a scan Barcode app on android , my application is simple and composed from an activity which contains a button and a textView which will receive the result of the scan.. The app works well but i want that i could realise serial scan in a raw. so after scanning a barcode i need that the capture Activity stay and the appli don't back to the button activity so i can scan the next Barcode. any solution please ?
this is my main java code :
public class MainActivity extends Activity {
private Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan= (Button)findViewById(R.id.btnScan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
});
}
public boolean onTouchEvent(final MotionEvent event) {
IntentIntegrator integrator = new IntentIntegrator();
integrator.initiateScan(null);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
TextView tv = (TextView) findViewById(R.id.scanResult);
tv.setText(data.getStringExtra("SCAN_RESULT"));//this is the result
} else
if (resultCode == RESULT_CANCELED) {
// Handle cancel
} }
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
I had the same problem when I did my scanner activity, and the solution that I found was to make my mainActivity extends Zxing CaptureActivity, like this I overrided handleDecode and I avoided to switch between different activities (as you have to do to obtain your scanner result).
Anyhow, to restart the scanning process after a precedent scan I called the method
restartPreviewAfterDelay(0L)
(that is a method of CaptureActivity) in the onClick function of a button.
Take a look at that method, I think that it is what you need.
i finally found the solution i had just to add this code in the onActivityResult() declaration
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
So after the scan is finished the app is ready to scan again instead of going back to the home activity

close an activity from other activity?

Does anyone know how to close an activity from other activity?? for example: i have 3 activity (activity A, B, and C) and from activity C, i can close an activity A..
my activity structure is activity A -> activity B -> activity C
how to close an activity A from activity C?
i was try this code :
#Override
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent goToLockScreen= new Intent(this,LockScreenForm.class);
startActivity(goToLockScreen);
finish();
but that code is only fot closing activity A from activity B, and can't close activity A from activity C direcly..
Does anyone know about closing an activity direcly from other activity??
thanks..
First Go to parent activity by starting it
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
switch(Code){
case A: go to that activity and finsih() this again come back to parent activity
case B: go to that activity and finsih() this again come back to parent activity
/////and son on
}
try It work perfectly for me
`public class aActivity extends Activity {
public static Activity handleToClose;
#Override
public void onCreate(Bundle savedInstanceState) {
.
.
.
handleToClose = this;
}
public void onClick(View v)
{
Intent i = new Intent(this, act2.class);
startActivity(i);
}
}`
Now You have to finish Activity-A from Activity-B
Activity-B or 2nd Activity
`public class act2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
// your code here
}
public void onClick(View v)
{
aActivity.handleToClose.finish(); //this will finish aActivity (1st Activity)
finish();//to finish current Activity
}
}`
Intent goToLockScreen= new Intent(this,LockScreenForm.class);
goToLockScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This is a prescribed way and you should follow it.. if you want some other behaviour yo can implement it.. there are lot many questions asked on this topic.. refer other questions...
What about starting both B and C forResult and send a result back to pervious activity to let A finally call finish()? Like this:
A startActivityForResult() -> B startActivityForResult()-> C
C setResult()-> B onActivityResult(){setResult()} -> C onActivityResult(){finish()}
Sounds complicated, but maybe it can be used as a workaround?
try this
If the update activity is launching another installation activity, then you may want to override void onActivityResult(int requestCode, int resultCode, Intent intent) in the update activity, providing the following implementation. Also, when the update activity launches the installation activity, it should do so with startActivityForResult(Intent, int), not with startActivity(Intent).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
finish();
}

Categories

Resources