button triggering function and intent at the same time. Android - java

So i am new to android and java, and i understand that i should move between activities with intents.
Intent randomintent = new Intent(profile.this, loggedactivity.class);
randomintent .putString("name", namestring);
startActivity(randomintent);
The thing is, that i also have a function that i want it to be executed just before this intent takes the user to another activity. So my code looks something like this.
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
//this uploads the image, it works without the intent i added
infosendstuff();
//this should be executed after the image is uploaded and stores the image link to a database (also works)
Intent randomintent = new Intent(profile.this, loggedactivity.class);
randomintent .putString("name", namestring);
startActivity(randomintent);
}
});
The problem seems to be the intent, when used, it ignores the other two functions above it, that upload the picture and store the link for that picture.
The goal is to upload the picture, once done, get the link, send the link to another activity though the intent (with the bundle) and thats about it.

it's better to use AsynkTask.
create a class, it should extend from AsynkTask. in doInBackground, upload your photos, process the response and send the link. and in onPostExecute method, go to the other activity.
update 1
class myClass extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
String result = uploadPhotos();
proccess result;
send links;
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Intent randomintent = new Intent(profile.this, loggedactivity.class);
randomintent .putString("name", namestring);
startActivity(randomintent);
}
}
now you can use it like this:
new myClass().execute();
but before coding, i think you need to study more about web Connection process in android.

It seems that uploadImage() Method does some stuff on the network and since the network request and response is done in another thread the code continue to execute and loggedactivity will show before the uploadImage() method is done.
So one way is that you force main thread to wait for network thread and after the network thread is done main thread continue to work but it cause the UI thread to freeze.
another way is that you should use callbacks that when the uploadImage() method is done some method will invoke and in that method you start your new activity. something like code below :
uploadImage(new ResponeListener() {
#override
public void onDataReady(String nameString) {
Intent randomintent = new Intent(profile.this,loggedactivity.class);
Bundle b = new Bundle();
b.putString("name", namestring);
startActivity(randomintent);
}
}

Related

how to open a webpage, fill an html form, submit it, get the form's result and then post the information to another activity in android

We have an aspx page with a form in it and we can only process this form in a browser-based environment (ie we cannot create a web service for it.
What we want to do is that we want to process this information in an android application. We want to send some initial data to this page, let the user fill it, submit the form, and then return the results to the calling activity, so we can show a proper message and act accordingly.
let me give an example for this usecase:
We are in activity A and in this activity we have a button that triggers the start of our journey:
//we are in activity A
mOurButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("additional_data_we_need", adittionalData);
startActivityForResult(intent, REQUEST_CODE);
}
});
Now we are in activity B and here, we should comunicate with that webpage that I was talking about, passing it the additionalData that is in this activity's extra bundle (it is acceptable if we do it using query strings or any other way).
After the user fills the form, and hit submit,we do some operation on it and return some results to another (web)page or in the current (web)page's postback (again it is acceptable if we use query strings, post method or any other way; whicever way that works for this senario). We get this returned result in android side and then get the result to ActivityA :
//we are in acitivity B
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
int adittionalData = getIntent().getExtras().getIntExtra("adittional_data_we_nedd");
//this is the first place that I don't know what to do
callTheWebPageAndGiveItTheData(adittionalData);
}
public void SomeListenerOfTheReturnedDataFromTheWebpage(Bundle returnedData //doesn't necessarily need to be of bundle type) {
intent intent = new Intent();
intent.putExtra("return_bundle", returnedData);
setResult(Activity.RESULT_OK, intent);
finish();
}
What can I do to achieve this goal?
Thanks in advance for your kind answers

how to end an outgoing call after activity result?

