How to send data by click back button? - android

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

Related

return back data to another activity

i have two activities A and B i am using a button to be directed to activity B i managed to write a code so it code be turned back to activity A automatically without any buttons after 5 seconds
but now i want when it return back to return data to A how it can be done
i wrote the code in A to recieve data but don't know what to add in activity B
Activity A ::
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button two = (Button) findViewById(R.id.button2);
Recieve = (TextView) findViewById(R.id.textView4);
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent Intent = new Intent(MainActivity.this, Gps.class);
//startActivity( Intent);
sendMessage();
}
});
}
public void sendMessage() {
Intent intent = new Intent(MainActivity.this, Hello.class);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Response = data.getStringExtra("key");
Recieve.setText("msg is " + Response);
}
}
Activity B::
public class Hello extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent i = new Intent(Hello.this, MainActivity.class);
Hello.this.startActivity(i);
Hello.this.finish();
}
}, 5000);
}
}

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 call method from intent

I've this code:
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, ConnectDialog.class);
update();
}
private void update(){
if(a)
startActivity(intent);
else{
//code
}
}
}
And this:
public class ConnectDialog extends Activity{
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect_dialog);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
The problem is: when I click on the button of the Intent, is it possible to execute the method update of the main activity again? Thank you very much
Just put the call to update into onResume() of the MainActivity. This way, it will be called at first startup and when the MainActivity is shown again later on:
#Override
protected void onResume(){
super.onResume;
update();
}
I would use the onActivityResult method.
Change your update method to
int YOUR_RESULT = 100;
private void update(){
if(a)
startActivityForResult(intent, YOUR_RESULT);
else{
//code
}
}
then in that same activity, use this method:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == YOUR_RESULT) {
update();
}
}
If you use this method, the update() method will only get called when coming back from that activity.
if u check the Android Life Cycle u will get the answer why the Update is not executing..
How ever to call the update method on click..
private void update(){
if(a)
startActivityForResult(intent, 0);
else{
//code
}
}
and use onActivityResult to call the update method again
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
super.onActivityResult(arg0, arg1, arg2);
update();
}

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.

Cant getting result from child activity

I have a Parent activity which is sending data to child activity but the child is not returning the result. I posted portion of code from both activity altogether below- Theres a few code that I didnt post for unnecessity.
public class TdeeActivity extends Activity {
public static final int CALLED_ACTIVITY = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tdee);
Button ok=(Button)findViewById(R.id.btnOk);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent bmr= new Intent(TdeeActivity.this,BMRActivity.class);
startActivityForResult(bmr,CALLED_ACTIVITY);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CALLED_ACTIVITY:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "THE RESULT-"+data.getExtras().getString("result"),
Toast.LENGTH_SHORT).show();
}
}
}
} // end class
public class BMRActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmr);
Button btnOk=(Button)findViewById(R.id.btnOk);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
public void showResult() {
Intent data= new Intent();
data.putExtra("result",result);
setResult(RESULT_OK, data);
finish();
}
}
}// end class
I tested you code in a dummy project and it was working fine at my end.. following is the code for both activity:
public class ParentActivity extends Activity {
private static final int CALLED_ACTIVITY = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent bmr = new Intent(ParentActivity.this, ChildActivity.class);
startActivityForResult(bmr, CALLED_ACTIVITY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case CALLED_ACTIVITY:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "THE RESULT-"+data.getExtras().getString("result"),
Toast.LENGTH_SHORT).show();
}
}
}
}
public class ChildActivity extends Activity {
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Returning result from child activity
Intent data = new Intent();
data.putExtra("result", "from child"
+ this.getCallingActivity().getClassName());
setResult(RESULT_OK, data);
finish();
}
}
So please post more code so that issue can be found..

Categories

Resources