Android : Close Activity after Result - android

I've written a Small Google Maps Application, which makes me a few Problems.
The LocationListener i wrote, overrides the onProviderDisabled Method to call an Activity, where the User can Switch on his GPS.
This do the Job well, but one Problem is still there. If i close the Maps_Activity and after that shut down the GPS, it seems, that the Listener is already running, because the Activity (the one who says me, that the GPS is not running) still pops up.
The LocationListner as followed:
public class LocationUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
mMyLocationOverlay.enableMyLocation();
mMyLocationOverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
mMapView.getController().animateTo(
mMyLocationOverlay.getMyLocation());
}
});
}
#Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(MapActivity.this, NoGpsActivity.class);
startActivity(i);
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS ready", Toast.LENGTH_LONG).show();
}
}
The NoGPSAcivity.class as followed:
public class NoGpsActivity extends Activity {
private OnClickListener mEnableGPSListener = new OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps_not_available_overlay);
Button mEnableGPS = (Button)findViewById(R.id.enablegps_button);
mEnableGPS.setOnClickListener(mEnableGPSListener);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 0){
finish();
}
}
}
Thank you for your help!

In your onDestroy() method you need to call removeUpdates(locationListener) so it will stop receiving updates.
Also another thing to watch out for is that the "Home" key in Android generally means "minimize" (leaving your program in the background) while the "Back" key means "close". So if your hitting home to exit, most likely it is still running.

Related

Zxing scanned result how to paste on editText

Hello I want to thank you in advance for your answers. My problem is I am using Zxing to scan qr codes. And I want to paste the scan value on the my edit text at Login Activity.
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.Result;
import com.logizard.logizard_go.R;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class ScanResult extends AppCompatActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
// Log.v("tag", rawResult.getText()); // Prints scan results
// Log.v("tag", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
Login.editTextUser.setText(rawResult.getText());
onBackPressed();
// If you would like to resume scanning, call this method below:
//mScannerView.resumeCameraPreview(this);
}
}
This is the sample code that I use but every time I use the button for scan nothing happens.
It looks like that you have a Login(Activity) that open the ScanResult(Activity) and you want to return the value of the scanned to Login
I suggest to you to look this doc, but also maybe you could move the handlingscan part of your code to Login activity
... implements ZXingScannerView.ResultHandler{
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
editTextUser.setText(rawResult.getText());
}
}
BETTER do like that
in Login
static final int GET_SCANNED = 1;
...
private void openScanResult(){
Intent i = new Intent(this, ScanResult.class);
startActivityForResult(i, GET_SCANNED);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GET_SCANNED) {
if(resultCode == Activity.RESULT_OK){
String result = data.getStringExtra("scanned");
editTextUser.setText(result)
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
in ScanResult
#Override
public void handleResult(Result rawResult) {
Intent returnIntent = new Intent();
returnIntent.putExtra("scanned",rawResult.getText());
setResult(Activity.RESULT_OK,returnIntent);
finish();
}

How to play Media player after backing from another activity?

The Media Player work well when I start the app and click the button. However, when I hit the Home button or when I go to another activity and then I cannot play Media file any more when I come back to the MainActivity. Here is my code:
public void playMedia(View view){
if(mp.isPlaying()){
mp.pause();
}
else
mp.start();
}
#Override
protected void onPause(){
super.onPause();
SOSPlayer.pause();
}
#Override
protected void onResume(){
super.onResume();
SOSPlayer.seekTo(0);
}
#Override
protected void onDestroy() {
super.onDestroy();
SOSPlayer.stop();
SOSPlayer.release();
}
#Override
protected void onStop() {
super.onStop();
SOSPlayer.stop();
}
I thing you call playMedia method on layout as:
<Button
...
android:onClick="playMedia"
..
/>
What you need is to play that media again after getting back from previous activity .. you need to start that activity for result with startActivityForResult and listen to feedback onActivityResult to play the media again. Here is a simple implementation:
private static final int REQUEST_ID = 0x0001;
private void startActivity() {
Intent intent = new Intent(getApplicationContext(), DifferentActivity.class);
startActivityForResult(intent, REQUEST_ID);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ID:
playMedia(null);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}

How I get the response of a native activity?

For example: my app calls a native settings activity, by
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(myIntent, CODE);
Then when it is finished (by pressing the back button for example) I want to know. I tried this way, but the onActivityResult() wasn't called when the native activity was finalized... so my app wasn't informed...
How I have to do? Anyone knows?
Thanks...
EDIT:
Thanks every one.
The complete code is that:
public class MainActivity extends AppCompatActivity {
public static final int DIALOG_CODE = 0x1;
private TextView txtGps;
private TextView txtNet;
private LocationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first();
}
private void checkConfigs() {
boolean gps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean net = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
setWidgets(gps, net);
if (gps && net){
Toast.makeText(this, "Configurações Ok!", Toast.LENGTH_SHORT).show();
} else {
DialogConfig.exibDialog(getFragmentManager());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == DIALOG_CODE) && (resultCode == RESULT_OK)){
checkConfigs();
} else {
Toast.makeText(this, "As config não foram alteradas!", Toast.LENGTH_SHORT).show();
}
}
public void setWidgets(boolean gsp, boolean net){
if (gsp){
txtGps.setText(R.string.gps_hab);
} else {
txtGps.setText(R.string.gps_n_hab);
}
if (net){
txtNet.setText(R.string.wifi_hab);
} else {
txtNet.setText(R.string.wifi_n_hab);
}
}
private View.OnClickListener onClickCheck() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
checkConfigs();
}
};
}
#SuppressWarnings("ConstantConditions")
private void first() {
txtGps = (TextView) findViewById(R.id.txt_gps);
txtNet = (TextView) findViewById(R.id.txt_net);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
findViewById(R.id.btn_check).setOnClickListener(onClickCheck());
}
public static class DialogConfig extends DialogFragment {
public static void exibDialog(FragmentManager fm){
new DialogConfig().show(fm, "dialog");
}
#Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("As conf não estão corretas! Alt configs?")
.setPositiveButton("Ok", onOk())
.setNegativeButton("Cancel", onCancel())
.create();
}
private DialogInterface.OnClickListener onCancel() {
return new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
};
}
private DialogInterface.OnClickListener onOk() {
return new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(myIntent, DIALOG_CODE);
}
};
}
}
}
[Resolved]
Thanks again to every one, I tried again, creating a interface of callback in dialog, so the activity could be informed and call the other native settings activity by itself , and got the response in onActivityResult(), but comparing only a code (not by RESULT_OK), This way worked. But there is a other way (like was suggested) that use the lifecycle, to me seems more easy.
I basically tried what you tried and it works for me.
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);
and for onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(PREFIX, "onActivityResult");
}
When I came back to the app, onActivityResult was called.
Not sure what you are doing different. can you show your onActivityResult code?

