Android 2.1 via eclipse
I have an activity that opens a dialog themed activity via checkbox onChecked function
Im creating this new dialog themed activity with an Intent.
Problem is, how do i dismiss the dialog themed activity once i finish with it? (the way it stands now, i have to send a new intent in order to go back to the previous activity via click of a button)
Any help would be greatly apprieciated!
Code snippet:
Main activity:
cbReminder.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
Intent intent = new Intent(getApplicationContext(), DateTimeDialog.class);
startActivity(intent);
}
}
});
Dialog themed activity:
public void onClick(View v) {
if (v.getId() == R.id.b_datetime_save)
{
}
else if (v.getId() == R.id.b_datetime_cancel)
{
finish();
Intent intent = new Intent(getApplicationContext(), MakeNoteActivity.class);
startActivity(intent);
}
}
As you specified, the intent was indeed not needed to return to the previous activity and should be removed.
To uncheck the checkbox after returning from the dialog, you can use startActivityForResult and set a callback for when you return.
Open your dialog like this:
Intent intent = new Intent( getApplicationContext(), DateTimeDialog.class );
startActivityForResult( intent, UNIQUE_IDENTIFIER );
Then add a callback to that same activity:
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data )
{
if ( requestCode == UNIQUE_IDENTIFIER )
{
cbReminder.setChecked( false );
}
}
The UNIQUE_IDENTIFIER can be any number that uniquely identifies this dialog. Let me know if you have any more questions.
Related
I am having an activity with custom list view. In my list view there are two types of items, with different layout. On items there is a switch and when I turn off the switch I go to Activity A, and when I turn on the switch I go to Activity B.
Here is my code:
Switch enable = (Switch) rowView.findViewById(R.id.enable);
enable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Intent intentChange = new Intent(getContext(), ActivityA.class);
intentChange.putExtra(PROPERTY, "test1");
((Activity)getContext()).startActivityForResult(intentChange, 100);
} else {
Intent newIntent=newIntent(getContext(),ActivityB.class);
((Activity)getContext()).startActivityForResult(newIntent, 200);
}
}
});
In each of these activities I call this:
Intent changedIntent=new Intent();
changedLimitIntent.putExtra("changed",changed);
changedLimitIntent.putExtra("changedDesc","desc);
setResult(Activity.RESULT_OK,changedIntent);
finish();
In my activity with custom adapter I have this code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == ActivityA.REQUEST_CODE) {
....
} else if (requestCode == ActivityB.REQUEST_CODE) {
.....
}
}
}
This work OK for me, however, when I receive the result from Activity A or Activity B on the activity with custom list view, and when I click back button is how I have this activity as many times I wait for result from other activities on back stack. I don't know what the problem is. I don't like to have my activity as many times I wait for result from other activities.
I hope I was clear with my question.
Try this to launch new activity. Hope it will help you.
Activity_A.this.finish();
Intent intentSettings = new Intent(Activity_A.this, Activity_B.class);
intentSettings.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intentSettings);
In my ArrayAdapter I have an AlertDialog with a button. Now I want to use ActivityForResult for that. In this simple code I can use an Intent to view the other Activity but I can not get passed data from it in ArrayAdapter.
public class AdapterReceiveSMS extends ArrayAdapter<ReceivedItemStructure> {
private myDialog dialog;
public AdapterReceiveSMS(ArrayList<ReceivedItemStructure> array) {
super(G.context, R.layout.rsms, array);
}
/* ----- Clicking on Forward Button ----- */
forward_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
G.activityDialogContext);
View vForward = G.inflater.inflate(R.layout.forward, null);
builder.setView(vForward);
final AlertDialog sms_dialog = builder.create();
sms_dialog.show();
from_file.setOnClickListener ( new View.OnClickListener () {
#Override
public void onClick (View v) {
Intent fileBrowser = new Intent(G.activity,ActivityFileBrwoser.class);
G.activity.startActivityForResult ( fileBrowser, 1 );
}
} );
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
}
}
onActivityResult in an overridden method of Activity class and called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it.”
you started the activity using this code
G.activity.startActivityForResult ( fileBrowser, 1 );
you must put your onActivityResult method in your calling activity ( I mean activity in which you are creating the object of AdapterReceiveSMS class. )
You can't add a callback method to a class and hope that the system calls it. onActivityResult belongs to your Activity which then can pass the information to your adapter.
I am confused and have no idea on how to use the startActivityResults and setResults to get data from previous activity. I have a view class and a activity class.
Basically in my view class i have this dialog and it will actually start the activity class called the colorActivity class. When user selects yes also it will pass the name of the selected circle to the colorActivity class. At the colorActivity class, users are allowed to enter color code for a particular circle and i would like to pass the color code back to the view class. I have problems passing values from activity back to view using the startActivityForResult and setResult method. Adding on, how to make use of the fetched data afterthat?
my code are as follows
Ontouchevent code from my view class:
#Override
public boolean onTouchEvent(MotionEvent event) {
x = event.getX();
y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
for (int i = 0; i < circles.size(); i++) {
if (circles.get(i).contains(x, y)) {
circleID = i;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new Builder(
getContext());
final EditText text = new EditText(getContext());
builder.setTitle("Adding colors to circles").setMessage(
"Proceed to Enter color");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di,
int i) {
Intent intent = new Intent(
getContext(),
colorActivity.class);
intent.putExtra("circlename", circleNameList.get(circleID));
startActivityForResults(intent, 1); // error incurred here : The method startActivityForResult(Intent, int) is undefined for the type new DialogInterface.OnClickListener(){}
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di,
int i) {
}
});
builder.create().show();
}
}, 3000);
break;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) { // Please, use a final int instead of hardcoded
// int value
if (resultCode == RESULT_OK) {
ccode = (String) data.getExtras().getString("colorcode");
}
}
}
public static String getColorCode() {
return ccode;
}
In the colorActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_ecolor);
circlenametextview = (TextView)findViewById(R.id.circlenametextview);
String circlename = super.getIntent().getStringExtra("circlename");
circlenametextview.setText(circlename);//get the circle name
savebutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(colorActivity.this, ?????);//how to return back to the view class?
colorcode = colorEditText.getText().toString();// I am able to get value right up till this point
Intent resultIntent = new Intent();
resultIntent.putExtra("colorcode", colorcode );
setResult(Activity.RESULT_OK, resultIntent);
finish();
}// onclick
});
}
After correcting the other code so that you can run the program, you can retrieve parameters back from your activity colorActivity in this way:
Step1: return some value from colorActivity
Intent resultIntent = new Intent();
resultIntent.putExtra("NAME OF THE PARAMETER", valueOfParameter);
...
setResult(Activity.RESULT_OK, resultIntent);
finish();
Step 2: collect data from the Main Activity
Overriding #onActivityResult(...).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) { // Please, use a final int instead of hardcoded int value
if (resultCode == RESULT_OK) {
String value = (String) data.getExtras().getString("NAME OF THE PARAMETER");
References
http://developer.android.com/training/basics/intents/result.html
How to manage `startActivityForResult` on Android?
http://steveliles.github.io/returning_a_result_from_an_android_activity.html
STARTACTIVITYFORRESULT IS NOW DEPRECATED
Alternative to it and recommended solution is to use Activity Result API
You can use this code, written in Kotlin language:
Create ResultLauncher:
private var resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
if (null != data && data.getBooleanExtra("REFRESH_PAGE", false)) {
//do your code here
}
}
}
start Activity by using above result launcher:
val intent = Intent(this, XYZActivity::class.java)
resultLauncher.launch(intent)
Return result from XYZActivity by
val resultIntent = Intent()
resultIntent.putExtra("REFRESH_PAGE", true)
setResult(Activity.RESULT_OK, resultIntent)
finish()
try using
ActivityName.this.startActivityForResult(intent,int)
Oh, and 1 small thing, in your code you have used
startActivityForResults(intent,int) ..replace that with
startActivityForResult(intent,int)
So, I am currently trying to edit the Snake game that android's api provides. I am trying to make it so that after pressing menu->settings->resume, it would resume the game. However, instead of going all the way to resume, after I press settings, it quits and resumes from there. I am using Intents to resume the program.
public boolean onOptionsSelected(MenuItem menu){
switch(menu.getItemId()){
case R.id.settings:
Intent prefActivity = new Intent(this,MyPreferences.class);
startActivityForResult(prefActivity, KEY_RESUME_RESULT);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch(requestCode){
case KEY_RESUME_RESULT:
if(resultCode==RESULT_OK){
if(mSnakeView.getMode() == SnakeView.PAUSE)
this.mSnakeView.setMode(SnakeView.RUNNING);
}
}
}
This is in MyPreferences.class
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.snake_preferences);
resume = (Preference)findPreference(getString(R.string.key_resume));
onPreferenceTreeClick(this.getPreferenceScreen(),resume);
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferencescreen,Preference preference){
super.onPreferenceTreeClick(preferencescreen,preference);
Intent intent = new Intent();
if(preference == resume){
setResult(Activity.RESULT_OK,intent);
finish();
}
return true;
}
You're explicity calling the method that resumes the game inside onCreate(), which is probably why the game is resuming as soon as you launch settings. I'd suggest not using the method and instead setting up a click listener for your preference:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.snake_preferences);
resume = (Preference)findPreference(getString(R.string.key_resume));
resume.setOnPreferenceClickListener (new Preference.OnPreferenceClickListener()
{
#Override
public void onPreferenceClick(Preference preference)
{
setResult(Activity.RESULT_OK,intent);
finish();
}
});
}
Also, based on your code onOptionsSelected() doesn't explicitly pause the game (however the UI should be paused considering that onPause() will be called), you might want to look into that.
I have a onClick listener which starts an activity using intent, but how to make the listener to fire the Activity intent only when the user click five times or more?
public boolean onClick(View v) {
Intent myIntent = new Intent(activity, loginActivity.class);
activity.startActivity(myIntent);
return false;
}
Here I am going to login Activity. How can I get back to previous activity after login successful?
public void onClick(View v) {
String username = Username.getText().toString();
String password = Password.getText().toString();
if(username.equals("guest") && password.equals("guest")) {
lResult.setText("Login successful.");
} else {
lResult.setText("Login failed");
}
}
Have a static variable in program which will increment on each click.
When you click count reach 5 then trigger code to start LoginActivity.
static int i = 0;
#override
public void onClick(View view) {
i++;
if (i == 5) {
i = 0;
Intent myIntent = new Intent(activity, loginActivity.class);
activity.startActivity(myIntent);
}
}
You can try to build a counter which count the clicks and from the 5th clicks let him go forward
To turn back to the previous activity just call
finish();
Add a static counter to your activity.
static int clickCount;
In your onClick:
if(clickCount++<5){return;}
For the fist question just a a counter variable on the class and increment in on onClick() and check it its >= 5 before starting the intent.
int clickCounter;
public boolean onClick(View v) {
clickCounter++;
if (clickCounter >= 5) {
Intent myIntent = new Intent(activity, loginActivity.class);
activity.startActivity(myIntent);
}
return false;
}
For the second question you must take into account whether previous Activity must keep exactly the same aspect or update with user data. Take a look at Activity.startActivityForResult (Intent intent, int requestCode) for calling an activity and get a result value from it.
-