Code in onActivityResult() not executed - java

I've got an android application that I want to open a different activity then my main one after a fresh install.
I tried this using startActivityForResult() and SharedPreferences. Here is my code:
main activity:
public class ONTTMainActivity extends Activity {
static final int REQUEST_CODE = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences("prefs", 0);
boolean firstRun = settings.getBoolean("firstRun", true);
if(firstRun){
startActivityForResult(
new Intent(this, ONTTSplashActivity.class), REQUEST_CODE);
}
setContentView(R.layout.activitymain);
}
second activity:
public class ONTTSplashActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityonttsplash);
final Button btnSkip = (Button) findViewById(R.id.button_skip);
btnSkip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(ONTTSplashActivity.this, "Toast Reached", Toast.LENGTH_LONG).show();
if (resultCode == RESULT_OK) {
SharedPreferences settings = getSharedPreferences("ONTT_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
}
The problem is that even though the second activity is ended the code in the onActivityResult function is never executed. I tried using a toast to see if it has been reached.
I've seen several similar questions but I've tried every solution but it's not working.

You are starting ONTTSplashActivity from ONTTMainActivity for getting result back from ONTTSplashActivity to ONTTMainActivity so put onActivityResult in first ONTTMainActivity activity:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(ONTTMainActivity .this, "Toast Reached", Toast.LENGTH_LONG).show();
if (resultCode == RESULT_OK) {
SharedPreferences settings = getSharedPreferences("ONTT_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
}

OnActivityResult() must be in you first activity not in the second activity.
Since from first activity only you are calling startActivityForResukts() so your first activity expect for results from the second activity.

Related

How to store a count given by a user and the user's choices across activities in Android Studio

I want to make a basic app in which I offer the user to add a trackers of various things like water etc. and then he can store how many glasses he has drank so far. However I want it to have saved the information even after the app closes. Please provide a solution.
This is what I've tried so far:-
public class MainActivity extends AppCompatActivity {
Button btnAddTracker;
//public static final String MY_PREFS_NAME = "MyCounter";
ImageView ivWater;
TextView tvWaterCount;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
if(pref.getBoolean("WaterStatus",false)){
ivWater.setVisibility(View.VISIBLE);
tvWaterCount.setVisibility(View.VISIBLE);
tvWaterCount.setText(pref.getInt("waterCount",0));
}
btnAddTracker=findViewById(R.id.btnAddTracker);
ivWater=findViewById(R.id.ivWater);
tvWaterCount=findViewById(R.id.tvWaterCount);
btnAddTracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,TrackerListActivity.class);
startActivity(intent);
}
});
editor.putInt("waterCount", 8);
editor.apply();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(pref.getBoolean("WaterStatus",false)){
ivWater.setVisibility(View.VISIBLE);
tvWaterCount.setVisibility(View.VISIBLE);
tvWaterCount.setText(pref.getInt("waterCount",0));
}
}
}
}
public class TrackerListActivity extends AppCompatActivity {
Button btnAddWaterTracker;
ImageView ivReturn,ivWater;
TextView tvWaterStatus;
boolean WaterStatus;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracker_list);
ivReturn=findViewById(R.id.ivReturn);
btnAddWaterTracker=findViewById(R.id.btnAddWaterTracker);
ivWater=findViewById(R.id.ivWater);
tvWaterStatus=findViewById(R.id.tvWaterStatus);
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
WaterStatus=pref.getBoolean("waterStatus",false);
ivReturn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2=new Intent();
intent2.putExtra("waterStatus",WaterStatus);
setResult(RESULT_OK,intent2);
if(btnAddWaterTracker.getVisibility()==View.GONE) {
editor.putBoolean("waterStatus",true);
editor.apply();
}
TrackerListActivity.this.finish();
//Intent intent1=new Intent(TrackerListActivity.this,MainActivity.class);
//startActivity(intent1);
}
});
btnAddWaterTracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WaterStatus=true;
btnAddWaterTracker.setVisibility(View.GONE);
tvWaterStatus.setVisibility(View.VISIBLE);
//editor.putBoolean("waterStatus",true);
//editor.apply();
}
});
}
}
There are many ways of saving informations locally, you could save it on a file using the Json or XML format, you could also use SQLite which are supported by all recent smartphones.
Unfortunately you won't get anyone to code for you on this website, check this link

