how can activity start a new activity and close itself? - java

I have an android view which calls another view and should be closed.
I use this code
public void onClick(View v) {
Intent intent = new Intent(A.this, B.class);
startActivityForResult(intent,1);
setResult(RESULT_OK);
finish();
}
and I see after Activity B is on and calls finish, Activity A appears
and i understand it has never been closed.
How can I resolve this?

Try
public void onClick(View v) {
Intent intent = new Intent(A.this, B.class);
A.this.finish();
startActivity(intent);
}

Call finish() before starting the activity
public void onClick(View v) {
Intent intent = new Intent(A.this, B.class);
finish();
startActivityForResult(intent,1);
setResult(RESULT_OK);
}

You have to use Intent Where you wan to Start new Activity
Intent intent=new Intent(MainActivity.this,newActivity.class);
startActivity(intent);
and you have to override MainActivity onPause()
#Override
protected void onPause() {
finish();
}

Try the following code:
public void onClick(View v) {
Intent intent = new Intent(A.this, B.class);
startActivity(intent);
finish();
}

public void onClick(View v) {
Intent intent = new Intent(A.this, B.class);
startActivity(intent);
finish();
}

Your are starting activity B for result from activity A
public void onClick(View v) {
Intent intent = new Intent(A.this, B.class);
startActivityForResult(intent,1);
setResult(RESULT_OK);
finish();
}
So activity A is expecting result to delivered by activity B when activity B finishes.
Now, to get around this problem, start activity B in onActivityResult() method of the activity from which you started activity A.
// modified onClick method
public void onClick(View v) {
// simply set result to OK and finish activity A
setResult(RESULT_OK);
finish();
}
In the activity that starts activity A, define two constants or you can have a separate Java class to define constants and refer them in this class.
public static final int REQUEST_CODE_FOR_A = 100;
public static final int REQUEST_CODE_FOR_B = 101;
Override the onActivityResult() method in the activity that starts activity A and start activity B as follows
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == REQUEST_CODE_FOR_A) {
// start activity B when activity returns RESULT_OK
Intent intent = new Intent(this, B.class);
startActivityForResult(intent, REQUEST_CODE_FOR_B);
} else if (requestCode == REQUEST_CODE_FOR_B) {
// handle the result from Activity B
}
}
}
Hope this helps.

Related

Can't find a way to properly pass data with intent b.w two activities

Whenever I move from 1st activity to 2nd acitivity and then come back to 1st activity the value given in 1st activity goes null , even when I'm passing the value back and forth through intent .
Activity - 1
String date = getIntent().getStringExtra("date");
String name = getIntent().getStringExtra("name");
textView1.setText(date);
textView2.setText(name);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(Main.this,date.class);
intent.putExtra("name1", name);
startActivity(intent);
}
});
Activity - 2
calendarView=(CalendarView)findViewById(R.id.calendarView);
String name1 = getIntent().getStringExtra("name1");
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
String date = dayOfMonth+"-"+month+"-"+year;
Intent intent = new Intent(date.this , Main.class);
intent.putExtra("date", date);
intent.putExtra("name", name1);
startActivity(intent);
}
});
You are not getting the data back because you are starting a new activity rather than getting back to your previous activity
From your first activity ,start activity for result
int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);
from your second activity return the result
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
finaly on your first activity,receive the results from the second activity on onActivityResult
Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_SECOND_ACTIVITY) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
// Write your code if there's no result
}
}
} //onActivityResult

How to pass an intent back to MainActivity

