finish() does not close current activity at first time - java

I'm trying to develop an app with two activities which they send data to each other. the problem is that I want tofinish(); second activity. when I click on goBackButton_ which I defined in XML_ SecondActivity comes up, when I click on the button again, it comes back to MainActivity as I wanted. why? and How to solve it?why it doesn't work at first time?
public class MainActivity extends AppCompatActivity {
Button button;
int REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("FirstActivity", "Hello from first activity");
startActivity(intent);
startActivityForResult(intent, REQUEST_CODE);
Log.d("TAG", "onClickListener: done!");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Log.d("TAG", "onActivityResult: Entered");
if(requestCode == REQUEST_CODE) {
Log.d("TAG", "onActivityResult: requestCode is OK");
if (resultCode == RESULT_OK) {
Log.d("TAG", "onActivityResult: result is returned OK");
String result = data.getStringExtra("SecondActivity");
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
Log.d("TAG", "onActivityResult: done!");
}
}
}
}
public class SecondActivity extends AppCompatActivity {
TextView textView;
Button goBackButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
goBackButton = (Button) findViewById(R.id.goBackButton);
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG", "onClick: Entered");
Intent returnIntent = getIntent();
returnIntent.putExtra("SecondActivity", "from second Activity");
setResult(RESULT_OK, returnIntent);
Log.d("TAG", "onClick: Message sent");
finish();
Log.d("TAG", "onClick: Activity finished");
//Intent myIntent = new Intent(SecondActivity.this,MainActivity.class);
//startActivity(myIntent);
}
});
textView = (TextView)findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if(extras != null){
String string = extras.getString("FirstActivity");
textView.setText(string);
}
}
}
solved

The problem is in your code -
startActivity(intent);
startActivityForResult(intent, REQUEST_CODE);
When you want to do startActivityForResult you don't have to do startActivity as this will first open your second activity without looking for result.
Remove startActivity(intent);

you have added startActivity(intent) as well as startActivityforResult(intent, REQUEST_CODE) which creates double instance of an activity use only startActivityforResult(intent, REQUEST_CODE);

Try remove startActivity(intent);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("FirstActivity", "Hello from first activity");
startActivityForResult(intent, REQUEST_CODE);
Log.d("TAG", "onClickListener: done!");
}
});

Related

onActivityResult not working with onBackPressed?