Deleting back stack of activities

I have 3 activities: A->B->C
The user starts from activity A. When going to B he can press back and return to A.
But... When user goes to C from B. I wish that A and B will be removed and user will exit the app when clicking back.
I tried:
Intent intent = new Intent(B.this, C.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
but on back it still goes to B. If doing so:
Intent intent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
The user goes back to A, so.. It is not what I need.
Override onBackPressed() in Activity C
#Override
public void onBackPressed() {
finishAffinity();
}
This will cause all Activitys running in the same task to finish. If the user starts the app again by tapping on it in the recent tasks window, Activity A will be shown.
100% working.
try to start Activity C like this.
Intent intent = new Intent(this,ActivityC.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity();
Start B activity with startActivityForResult():
Intent intent = new Intent(A.this, B.class);
startActivityForResult(intent, 100);
and override in class A startActivityForResult():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 100) {
if (resultCode == 1) {
finish();
}
}
}
Now in B class set the result to be sent back to activity A:
Intent intent = new Intent(VerifyPhoneActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
setResult(1);
finish();
If I understood you right, You could achieve this is using SharedPreferences:
In Your Activity A add this:
public class ActivityA extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
if (savedInstanceState == null){
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("CloseApp", false);
editor.commit();
}
}
#Override
protected void onResume() {
super.onResume();
boolean finish = prefs.getBoolean("CloseApp", false);
if (finish){
this.finish();
}
}
In Activity B:
public class ActivityB extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
boolean finish = prefs.getBoolean("CloseApp", false);
if (finish){
this.finish();
}
}
And Activity C:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("CloseApp", true);
editor.commit();
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
That should work.
you can just write this in Activity C if your application work from JELLY_BEAN to up .
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}
if your app work under JELLY_BEAN you can use this solution :
Activity C :
#Override
public void onBackPressed() {
Intent i = new Intent(C.this,A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("BackFromC",true);
startActivity(i);
super.onBackPressed();
}
Activity A in onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
if(getIntent() != null){
if(getIntent().getBooleanExtra("BackFromC",false)){
finish();
}
}
... your Code
}

Sending Zxing scanResult to another activity

I have tried everything and whatever I could to solve this problem. At last I am posting it here to get a solution (New to Android).
I have made an android scanner app and I am using ZXing open source code. The problem is after scan I am trying to send the scan result to another activity but unable to do.
Here is my code:
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler, NavigationView.OnNavigationItemSelectedListener {
private ZXingScannerView mScannerView;
private int CALL_SCANNER_APP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Scan Button code
public void onClick(View v) {
ZXingScannerView mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
//startActivityForResult(mScannerView1, CALL_SCANNER_APP);
}
#Override
protected void onPause (){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
ResultActivity.tvresult.setText(result.getText());
/*Log.w("handleReuslt", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
//alertDialog.show();
builder.setPositiveButton("Result", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("OK", null).show();*/
//Resume Scanning
//mScannerView.resumeCameraPreview(this);
}
There is one method which send results from One activity to other activity is scanActivityForResult() but in my case I am not using intent on public void onClick(View v)
So how do I achieve this.
Thanks!
Use Below code into the button click.
Intent intent = new Intent(SelectOptionActivity.this, CaptureActivity.class);
intent.putExtra("SCAN_MODE", "ONE_D_MODE");
intent.putExtra("SCAN_FORMATS", "CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF,CODABAR,EAN_13,EAN_8,UPC_A,QR_CODE");
intent.setAction(Intents.Scan.ACTION);
startActivityForResult(intent, 1);
And override this method to get result of scanning.
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1 && resultCode == RESULT_OK) {
final String contents = intent.getStringExtra(Intents.Scan.RESULT);
final String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT);
}
}
in handleDecodeInternally you directly intent the Capture Activity to desired Activity
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
maybeSetClipboard(resultHandler);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (resultHandler.getDefaultButtonID() != null && prefs.getBoolean(PreferencesActivity.KEY_AUTO_OPEN_WEB, false)) {
resultHandler.handleButtonPress(resultHandler.getDefaultButtonID());
return;
}
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.GONE);
Intent intent = new Intent(CaptureActivity.this, AfterCaptureActivity.class);
startActivity(intent);
finish();