I have a outGoingCall broadcast receiver.
basically I want it to intercept any outgoing call and show a dialog for certain pre-defined numbers.
so I made this broadcast init an activity which inits an FragmentDialog which init a AlertDialog.
When the user click "no"
I want to stop the call from happening.
I know setResultData(null); in the broadcast should do it.
But how can I pass the dialog result to the broadcast ?
there is no onActivityResult() in a broadcast.
I know how to pass it till the activity only.
fragmentDialog code:
public class YesNoDialogFragment extends DialogFragment {
private YesNoDialogFragmentListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
mListener = (YesNoDialogFragmentListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
here is my activity code:
public class MainActivity extends FragmentActivity implements
YesNoDialogFragmentListener {
public static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showYesNoDialog();
}
#Override
public void onDialogPositiveClick() {
// how to send result to receiver ??
finish();
}
here is my receiver code:
#Override
public void onReceive(final Context context, final Intent intent) {
Log.v(Constants.LOGTAG, "OutgoingCallReceiver onReceive");
if (intent.getAction()
.equals(OutgoingCallReceiver.OUTGOING_CALL_ACTION)) {
Log.v(Constants.LOGTAG,
"OutgoingCallReceiver NEW_OUTGOING_CALL received");
// get phone number from bundle
String phoneNumber = intent.getExtras().getString(
OutgoingCallReceiver.INTENT_PHONE_NUMBER);
if ((phoneNumber != null)
&& phoneNumber
.equals(OutgoingCallReceiver.ABORT_PHONE_NUMBER)) {
Toast.makeText(
context,
"NEW_OUTGOING_CALL intercepted to number 123-123-1234 - aborting call",
Toast.LENGTH_LONG).show();
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
SharedPreferences sharedPreferences = context
.getSharedPreferences(Constants.SHARED_PREF_NAME,
Context.MODE_PRIVATE);
boolean isBloacked = sharedPreferences.getBoolean(
Constants.IS_NUMBER_BLOCKED, true);
if (isBloacked) {
// dialog and then:
setResultData(null);
}
}
as you can see i tried to share the activity result via shared preferences, how come the code is async and the setResultData(null); is called before the dialog is shown?
from what I know there is no way to end the call besides setResultData(null);
You have to go through an activity (or a fragment) and then pass it to the receiver. Whenever you start a dialog, it has a parent activity, and that is where the result is sent. Just add something to your activity that passes the result on to your receiver.
You might actually consider altering your design to put more of your logic into the activity. Receivers are generally intended to be pretty lightweight objects that receive notification of something, pass it on to somewhere else. and then go away. Anyway, I obviously don't know your code, so maybe this doesn't make sense.
EDIT
Sorry, I understand your problem better now. I'm used to only working with setResultData when one activity has launched another activity, and the 2nd one wants to send something back to the 1st one. But you are using it to stop an ordered broadcast, right?
Unfortunately, Android does now allow you to do what you are trying to do. This section of the doc specifically says that you cannot show a dialog from within a broadcast:
http://developer.android.com/reference/android/content/BroadcastReceiver.html#ReceiverLifecycle
I think what you need to do is always return setResultData(null) right after starting your activity. If the user then clicks "no" in your dialog, then you are done. But if the user clicks "yes" (I'm assuming there is a "yes") then you would have to go ahead and make the call, and make sure you don't catch it again in your receiver.
Does that make sense? Sorry for my confusion earlier.

Stopping a Handler Based Runnable after AsyncTask

I'm fairly new to Android programming.
Simple Explanation for my problem:
I have an async task to collect JSON based data after every 20 seconds based on this runnable:
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
mTask = new JSONParse();
mTask.execute();
handler.postDelayed(this, 20000);
}
};
How do I stop it when I want to?
Detailed Explanation for my Problem:
Within this Async Task, I check if the data is available, and if not available, I go back to the mainscreen by first invoking
mTask.cancel(true);
and then in the onCancelled() method as follows:
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
mTask.cancel(false);
pDialog.dismiss();
displayWrongPhoneToast();
}
where displayWrongPhoneToast() is a simple function as follows:
public void displayWrongPhoneToast() {
Toast.makeText(getApplicationContext(),
"Sorry! Enter at least one field to continue.",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(TabActivity.this, MainActivity.class);
startActivity(intent);
}
The problem I have is, the handler is causing the runnable to execute in the background, which is making the application request data over and over again and causing the displayWrongPhoneToast() to execute over and over again.
I tried some methods I found online to stop the runnable, but it refuses to. Any help is appreciated. Thanks :)
You have to call
handler.removeCallbacks(r).

How to call takePicture() method from another activity in android?

I have main activity class where i have written takePicturefromCamera() method like this:
public void takePicturefromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mFileTemp);
}
else {
// The solution is taken from here: http://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
} catch (ActivityNotFoundException e) {
Log.d("TAG", "cannot take picture", e);
}
}
Now I have another class where i am doing some cropping part and my requirement is if while cropping user feels that he want to take some another picture instead of previous there i want to call above takePicturefromCamera() method of main activity class on some button click. Can anyone help me how can I do like this. I have tried by doing like this:
retake_button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// setResult(RESULT_CANCELED);
main m = new main();
m.takePicturefromCamera();
}
});
But it gives me error NullPointerException at mImageCaptureUri = Uri.fromFile(mFileTemp);
Please help me.
I would suggest you to keep takePicturefromCamera() in separate class, and then call this method passing the activitycontext and data required to it.
Or else you can make Activity2 extend Activity1 and use takePicturefromCamera().
Make that method as static so you can use it anywhere in your application.
Also add one more parameter "File" to your function. By this, you also have flexibility to use the same function for different file object in your application.
Hope this will help you.

