I have Activity 'A', Activity 'B', Activity 'C', Activity 'D', Activity 'E', Activity 'E' . I want to exit the Activity click on onBackPressed(). When i run the app it goes to Activity 'A' it does not exit the app. How can i implement with this.
Here is my Code
public class MainActivity extends Activity {
TableLayout table_layout;
EditText firstname_et, lastname_et;
Button addmem_btn;
DatabaseHelper databaseHelper = new DatabaseHelper(this);
protected SQLiteDatabase db;
ProgressDialog PD;
ImageView imgButtonBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.performance_report);
table_layout = (TableLayout) findViewById(R.id.tableLayout_PerformanceReport);
//ImageView imgButtonBack;
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);
imgButtonBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Employee_List.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//finish();
}
});
}
}
#Override
public void onBackPressed()
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(MainActivity.this);
alertbox.setTitle("Do you wish to exit ?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// finish used for destroyed activity
finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Nothing will be happened when clicked on no button
// of Dialog
}
});
alertbox.show();
}
}
Thanks to Appreciate.
You can try this in onBackPressed:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Which exits the application. And works fine for me. Hope it helps.
call this.finish() while you open your new activity(i.e going from activty A to some other activity). In your case write this
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Employee_List.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
MainActivity.this.finish();
}
});
You can do something like this -
private exit = false;
public void onBackPressed() {
if (exit)
Home.this.finish();
else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
Related
I have created a new layout name dialog_exit for onBackPressed but when I install and open, my application can not open and showing error close app
Please review my whole code and guide me how can I solve this problem
Here is my main activity code
public class MainActivity extends AppCompatActivity {
public Dialog mDialog;
public Button mDialogyes, mDialogno;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDialog();
}
private void createDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_exit);
mDialog.setCanceledOnTouchOutside(true);
mDialog.setCancelable(true);
mDialogyes = (Button) findViewById(R.id.yes);
mDialogno = (Button) findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
});
}
#Override
public void onBackPressed() {
mDialog.show();
}
}
Here is my layout code as screenshot because
stackoverflow not allow me to add more code that why sharing image
Updated code of createDialog function
private void createDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mDialog.setContentView(R.layout.dialog_exit);
mDialog.setCanceledOnTouchOutside(true);
mDialog.setCancelable(true);
mDialogyes = (Button) mDialog.findViewById(R.id.yes);
mDialogno = (Button) mDialog.findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
try this code
mDialogyes = (Button)mDialogyes. findViewById(R.id.yes);
mDialogno = (Button)mDialogyes. findViewById(R.id.no);
mDialogyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
mDialogno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
You have to do like this
mDialogyes = (Button) mDialog.findViewById(R.id.yes);
mDialogno = (Button) mDialog.findViewById(R.id.no);
I want to pass an XML resource from one activity to another activity using Java Code? I don't want to create separate different activities for different buttons.
ImageButton imageBttn = (ImageButton)findViewById(R.id.imageButton1);
imageBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, info.class));
}
});
Pseudocode to explain what I'm trying to do:
If BUTTON_1 is clicked
-Pass swirl.png to info.class
If BUTTON_2 is clicked
-Pass golden.png to info.class
If BUTTON_3 is clicked
-Pass arcade.png
imageBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, info.class)
intent.putExtra("image",R.drawable.ic_search_grey);
startActivity(intent);
}
});
On Mainactvitiy get the int drawable
int res = getIntent().getIntExtra("image", -1);
if(res > -1) {
Drawable drawable = getResources().getDrawable(res, null);
imgBtn.setImageDrawable(drawable);
}
InfoActivity.java
public class InfoActivity extends Activity {
private static final String EXTRA_IMAGE = "image";
public static void launch(Activity activity, #DrawableRes int imageResId) {
Intent intent = new Intent(activity, InfoActivity.class);
intent.putExtra(EXTRA_IMAGE, imageResId);
activity.startActivity(intent);
}
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
int imageResId = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (imageResId == -1) {
throw new IllegalArgumentException(EXTRA_IMAGE);
// or set error/default image resource id
}
// ... something to do with imageResId
}
}
MainActivity.java
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.swirl);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.golden);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.arcade);
}
});
}
I have an activity that is suppose to finish itself and close the application. Now, in certain cases, which are varying on how the user is navigating to the activity, the activity is getting stacked. When the activity is stacking up, then calling finish() or android.os.Process.killProcess(android.os.Process.myPid()); or both together is only showing up the same activity again.
The Manifest:
<activity
android:name="newActivities.HomeActivity"
android:label="#string/title_activity_home"
android:screenOrientation="portrait">
</activity>
The activity:
public class HomeActivity extends Activity {
private EditText studentNameEdittext;
private Button startYourStoryButton, loginButton, navCollegesButton, settingsButton, search_friends_button, browseStoriesButton;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// saveInPreference("loginStatus", "");
// }
// Set up the action bar
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#009945")));
bar.setTitle("Study Story");
bar.setIcon(R.drawable.statusbar_icon);
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.white_colour));
yourTextView.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// studentNameEdittext = (EditText)
// findViewById(R.id.studentNameEdittext);
startYourStoryButton = (Button) findViewById(R.id.startYourStoryButton);
// loginButton = (Button) findViewById(R.id.loginButton);
navCollegesButton = (Button) findViewById(R.id.navCollegesButton);
// settingsButton = (Button) findViewById(R.id.settingsButton);
// search_friends_button = (Button)
// findViewById(R.id.search_friends_button);
browseStoriesButton = (Button) findViewById(R.id.browseStoriesButton);
// textView1 = (TextView) findViewById(R.id.textView1);
// Set up font type
// studentNameEdittext.setTypeface(TypeFaceController.generalTextFace(HomeActivity.this));
startYourStoryButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// loginButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
navCollegesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// settingsButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// search_friends_button.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
browseStoriesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// textView1.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
startYourStoryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(HomeActivity.this, SignUp.class);
i.putExtra("signUpCaller", "Home");
startActivity(i);
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View arg0){
// Intent i = new Intent(HomeActivity.this, Login.class);
// startActivity(i);
// }
// });
// search_friends_button.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this,
// FindStudentBrowseStoryActivity.class);
// i.putExtra("Button", "search_friends_button");
// i.putExtra("searchString", studentNameEdittext.getText().toString());
// startActivity(i);
//
// }
// });
browseStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, FindStudentBrowseStoryActivity.class);
i.putExtra("Button", "browseStoriesButton");
startActivity(i);
}
});
navCollegesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, CollegeListActivity.class);
startActivity(i);
}
});
// settingsButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this, HomeSettingsActivity.class);
// i.putExtra("FromActivity", "HomeSettingsActivity");
// startActivity(i);
// finish();
//
// }
// });
}
// #Override
// protected void onStart(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onStart();
// }
//
// #Override
// protected void onResume(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onResume();
// }
// =========Login button action bar
#Override
public boolean onCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_menu, menu);
return true;
}
// =========Login button action bar
#Override
public boolean onOptionsItemSelected(MenuItem item){
// handle item selection
switch (item.getItemId()) {
case R.id.home_login_string:
Intent i = new Intent(HomeActivity.this, Login.class);
// finish();
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// logic to fix logout
#Override
public void onBackPressed(){
// Intent startMain = new Intent(Intent.ACTION_MAIN);
// startMain.addCategory(Intent.CATEGORY_HOME);
// startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);;
// startActivity(startMain);
//
// int pid = android.os.Process.myPid(); //
// android.os.Process.killProcess(pid); // return; }
android.os.Process.killProcess(android.os.Process.myPid());
finish();
}
// method to save variable in preference
public void saveInPreference(String name, String content){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(name, content);
editor.commit();
}
// getting content from preferences
public String getFromPreference(String variable_name){
String preference_return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preference_return = preferences.getString(variable_name, "");
return preference_return;
}
}
Please tell me where am I going wrong? Why is the activity stacking?
P.S: We cannot use single top etc as it causes some transition issues with the existing custom theme!
Take one application class which extends Application and take one arrayList and maintain the references of the activities in the arraylist.
When you click on back button in desired activity then finish the all the activities using arraylist.
Take one base activity. Which is super class of all the activities
public class BaseActviity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App application = (App) getApplication();
application.addActivity(this);
}
}
Take one application class
public class App extends Application {
public App() {
if (listActivty == null) {
listActivty = new ArrayList<BaseActviity>();
}
}
public ArrayList<BaseActviity> listActivty;
public void addActivity(BaseActviity actviity) {
if (!listActivty.contains(actviity)) {
listActivty.add(actviity);
}
}
}
take 4 samples activity classes like ......
1) public class FirstActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
2) public class SecondActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
}
3).........................
4) ............................
in 4 th activity class placed the following code
In desire activity that means final activity,override the onBackPressed
public void onBackPressed() {
super.onBackPressed();
App application = (App) getApplication();
ArrayList<BaseActviity> listActivty = application.listActivty;
for (BaseActviity actviity : listActivty) {
actviity.finish();
}
}
Wherever you are opening the activity which is getting stacked up, use this:
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Check if the Activity, that would be last activity when user clicks on the back button,is visible or not and if visible use
System.exit(0);
At last, the problem is solved. I has to do a little trick:
ParseUser.getCurrentUser();
ParseUser.logOut();
Intent i = new Intent(getActivity(), NewHomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().startActivity(i);
getActivity().finish();
This did not cause any transition issues as well.
I have a custom dialog which when the user exits out of it, the main activity is to be refreshed by using start activity. So far this is not the case as the dialog closes without either of the listeners executing. This occurs when pressing the back button as well as pressing off the dialog on the screen.
public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {
public Activity mActivity;
public CustomDialogClass(Activity activity) {
super(activity);
this.mActivity = activity;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
setCanceledOnTouchOutside(true);
new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
Log.e("check", "STARTED_dismiss");
Intent i = new Intent(mActivity, MainActivity.class);
mActivity.startActivity(i);
}
};
new OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
Log.e("check", "STARTED_Cancel");
Intent i = new Intent(mActivity, MainActivity.class);
mActivity.startActivity(i);
}
};
}
You have to set the listeners, in order to do that just call the setOnDismissListener and setOnCancelListener methods in the onCreate method. Like this:
setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// your code here
}
});
setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// your code here
}
});
You create anonymous listener. You need to handle youre listener.
do something like this:
OnDismissListener onDismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
Log.e("check", "STARTED_dismiss");
Intent i = new Intent(mActivity, MainActivity.class);
mActivity.startActivity(i);
}
};
OnCancelListener onCancelListener = new OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
Log.e("check", "STARTED_Cancel");
Intent i = new Intent(mActivity, MainActivity.class);
mActivity.startActivity(i);
}
};
and then add listeners to your object:
myObject.setOnDismissListener(onDismissListener);
myObject.setOnCancelListener(onCancelListener);
I created two dialogs, the first one opens the second dialog that would access the listview and it did, the second dialog selects specific item in the listView and transfers that item to the textview in the first dialog... I messed up my logic, how can I do this?
here's the first dialog:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_students_dialog);
imb1=(ImageButton)findViewById(R.id.im1);
imb2=(ImageButton)findViewById(R.id.im2);
imb3=(ImageButton)findViewById(R.id.im3);
text1=(TextView)findViewById(R.id.Text1);
text2=(TextView)findViewById(R.id.Text2);
text3=(TextView)findViewById(R.id.Text3);
/* Get values from Intent */
Intent intent = getIntent();
String name = intent.getStringExtra("Title1");
text1.setText(name);
ie1=(EditText)findViewById(R.id.edit1);
ib=(Button)findViewById(R.id.dialog_button_cancel);
ib1=(Button)findViewById(R.id.dialog_button_ok);
ib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(InsertStudent.this, StudentsActivity.class);
startActivity(intent);
}
});
ib1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String data1 = ie1.getText().toString();
String data2 = ie2.getText().toString();
mySQLiteAdapter.insertSchool(data1, data2);
updateList();
Intent myIntent = new Intent(InsertStudent.this, StudentsActivity.class);
startActivity(myIntent);
}
});
imb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(InsertStudent.this, Add1.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(myIntent);
}
});
imb2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(InsertStudent.this, Add2.class);
startActivity(myIntent);
}
});
imb3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(InsertStudent.this, Add3.class);
startActivity(myIntent);
}
});
}
private void updateList(){
cursor.requery();
}
}
here's the second dialog:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_add_class_students);
listContent = (ListView)findViewById(R.id.listView1);
mySQLiteAdapter = new Database(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueSchoolAll();
button1 = (Button) findViewById(R.id.Button01);
button2 = (Button) findViewById(R.id.dialog_button_ok);
// Capture button clicks
button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(Add1.this, InsertSubject.class);
startActivity(myIntent);
}
});
cursor.requery();
String[] from = new String[]{Database.KEY_ID2, Database.KSCHOOL, Database.KSCHOOLCODE};
int[] to = new int[]{R.id.rid, R.id.rt1, R.id.rt2};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row_school, cursor, from, to);
listContent.setAdapter(cursorAdapter);
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2);
final int item_id = cursor.getInt(cursor.getColumnIndex(Database.KEY_ID2));
sdid.sdid(item_id);
Intent intent=new Intent(Add1.this,DetailsSchool.class);
startActivity(intent);
}
});
cursor.requery();
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Cursor cursor = (Cursor) arg0.getItemAtPosition(arg2);
final int item_id = cursor.getInt(cursor.getColumnIndex(Database.KSCHOOLCODE));
Intent intent = new Intent(getApplicationContext(),InsertStudent.class);
intent.putExtra("Title1", item_id);
startActivity(intent);
}
});
cursor.requery();
}
private void updateList(){
cursor.requery();
}
}
you've called setOnItemClickListener twice for the same listview in your second dialog