How to properly start nextQuestion method by pressing OK button in a popup dialog?

In my quiz game, after wrong answer I call a popup with an Intent for result. In that popup I have an OK button. I need, after user press OK button, to load next question. But now, I see in background next question loaded, even though my popup is not closed. Here's my code:
static final int MY_REQUEST = 0;
Intent i = new Intent(Kviz.this, Popup_pogresno.class);
startActivityForResult(i, MY_REQUEST);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
nextQuestion();
}
And my popup class (it's a Theme.Dialog activity):
public class Popup_pogresno extends Activity implements OnClickListener{
Button ok;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.popup);
ok = (Button) findViewById(R.id.bPopupOK);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onBackPressed() {
//do nothing
}
}
So, I need the next question NOT to load UNTIL I press the OK button.
set a result code in Popup_pogresno Activity, and check this result code in Kviz activity on the basis of request code. If result code is ok the call the function nextQuestion()
set result code as follow and check in Kviz for is result code.
Intent i = new Intent(Kviz.this, Popup_pogresno.class);
startActivityForResult(i, MY_REQUEST);
set result code on ok button click in Popup_pogresno :
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
check for result code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_REQUEST) {
if(resultCode == RESULT_OK){
nextQuestion();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}

Execute code after getting back from an Intent

I have a TextView in my main activity.
pressing a button i open another activity and get to the options where i can rename my
TextView
btnSet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Options.class);
startActivity(intent);
}
});
In my Options activity i rename my TextView like this
public class Options extends MainActivity{
public static Boolean isRenamed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
String lblName = ("Counter 1");
Button btnOk = (Button) findViewById(R.id.btn_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent backToMain = new Intent(Options.this, MainActivity.class);
EditText labelName = (EditText) findViewById(R.id.set_name);
String lblName = labelName.getText().toString();
backToMain.putExtra(LABEL_NAME, lblName);
isRenamed = true;
startActivity(backToMain);
finish();
}
});
}
}
I am using the boolean isRenamed and i set it to true after clicking ok
And in my main activity i've set this
if (Options.isRenamed == true) {
// Get the message from the intent
Intent backToMain = getIntent();
String lblName = backToMain.getStringExtra(Options.LABEL_NAME);
// Edit the text view
TextView label = (TextView) findViewById(R.id.label1);
label.setText(lblName);
}
For now it's force closing, but is there some more elegant way to see if i've renamed the file and then execute that piece of code to set it?
Context.startActivityForResult();
do all your renaming and other stuff there. return a simple integer to know what happened. That way when you call finish() in your second activity it will return to your first without creating a new instance.
Use startActivityForResult() instead of startActivity(). In the Options Activity:
public static final int RENAMED = 100;
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent backToMain = new Intent(Options.this, MainActivity.class);
EditText labelName = (EditText) findViewById(R.id.set_name);
String lblName = labelName.getText().toString();
backToMain.putExtra(LABEL_NAME, lblName);
isRenamed = true;
setResult(RENAMED);
finish();
}
});
In MainActiviy, override onActivityResult() and
when it is fired check if resultCode paramter is equals to RENAMED .
for this senario you need to use
startActivityForResult(intent, requestCode)
instead of startActivity(intent)
in your Options Activity you ca setResult(resultCode, data) and call finish.
and in MainActivity you can use data in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
you can use
startActivityForResult(intent, intentsData.REQUEST_CODE);
and then change your TextView when activity is resumed
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/**
* change your TextView
*/
super.onActivityResult(requestCode, resultCode, data);
}

Categories

Resources