I have two activities, Activity1.java and Activity2.java. Activity1.java starts Activity2.java and I need Activity2.java to return some data back to Activity1.java when the user presses the back button on the Action Bar. But for some reason, it is not working...
Activity1.java:
public class Activity1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Intent intent = new Intent(this, Activity1.class);
int requestCode = 100;
startActivityForResult(intent, requestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("TEST", "RequestCode:" + requestCode);
Log.i("TEST", "ResultCode:" + resultCode );
switch (resultCode) {
case RESULT_OK:
Log.i("TEST", data.getStringExtra("MESSAGE"));
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Activity2.java
public class Activity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Activity1.class);
intent.putExtra("MESSAGE", "Hello from Activity 2!");
Log.i("TEST", "Setting result...");
setResult(RESULT_OK, intent);
finish();
super.onBackPressed();
}
}
When I run the app, only "Setting result..." is logged to Logcat. It seems like the onActivityResult override isn't even called. I've tried to change up the request code, result code, and setting the result in the onCreate() method of Activity2, but nothing works.
Could anybody help? Any help would be appreciated!
You are not calling the intent correctly:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
Intent intent = new Intent(this, Activity1.class);
int requestCode = 100;
startActivityForResult(intent, requestCode);
}
should be:
Intent intent = new Intent(this, Activity2.class);
You need to return the result when you press the ActionBar back/home button, but you added the code in the bottom back button.
So, transfer the code in Activity2 to be handled when the ActionBar back button is pressed, so Override onOptionsItemSelected, and the home button has an id of android.R.id.home.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(this, Activity1.class);
intent.putExtra("MESSAGE", "Hello from Activity 2!");
Log.i("TEST", "Setting result...");
setResult(RESULT_OK, intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
There are 3 problems with your code.
1. From Activity1, you start itself not Activity2. Change your code from
Intent intent = new Intent(this, Activity1.class);
to
Intent intent = new Intent(this, Activity2.class);
2. In onBackPressed() of Activity2, no need to declare Activity1 inside the intent, change your code from
Intent intent = new Intent(this, Activity1.class);
to
Intent intent = new Intent();
3. In Activity1, you should check requestCode before process further to make sure the data return from correct activity, because you might start more than one activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.i("TEST", "RequestCode:" + requestCode);
Log.i("TEST", "ResultCode:" + resultCode);
if (requestCode == 100) {
switch (resultCode) {
case RESULT_OK:
Log.i("TEST", data.getStringExtra("MESSAGE"));
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}

VideoView won't play on a different activity

I have this button which should play the video on another activity or to be specific in Main2Activity. The problem is that the video wouldn't play when I click the button. Everything is working fine, the only problem I have is when I click that said button.
MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final Uri videoUri = data.getData();
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
resultvideo.setVideoURI(videoUri);
mediacontroller.setAnchorView(resultvideo);
resultvideo.pause();
}
buttonPlay = (Button) findViewById(R.id.buttonPlay);
{
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediacontroller.show();
mediacontroller.setAnchorView(resultvideo);
resultvideo.start();
}
});
}
buttonFullScreen = (Button) findViewById(R.id.buttonFullScreen);
{
buttonFullScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("VIDEO_URI", videoUri.toString());
startActivity(intent);
}
});
}
}
Main2Activity:
public class Main2Activity extends Activity {
Button buttonPlay;
Button buttonFullScreen;
static final int REQUEST_VIDEO_CAPTURE = 1;
VideoView resultvideo;
MediaController mediacontroller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String uri = getIntent().getStringExtra("VIDEO_URI");
Uri videoUri = Uri.parse(uri);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
resultvideo = (VideoView)findViewById(R.id.videoView2);
resultvideo.start();
}
}
you will need to add
resultvideo.setVideoURI(videoUri);
after you initialed the resultvideo.

ANDROID How can I send result in a new Activity after scanning a QR Code?

Hello to everyone I'm trying to create an app that scan a QR Code.
In the main activity I want to make the scan of the QR Code and I want to send the result in a new Activity.
Here is my code
Main Activity.java:
public class MainActivity extends AppCompatActivity {
SurfaceView cameraView;
BarcodeDetector barcode;
CameraSource cameraSource;
SurfaceHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
cameraView = (SurfaceView) findViewById(R.id.cameraView);
cameraView.setZOrderMediaOverlay(true);
holder = cameraView.getHolder();
barcode = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
if(!barcode.isOperational()){
Toast.makeText(getApplicationContext(), "Sorry, Couldn't setup the detector", Toast.LENGTH_LONG).show();
this.finish();
}
cameraSource = new CameraSource.Builder(this, barcode)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(24)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(1920,1024)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
cameraSource.start(cameraView.getHolder());
}
}
catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
barcode.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if(barcodes.size() > 0){
Intent intent = new Intent(MainActivity.this, Result.class);
startActivityForResult(intent, 100);
intent.putExtra("barcode", barcodes.valueAt(0));
setResult(RESULT_OK, intent);
finish();
}
}
});
}}
Result.java:
public class Result extends AppCompatActivity {
TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
result = (TextView) findViewById(R.id.result);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 100 && resultCode == RESULT_OK){
if(data != null){
final Barcode barcode = data.getParcelableExtra("barcode");
result.post(new Runnable() {
#Override
public void run() {
result.setText(barcode.displayValue);
}
});
}
}
}}
But when I try to test the app in the result activity i can't see the result.
What's wrong?
Thank you to everyone
In Result activity the retrieving of the data should be in onCreate method, not in onActivityResult, your Result class should look like this:
public class Result extends AppCompatActivity {
TextView result;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
result = (TextView) findViewById(R.id.result);
final Barcode barcode = getIntent().getParcelableExtra("barcode");
result.setText(barcode.displayValue);
}
}
and in MainActivity, this line:
intent.putExtra("barcode", barcodes.valueAt(0));
should be before
startActivityForResult(intent, 100);
not after, like this:
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("barcode", barcodes.valueAt(0));
startActivityForResult(intent, 100);
finish();
You only use startActivityForResult if you want the starting activity to be returned with an result from the called activity. In your case just start the result activity by calling startActivity and get the data in the result activity by using getIntent.
the code You wrote in your MainActivity
Intent intent = new Intent(MainActivity.this, Result.class);
startActivityForResult(intent, 100);
intent.putExtra("barcode", barcodes.valueAt(0));
setResult(RESULT_OK, intent);
finish();
is wrong Actually it should be like the following and please do not ActivityForResult
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("barcode", barcodes.valueAt(0));
startActivityForResult(intent, 100);
finish();
And for getting result from Your MainActivity in ResultActivity onCreate() method use following code if you are going to show result then
TextView YourResult
YourResult = (TextView) findViewById(R.id.TextView_YourResult);
final Barcode barcode = getIntent().getParcelableExtra("barcode");
result.setText(barcode.displayValue);

