How I get the response of a native activity? - android

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?

Related

How to send data by click back button?

I'm using two activities, MainActivity & SubActivity.
MainActivity.class
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sub = new Intent(this, SubActivity.class);
sub.putExtra("name", "a");
startActivity(sub);
}
}
}
}
SubActivity
public class SubActivity extends AppCompatActivity {
EditText text;
#Override
protected void onCreate() {
...
text.setText(getIntent().getStringExtra("name"));
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
In this case, if I change the text in EditText in SubActivity, I want to send changed text data to MainActivity when back button pressed in SubActivity(It means SubActivity onDestroy()). I don't want to make the second MainActivity like this in SubActivity.
#Override
public void onBackPressed() {
Intent intent = new Intent (this, MainActivity.class);
intent.putExtra("name", text.getText().toString());
startActivity(intent);
}
Is there any way to send text data when SubActivity removed from the activity stack?
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sub = new Intent(this, SubActivity.class);
sub.putExtra("name", "a");
startActivityForResult(sub , 2);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("name");
textView1.setText(message);
}
}
}
And
#Override
public void onBackPressed() {
Intent intent = new Intent (this, MainActivity.class);
intent.putExtra("name", text.getText().toString());
setResult(2,intent);
}
You need to use startActivityForResult() if you expect to have a return from the started activity.
After that, you'll also need to implement onActivityResult() method on the start activity to actually read the returned data.
Use startActivityForResult instead of startActivity
MainActivity :
public class MainActivity extends AppCompatActivity {
Button button;
String name= "a";
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sub = new Intent(this, SubActivity.class);
sub.putExtra("name", name);
startActivityForResult(sub,100);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 100) {
String name = data.getStringExtra("name);
text.setText(name);
}
}
}
}
SubActivity:
public class SubActivity extends AppCompatActivity {
EditText text;
#Override
protected void onCreate() {
...
text.setText(getIntent().getStringExtra("name"));
}
#Override
public void onBackPressed() {
Intent resultIntent = new Intent();
resultIntent.putExtra("name", "your_editext_value");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
You can use SharedPreference for storing value and update it or use it anywhere instead of using Intent
like In MainActivity
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Editor edit=sp.edit();
edit.putString("name","a");
edit.commit();
Intent sub = new Intent(this, SubActivity.class);
startActivity(sub);
}
}
} }
and In SubActivity
public class SubActivity extends AppCompatActivity {
EditText text;
#Override
protected void onCreate() {
...
text.setText(sp.getString("name",""));
text.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Editor edit=sp.edit();
edit.putString("name",s.toString);
edit.commit();
} });
}
#Override
public void onBackPressed() {
super.onBackPressed();
}}
To use value from SharedPreference
sp.getString("name","");
For using SharedPreference look at this https://developer.android.com/training/data-storage/shared-preferences#java

Speech recognition result does not update EditText

I tried using a "speech to text" feature in my app.
it opens up the recording window/ dialog or whatever but the text doesn't show.
this is the code:
public void onTalk(View v){
promptSpeechInput();
}
public void promptSpeechInput()
{
Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT,"say something");
try{
startActivityForResult(i, 50);
}
catch(ActivityNotFoundException e){
Toast.makeText(this,"sorry your device doesnt support speech language",Toast.LENGTH_LONG).show();
}
}
then there's the onResult part:
public void onActivityResult(int request_code, int result_code, Intent i){
super.onActivityResult(request_code,result_code,i);
if (request_code==RESULT_OK)
if(i!=null) {
EditText locationTS = (EditText) findViewById (R.id.locationET);
ArrayList<String> result = i.getStringArrayListExtra((RecognizerIntent.EXTRA_RESULTS));
locationTS.setText(result.get(0));
}
}
locationTS is an EditText, and it does not show any text after i talk.
This worked in my case:
I had a separate Helper class as:
public class SpeechRecognitionHelper {
private static final int VOICE_RECOGNITION_REQUEST_CODE=101;
public static void run(Activity activity){
if(isSpeechRecognitionActivityPresent(activity)){
startRecognition(activity);
}
else {
Toast.makeText(activity,"You must install Google Voice Search",Toast.LENGTH_LONG).show();
installGoogleVoiceSearch(activity);
}
}
private static boolean isSpeechRecognitionActivityPresent(Activity activity){
try {
PackageManager packageManager = activity.getPackageManager();
List activities = packageManager.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH),0);
if (activities.size()!=0){
return true;
}
}
catch (Exception e){
}
return false;
}
public static void startRecognition(Activity activity){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Say Something");
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
activity.startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
}
private static void installGoogleVoiceSearch(final Activity activity){
Dialog dialog = new AlertDialog.Builder(activity)
.setMessage("For recognition Install Google Voice Search")
.setTitle("Install voice search?")
.setPositiveButton("Install", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.voicesearch"));
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
}
Then in the MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final int VOICE_RECOGNITION_REQUEST_CODE=101;
private static final int CAMERA_REQUEST=201;
private Button buttonVoiceCommand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonVoiceCommand = (Button)findViewById(R.id.buttonVoiceCommand);
buttonVoiceCommand.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.buttonVoiceCommand){
run(MainActivity.this);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(matches.size()>0){
if(matches.get(0).indexOf("camera")>0){
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_REQUEST);
}
else {
Toast.makeText(this,matches.get(0),Toast.LENGTH_LONG).show();
}
}
}
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
//Perform whatever you want to do (-.-)
Toast.makeText(this,"Camera Working",Toast.LENGTH_LONG).show();
}
}
}
I Toast the content of matches.get(0) You just have to set it in an edit text

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.