Android - After closing an activity, when I run the app again, two activities run at the same time. How can I avoid it?

So I've got an activity in my android app, that runs on start.
This activity is just a page with a start button.
When I press the start button, it calls another activity and closes itself:
Intent i = new Intent(this, Dictating.class);
startActivity(i);
finish();
The other Activity is using Text-to-speech to dictate some words.
Now I've got something weird happening:
1) I listen to the dictating.
2) I press back button: dictating stops (what I want)
3) I run again the app, press the start button. Now I have my new activity running and dictating, but in the back I can hear the older Activity that resumed where it was, and continues dictating.
I would like for the new activity to start all over again, and not keep the other activity.
How can I do that ?
PS: This is an activity problem, and not a text-to-speech problem as I'm flushing the text-to-speech each time, It could not be kept in the memory
Thank you
EDIT:
Here is the onCreate of my Dictating class, there is tons of code in this class, I obviously don't want to post all my code, so here is some parts:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.streaming);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
this.txtCurrentWord = (TextView) findViewById(R.id.txtCurrentWord);
this.btnPlayPause = findViewById(R.id.btnPlayPause);
this.btnPlayPause.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
this.tts = new TextToSpeech(this, this);
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
there are a few weird things I'm doing like:
Runnable task = new Runnable() {
public void run() {
//runs on ui
runOnUiThread(new Runnable() {
public void run() {
readNextWord();
}
});
}
};
worker.schedule(task, 1, TimeUnit.SECONDS);
this delays the next word by one second, and then executes a fonction in the main ui thread. not sure if this matter
And some flushing at the end:
#Override
public void onDestroy() {
tts.shutdown();
super.onDestroy();
}
You need to add launchMode property to your activity inside AndroidManifest file, for more detail see "Using the manifest file"
This question is over a year old, but I can't believe no one ever gave you the right answer. Also, I don't think you should have accepted an answer that clearly didn't solve anything for you. By accepting such answers, you're just cluttering the StackOverflow google search results with junk for other people with the same problem.
The flushing you do at the end is completely wrong. According to the Activity lifecycle, onDestroy() is never guaranteed to be called. If you want to make sure the flushing gets done properly, do it inside of onPause().
For now the solution I'm giving you does fix the main problem you've described. However, if you do get the time to do a more complete rewrite, you'll want use a service that you bind to your activity. That will give you the finer control you require.

Categories

Resources