My app has a RecyclerView in the MainActivity with an onClickListener which sends an intent to a DetailActivity. The DetailActivity has a button to go back without doing anything and a button to send an intent to the `Activity.
I already checked other posts in here like How to pass intent with extras to an already running activity and others, but no one results.
Here is a version that I tried:
MainActivity:
#Override
protected void onNewIntent(Intent intent) {
int codPedido = getIntent().getIntExtra("CodPedido",1);
//Toast to test if it's working
Toast.makeText(getApplicationContext(), String.valueOf(codPedido), Toast.LENGTH_SHORT).show();
}
OnClick of RecyclerViewAdapter:
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
DetailActivity:
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_confirm) {
Intent intent = new Intent(DetailActivity.this, MainActivity.class);
intent.putExtra("CodPedido", codPedido);
startActivityForResult(intent, 1);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Edit:
This is what I tried now:
viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity mActivity = new MainActivity();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
mActivity.startActivityForResult(intent, 1);
}
});
and it gives method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
What I was doing before was using the context which is here in the constructor
public RvPedidosAdapter(List<Pedido> pedidos, Context context) {
this.pedidos = pedidos;
this.context = context;
}
like this:
viewHolder.clRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
context.startActivity(intent);
}
});
On Your code please pass startActivityForResult() with intent param with result code and get the result on MainActivity in onActivityResult();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("CodigoPedido", pedidos.get(i).getCodPedido());
intent.putExtra("Local", pedidos.get(i).getLocal());
intent.putExtra("Dia",pedidos.get(i).getDia());
intent.putExtra("Periodo", pedidos.get(i).getPeriodo());
intent.putExtra("urgente", pedidos.get(i).isUrgente());
intent.putExtra("requisitante",pedidos.get(i).getRequisitante());
intent.putExtra("observacoes", pedidos.get(i).getObservacoes());
startActivityForResult(intent, 1);
On your second activity please use this code.
Intent intent = new Intent(DetailActivity.this, MainActivity.class);
intent.putExtra("CodPedido", codPedido);
setResult(RESULT_OK, intent);
finish();
and move to your MainActivity.class to get the result data in onActivityResult() method like this.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
(data.getIntExtra("CodPedido");
}
}
you can use
startActivityForResult(Intent intent,int requestcode);

startActivityForResult to one class and have that class return the data to a different class?

I have 3 classes: MainActivity, HighScoreActivity, and GameScreenActivity. I want to go to the GameScreenActivity via MainActivity, and then when the game has finished, pass the score to the HighScoreActivity. Everything gets passed to the GameScreenActivity successfully, but it doesn't go to the onActivityResult in HighScoreActivity.
I believe it's because of the MainActivity having the startActivityForResult, so the GameScreenActivity's finishQuiz() is expecting to return its data to the MainActivity. How would I pass the GameScreenActivity's data to the HighScoreActivity?
MainActivity()
MainActivity(){
...
private void startQuiz() {
String difficulty = spinnerDifficulty.getSelectedItem().toString();
Intent intent = new Intent(getBaseContext(), GameScreenActivity.class);
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
}
GameScreenActivity()
GameScreenActivity(){
...
private void finishQuiz(){
Intent resultIntent = new Intent(getBaseContext(),
HighScoreActivity.class);
resultIntent.putExtra(EXTRA_SCORE, score);
resultIntent.putExtra(EXTRA_DIFFICULTY, difficulty);
setResult(RESULT_OK, resultIntent);
startActivity(resultIntent);
}
}
HighScoreActivity()
HighScoreActivity(){
...
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
}
-------------------------------------------------------------
Trying with the Broadcast method:
GameScreenActivity() with broadcasting methods
GameScreenActivity(){
...
private void finishQuiz(){
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("scoreEvent");
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
intent.putExtra(EXTRA_SCORE, score);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
sendBroadcast(intent);
Intent goToHighScores = new Intent(getBaseContext(), HighScoreActivity.class);
startActivity(goToHighScores);
}
}
HighScoreActivity() with broadcasting methods
HighScoreActivity(){
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("scoreEvent"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
}
Considering HighScoreActivity is running,
You can utilize LocalBroadcastManager to register local broadcastReceiver in HighScoreActivity with IntentFilter. Also, don't forget to unregister in onDestroy()
Now, instead of setResult do sendBroadcast() from GameScreenActivity
Hope this helps. Happy coding!

Java Android finish activity , start previous activity

I have a 2 activity A and B .
In activity A I start activity B . On activity B I want to do photo and go back to activity A and do next step.
In activity A I have :
Intent intent1 = new Intent(this, CameraActivity.class);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent1, REQUEST_CAMERA);
In activity B I have
buttonClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
camera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
startActivity();
}
});
}
});
private void startActivity(){
Intent output = new Intent();
output.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
setResult(REQUEST_CAMERA, output);
finish();
}
And on Activity A I have :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
} else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
}
I don't know how on Activity B put fileUri and start good method on activity A
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new ImageTask().execute(data);
clearCamera();
}
};
Intent output = new Intent();
output.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
setResult(RESULT_OK, output);//change this
finish();

Android startActivityForResult and onActivityResult has unpredictable behaviours

I have an application in which multiple activities are shown in a certain order, which can change based on events in the current activity. I have a "master" activity which manages which activities are shown. Each ativity is started with startActivityForResult() with a requestCode unique to that activity.
When the activity finsishes, I set the resultCode to a value which will have meaning to the master activity. In the master activity's onActivityResult method, I have a switch (requestCode), which will tell me which activity has returned, and in each case block I work with the resultCode to determine which activity to start next.
The problem I'm having, is that at times, seemingly randomly, the application behaves quite erratically, showing activities out of sequence.
I've been unable to replicate the issue while debugging, so all the information I have looks good, but the end users are constantly complaining about the erratic behaviour.
How can I test to see where the problem is?
The code from the master activity's onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Settings.SCREEN_UPDATE:
ShowActivity(LoginActivity.class, Settings.SCREEN_LOGIN);
break;
case Settings.SCREEN_LOGIN:
if (resultCode == RESULT_OK) {
Settings.CurrentReport = new Report();
Settings.CurrentReport.setUserId(data.getIntExtra("userId", -1));
selectStore();
} else {
finish();
}
break;
case Settings.SCREEN_PRODUCT: // Coming back from the product selection screen
if (resultCode == RESULT_OK) {
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (resultCode == RESULT_CANCELED){
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
}
break;
case Settings.SCREEN_ACTION: // Coming back from the action screen, regardless of result, show options screen.
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
break;
case Settings.SCREEN_OPTIONS: // All choices return result_ok. Check the "mode" extra
String mode = data.getStringExtra("mode");
processOption(mode);
break;
case Settings.SCREEN_SESSION:
if (resultCode == RESULT_CANCELED) {
ShowActivity(OptionsActivity.class, Settings.SCREEN_OPTIONS);
} else if (resultCode == RESULT_OK ){
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
}
break;
} // switch (requestCode)
} // protected void onActivityResult(int requestCode, int resultCode, Intent data) {
private void processOption(String mode) {
if (mode.equals("select")) {
ShowActivity(ProductActivity.class, Settings.SCREEN_PRODUCT);
} else if (mode.equals("repeat")) {
Settings.CurrentReport.repeatItem();
ShowActivity(ActionActivity.class, Settings.SCREEN_ACTION);
} else if (mode.equals("session")) {
ShowActivity(SessionActivity.class, Settings.SCREEN_SESSION);
} else { // mode equals "end"
confirmFinish();
}
}
private void ShowActivity(Class cls, int requestCode) {
Intent activity = new Intent(this, cls);
startActivityForResult(activity, requestCode);
}
Then, the code from one of the other activities handling the finish() event:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.options);
Button btn;
btn = (Button)findViewById(R.id.btnSelect);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "select");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnRepeat);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "repeat");
setResult(RESULT_OK, intent);
finish();
}
});
btn.setEnabled(Settings.CurrentReport.hasPreviousItem());
btn = (Button)findViewById(R.id.btnSession);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "session");
setResult(RESULT_OK, intent);
finish();
}
});
btn = (Button)findViewById(R.id.btnEnd);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
intent.putExtra("mode", "end");
setResult(RESULT_OK, intent);
finish();
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Intent i = getIntent();
i.putExtra("mode", "end");
setResult(RESULT_OK, i);
finish();
break;
}
return super.onKeyDown(keyCode, event);
}
Im just guessing, but maybe Intent intent = getIntent(); is causing the problems. You could try to replace it with Intent intent = new Intent();
getIntent() returns the intent that started the current activity and shouldn't be used as a result.

Categories

Resources