can't call onactivity result function after child activity is finished

i am using following codes.
addNewReceipt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), AddReceipt.class);
myIntent.putExtra("receiptList", receipts);
startActivityForResult(myIntent, RECEIPT_ADD);
}
});
}
#SuppressWarnings("unchecked")
public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data)
{
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == RECEIPT_ADD)
{
receipts = (ArrayList<Receipt>) data.getSerializableExtra("receiptList");
addReceiptsInListView();
}
}
}
The code for AddReceipt class is as follow,
#Override
public void finish() {
Intent data = new Intent();
data.putExtra("receiptList", receipts);
setResult(RESULT_OK, data);
super.finish();
}
#SuppressWarnings("unchecked")
public void onCreateCall()
{
done.setOnClickListener(new OnClickListener()
{ //receiptAddBtn
#Override
public void onClick(View v)
{
String error = "";
Receipt receipt = new Receipt();
receipt.comments = comments.getText().toString();
receipt.referenceNo = receiptNo.getText().toString();
receipt.image = imageSelected;
if (receipt.image == null || receipt.referenceNo == "" )
{
error = "Please input Receipt No. and attach Image";
displayAlert(error);
}
else
{
receipts.add(receiptCounter,receipt);
finish();
}
}
});
}
The problem is, when the activity is finished... and i pass this receipt, in my previous class from which i call this activity public synchronized void onActivityResult Never works.
The back button is not ending activity either.
Please tell me where i am wrong,.
Best Regards
Here is the solution to your problem
#Override
public void finish() {
Intent data = new Intent();
data.putExtra("receiptList", receipts);
setResult(Activity.RESULT_OK, data);
super.finish();
}

setResult doesn't call onActivityResult

I have two activities which starts the same sub-activity for result.
But in only one of them onActivityResult works.
Here are parts of my code
This is my first Activity. As you can see it calls NewCommentActivity in startActivityForResult and this part works fine
public class OfferActivity extends ListActivity implements View.OnClickListener {
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.offer_menu_comment:
Intent commentIntent = new Intent(this, NewCommentActivity.class);
commentIntent.putExtra(Offer.OFFER, offer);
startActivityForResult(commentIntent, COMMENT_REQUEST_CODE);
return true;
...
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case COMMENT_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Integer commentCnt = offer.getCommentCnt() + 1;
offer.setCommentCnt(commentCnt);
commentButton.setText(getString(R.string.offer_comments, offer.getCommentCnt()));
}
break;
}
}
...
}
Here is my second activity which calls NewCommentActivity too, but here onActivityResult is not called
public class CommentsActivity extends ListActivity{
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case COMMENT_ITEM_ID:
Intent commentIntent = new Intent(this, NewCommentActivity.class);
commentIntent.putExtra(Offer.OFFER, offer);
startActivityForResult(commentIntent, COMMENT_REQUEST_CODE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case COMMENT_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Integer commentCnt = offer.getCommentCnt() + 1;
offer.setCommentCnt(commentCnt);
Comment comment = data.getParcelableExtra(Comment.COMMENT);
commentImageListAdapter.addItemAtFront(comment);
}
break;
}
}
...
}
And here is code for NewCommentActivity :
public class NewCommentActivity extends Activity implements View.OnClickListener {
private static final String TAG = "Gift/NewCommentActivity";
private Offer offer;
private EditText editText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_comment);
offer = getIntent().getParcelableExtra(Offer.OFFER);
editText = (EditText) findViewById(R.id.new_comment_text);
Button button = (Button) findViewById(R.id.new_comment_button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (editText.getText().length() > 0) {
new AddCommentAsyncTask().execute(offer, editText.getText().toString());
}
}
private class AddCommentAsyncTask extends AsyncTask<Object, Void, Comment> {
private String errorString;
private ProgressDialog progressDialog;
#Override
protected Comment doInBackground(Object... objects) {
Offer offer = (Offer) objects[0];
String text = (String) objects[1];
Comment comment = null;
try {
comment = ServiceContainer.getService().addComment(offer, text);
} catch (OfferException e) {
Log.e(TAG, "exception in comment", e);
int id;
if ((id = e.getErrorStringId()) != -1) {
errorString = getString(id);
} else {
errorString = e.getLocalizedMessage();
}
cancel(false);
}
return comment;
}
#Override
protected void onPreExecute() {
progressDialog = Utils.newSpinnerDialog(NewCommentActivity.this, R.string.sending);
}
#Override
protected void onCancelled() {
progressDialog.dismiss();
AlertDialog.Builder builder = Utils.newAlertDialog(NewCommentActivity.this, errorString, true);
builder.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
new AddCommentAsyncTask().execute(offer, editText.getText().toString());
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
setResult(RESULT_CANCELED);
finish();
}
})
.create()
.show();
}
#Override
protected void onPostExecute(Comment comment) {
progressDialog.dismiss();
Intent intent = new Intent();
intent.putExtra(Comment.COMMENT, comment);
setResult(RESULT_OK, intent);
finish();
}
}
And finally AndroidManifest for all activities:
<activity android:name=".activity.OfferActivity"
android:configChanges="orientation"/>
<activity android:name=".activity.CommentsActivity"
android:configChanges="orientation"
android:label="#string/comment_activity_title"/>
<activity android:name=".activity.NewCommentActivity"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation"
android:label="#string/new_comment_activity_title"/>
</application>
Please help me.
Thanks.

Categories

Resources