Android code to add and view data through application

I am developing a Task manager( a simple one) to learn android and this is my short description.
I am making two activities one to view task and other to add ( and I am using an Application class through which i add the task)..
when i add the task on the addtask activity my viewtask activity still remains blank. Could you help me out.
This is my viewTask activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
setupviews();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
System.out.println(requestCode);
if (requestCode == 1) {
showtask(); // your "refresh" code
}
}
public void OnResume()
{
super.onResume();
System.out.println("Its working...");
showtask();
}
/*public void onPause(){
super.onPause();
}*/
public void showtask()
{
ArrayList<Task> task=gettma().gettask();
StringBuffer sb=new StringBuffer();
for(Task t:task){
sb.append(String.format("* %s\n", t.toString()));
System.out.println("Its working...again");
}
taskText.setText(sb.toString());
}
private TaskManagerApplication gettma() {
TaskManagerApplication tma1=(TaskManagerApplication)getApplication();
return tma1;
}
private void setupviews() {
AddButton=(Button)findViewById(R.id.AddButton);
taskText=(TextView)findViewById(R.id.TextList);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(ViewTask.this,AddTask.class);
startActivity(intent);
}
});
}
}
And this is my Addtask activity.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtask);
setupviews();
}
protected void addtask() {
String name=EditText.getText().toString();
Task t= new Task(name);
//System.out.println("its working here");
gettma().addTask(t);
finish();
}
private TaskManagerApplication gettma() {
TaskManagerApplication tma=(TaskManagerApplication)getApplication();
return tma;
}
private void setupviews() {
EditText=(EditText)findViewById(R.id.EditText);
AddButton=(Button)findViewById(R.id.AddButton1);
CancelButton=(Button)findViewById(R.id.CancelButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addtask();
}
});
CancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
Please Help
EditText=(EditText)findViewById(R.id.EditText);
This is the line in your setupviews(). You cannot do this because EditText is a class and you need a variable of that type to which you can assign a value. It must be EditText followed by some variable name.
if (requestCode == 1) {
showtask(); // your "refresh" code
}
This is in your onActivityResult(). You aren't checking the resultCode to check if the called Activity failed to do the operation that would produce a result.
Also, in numerous places you arent following the Java naming convention. Please, use upper and lower cases properly when naming variables and classes.

Android switching activities

I have 2 activities. One called Login and another called ListDeals. Login has a form with a submit button which, when pressed, should switch our activity to ListDeals. This works.
However, in Logcat I don't get a message saying that the activity has started. Also, when in ListDeals, if the user presses the back button, both activities should be killed. I looked around and this is what I came up with:
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
Button submit=(Button)findViewById(R.id.submit);
submit.setOnClickListener(onSubmit);
}
private View.OnClickListener onSubmit=new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent=new Intent(view.getContext(),ListDeals.class );
startActivityForResult(myIntent,0);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login_screen, menu);
return true;
}
#Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
if(resultCode==2) {
finish();
}
}
}
public class ListDeals extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deals_list);
System.out.println("starting activity");
}
#Override
protected void onDestroy() {
System.out.println("dude");
setResult(2);
super.onDestroy();
}
protected void onStop(){
setResult(2);
super.onStop();
}
}
However, when I press the back button, It takes me back to the Login activity which is not what I want.
In your click handler, onSubmit, just finish your login activity, like this. That way, it won't be on the activity stack, and as a result, pressing back from your other activity will bring the user back to where they started.
private View.OnClickListener onSubmit=new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent myIntent=new Intent(view.getContext(),ListDeals.class);
startActivity(myIntent);
finish();
}
};
Also, to address you second question, use the Log class methods, such as Log.i or Log.d for debug messages, those will show up in logcat.
Finish Login before starting the new Activity. Besides you don't need the result.
private View.OnClickListener onSubmit=new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent=new Intent(Login.this, ListDeals.class );
startActivity(myIntent);
Login.this.finish() // add this to finish it.
}
};

Categories

Resources