Display text to another class

I have a showAddForm button like the imej below in Claims.java.
When the + button is pressed, it will show Alert Dialog Window with radio buttons. When the radio button is checked, it will goes to specific activity. In the activity, it has an editText and a save button. I want the value on the editText display on the showAddForm button when the save button in the activity is clicked. How can I do to achieve this?
Claims.java
public class Claims extends Fragment {
private TextView c;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View claims = inflater.inflate(R.layout.claims, container, false);
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
AlertDialogRadio();
}
};
Button button1 = (Button) claims.findViewById(R.id.button10);
Button button = (Button) claims.findViewById(R.id.button8);
button1.setOnClickListener(listener);
c=(TextView)claims.findViewById(R.id.textView49);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), CameraMain.class);
startActivity(intent);
}
});
return claims;
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivity(intent);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivity(intent);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivity(intent);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivity(intent);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivity(intent);
}
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("text");
c.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
Assume the user choose Project.
Project1.java
public class Project1 extends AppCompatActivity {
private static String text;
private static EditText txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
text = txt.getText().toString();
returnIntent.putExtra("text", text);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
Now when I click save button in Project1.java, it return to the AlertDialogRadio which is not I want and the text still not displaying on the textView!!! ANYONE CAN HELP?????
You can use startActivityForResult() and override onActivityResult() in your activity. You can use setResult() in the second activity to pass whatever you want to your caller activity.
Example here and here
edit:
If you want it to use from a Fragment, you have to write this in your Activity that is holding the Fragment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
This will pass the result to your fragment, so you can handle the result inside your fragment.
And as I already mentioned, you have to use startActivityForResult() instead of startActivity()
as #keybee said you should use startActivityForResult() to start the project.class from your dialog.
In the Project1.Class when you click save use setResult() to send the value back to the claims.class(Dont do startActivity() again. just use finish() ).
and in your Claims.class use onActivityResult(int requestCode, int resultCode, Intent data) to recieve the value sent from the project1.class.
you can do a setText() on showAddForm button in the onActivityResult(int requestCode, int resultCode, Intent data) function

onActivityResult (Re) called

I have the following situation:
Parent Activity:
ParentActivityClass
{
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState)
{
.....
intent = new Intent(this, ChildActivity.class);
startActivityForResult(intent, 202);
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startActivity(intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.d("Log", "OK");
}
Child Activity
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
#Override
public void finish()
{
Intent intent = new Intent();
intent.putExtra("extra", ".....");
setResult(RESULT_OK, intent);
super.finish();
}
When calling the finish() method of child activity, onActivityResult is called in the parent activity. When the child activity is open for the 2nd time, onActivityResult is not called.
Where is the mistake?
The problem I see is that you are calling startActivity(intent) instead of startActivityForResult(intent, 202) within you View.OnClickListener.
Edit:
I'm assuming that you are going to the ChildActivity through the button.
Hope it helps ;)
Best Regards

Categories

Resources