Exit app when back pressed - android

sorry for this again button i ant figure out the correct placement here. i just want it on this class only to exit the app when back pressed but i cant figure out what exactly to write or where to write it. thanks for the help. code of class below.
package com.example.whattodo2;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class Title extends Activity {
Button reset, rts;
ImageView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title);
reset = (Button) findViewById(R.id.reset);
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
double rand = Math.random();
if(rand < 0.5){
Intent reset1 = new Intent(Title.this, MainActivity.class);
startActivity(reset1);
} else {
Intent reset2 = new Intent(Title.this, Question36.class);
startActivity(reset2);
}
}
});
rts = (Button) findViewById(R.id.rts);
rts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent rts=new Intent(Title.this,Rts.class);
startActivity(rts);
}
});
final Animation a = AnimationUtils.loadAnimation(this, R.animator.animation);
a.reset();
final ImageView rImage = (ImageView) findViewById(R.id.title);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.root);
layout.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
rImage.startAnimation(a);
func(); //A call to the function.
}
});
}
protected void func() {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.title, menu);
return true;
}
}

Use like this:
public class Title extends Activity {
#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);
super.onBackPressed();
}
}
hope this will give you some solution.

Before onCreate in all the activities:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Intent intent=new Intent (Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// finish();
}
return true;
}

Related

Android : Choose Intent to open from Button

I'm working on android project. In my activity i have four buttons. The user has to select the particular button to receive the notifications. So the next time if i select Notifications(its a fragment of nav drawer) it should directly lead me to that particular activity instead of again selecting the department.
1st Run
Nav Drawer (select Notification)>>Opens Activity(to choose button to receive notification) >> Opens that particular activity
2nd Run
Nav Drawer(select Notification)>> Directly opens the selected activity
Notification.class
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.NotificationCompat;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mateoj.multiactivitydrawer.department.dept_1styeartab;
import com.pushbots.push.Pushbots;
public class notifications extends BaseActivity {
private WebView webView;
Button clickButton;
Button clickButton1;
Button clickButton2;
Button clickButton3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Pushbots.sharedInstance().init(this);
Pushbots.sharedInstance().setCustomHandler(customHandler.class);
setContentView(R.layout.activity_notifications);
SharedPreferences preferences = getSharedPreferences("com.mateoj.multiactivitydrawer", MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
clickButton = (Button) findViewById(R.id.ncs);
clickButton1 = (Button) findViewById(R.id.nmech);
clickButton2 = (Button) findViewById(R.id.nece);
clickButton3 = (Button) findViewById(R.id.neee);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_cse.class);
Pushbots.sharedInstance().tag("cse");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
editor.putString("session", "cse").commit();
editor.commit();
startActivity(show);
}
});
clickButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_mech.class);
Pushbots.sharedInstance().tag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "mech").commit();
editor.commit();
startActivity(show);
}
});
clickButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_ece.class);
Pushbots.sharedInstance().tag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "ec").commit();
editor.commit();
startActivity(show);
}
});
clickButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_eee.class);
Pushbots.sharedInstance().tag("eee");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "eee").commit();
editor.commit();
startActivity(show);
}
});
onStartUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
onStartUp();
}
#Override
protected void onPause() {
super.onPause();
onStartUp();
}
#Override
protected void onStop() {
super.onStop();
onStartUp();
}
private void onStartUp()
{
SharedPreferences sharedPreferences = getSharedPreferences("com.mateoj.multiactivitydrawer", Context.MODE_PRIVATE);
String str = sharedPreferences.getString("session", "");
if (str.equals("cs")) {
clickButton.setClickable(true);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("mech")) {
clickButton.setClickable(false);
clickButton1.setClickable(true);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("ec")) {
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(true);
clickButton3.setClickable(false);
} else if (str.equals("eee"))
{
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(true);
}
}
/* private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
} */
#Override
protected boolean useDrawerToggle() {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_credits)
return true;
if (item.getItemId() == android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}
}
The onStartup code saves the preferences

I can't make a button appear (possibly issue with static referencing)

I want to make a button appear in the MenuActivity layout but the deciding if statement is in the CapitalReceiver class. I've tried adding 'static' to various variables but it didn't work. Please help!
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class MenuActivity extends Activity {
String status;
Boolean verified = false;
String textColour = "#000000";
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
String country = "7ec47294ff3d8b74";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_layout);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Button IDButton = (Button) findViewById(R.id.getIt);
Button RefreshButton = (Button) findViewById(R.id.refresh);
long updateTimeMillis = System.currentTimeMillis();
String updateTime = (String) DateFormat.format("hh:mm", updateTimeMillis);
//If application has been submitted//
if(preferences.contains("first_middle_store") & !(verified)) {
status = "Status: Application pending. Last updated: " + updateTime;
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.VISIBLE);
textColour = "#000000";
}
//If application has not been submitted
else {
status = "Status: Application not yet submitted";
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.GONE);
textColour = "#000000";
}
TextView text=(TextView)findViewById(R.id.application_status);
text.setTextColor(Color.parseColor(textColour));
text.setText(status);
Button btnNextScreen = (Button) findViewById(R.id.verify);
//Listening to verify event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), VerifyActivity.class);
startActivity(nextScreen);
}
});
Button btnNextScreen2 = (Button) findViewById(R.id.how);
//Listening to HowItWorks event
btnNextScreen2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen2 = new Intent(getApplicationContext(), HowItWorksActivity.class);
startActivity(nextScreen2);
}
});
//Listening to IDbutton event
IDButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen3 = new Intent(getApplicationContext(), IDActivity.class);
startActivity(nextScreen3);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_layout, container, false);
return rootView;
}
}
public void refresh(View view) {
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
mTvCapital.setText("hello");
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);
mServiceIntent.putExtra(Constants.EXTRA_ANDROID_ID, country);
// Starting the CapitalService to fetch the capital of the country
startService(mServiceIntent);
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent filter
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);
}
// Defining a BroadcastReceiver
private static class CapitalReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_APPROVAL);
if(capital == "YES") {
//status = "Status: Application Approved";//
//IDButton.setVisibility(View.VISIBLE);//
}
else if(capital == "NO"){
//status = "Status: Application Denied";//
}
}
}
}
Just glancing over your code, a possible solution (and perhaps not the best) would be to make the ID Button variable global. You would then instantiate it in the onCreate whilst still allowing it to be manipulated in other classes in this MenuActivity.
I hope this helps.

How to start an activity in Android?

I am very new to android programming. I want to use a code that takes me to MainActivity from my current activity on a click of a Button.
Here is my current code:
package com.example.flashlightapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Whitelight extends Activity implements OnClickListener {
Button b1 = (Button) findViewById(R.id.b3);
Intent i = new Intent(this, MainActivity.class);
{
this.startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
What should I put in
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
At first you must check if you declared all your activities in the manifest.xml file.
and in your Java code try this:
package com.example.flashlightapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Whitelight extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
Button b1 = (Button) findViewById(R.id.b3);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Whitelight.this, MainActivity.class);
this.startActivity(i);
}
});
}
}
This tutorial explains how to use intents and listeners : http://goo.gl/phLWkx
Try this..
public class Whitelight extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
Button b1 = (Button) findViewById(R.id.b3); // Initialization of Button
b1.setOnClickListener(this); // Initialization of ClickListener to the Button
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
Follow the links
http://developer.android.com/index.html
http://developer.android.com/training/index.html
http://www.mkyong.com/tutorials/android-tutorial/
Use following :
Button b1;
public class Whitelight extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
b1 = (Button) findViewById(R.id.b3); // Initialization of Button
b1.setOnClickListener(this); // Initialization of ClickListener to the Button
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==b1){
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
}
in onClick(...) :
you can choose if your button is press then perform specific activity, in your case if you press b1 button then perform button specific activity :
so we can check view v==b1 button. if you want to more button then
if(v==b1){
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
else if(v==b2)
{
// perform another action ;
}

App crashes when Launching "Unfortunately, has stopped"

I have a program and when I try to start it, it crashes. I really don't understand why, even Eclipse show's that there are no errors.
I can show you the code of a page on which I think is the problem.
package ctect.android.maxipro;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class BasicScreenActivity extends Activity {
private Button butonul1;
private Button butonul2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic_screen);
butonul1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View currentView) {
// TODO Auto-generated method stub
butonul2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View currentView) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(currentView.getContext(), NeedForSpeedActivity.class);
startActivityForResult(myIntent, 0);
Intent myIntent2 = new Intent(currentView.getContext(), Fifa2012Activity.class);
startActivityForResult(myIntent2, 0);
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.basic_screen, menu);
return true;
}
}
if somebody understands, please help me.
You forgot to assign an object to butonul1 before using it. You need to add this line before butonul1.setOnClickListener:
butonul1= (Button) findViewById(R.id.butonul1);
This is assuming that you gave it the id butonul1 in your layout file.

Text To Speech error

Can any let me know what I am doing wrong. Trying to get Text To Speech to work onClick for a Text View.
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener
{
private TextToSpeech tts;
private static final int MY_DATA_CHECK_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_24);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
((Button)findViewById(R.id.btnClear)) .setOnClickListener(clearbutton);
}
public void onClick(View v)
{
TextView textSpeak = (TextView) findViewById(R.id.mainText);
tts.speak(textSpeak.getText(), TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit( int i)
{
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == MY_DATA_CHECK_CODE)
{
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
tts = new TextToSpeech(this, this);
}
else
{
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onDestory()
{
if (tts != null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
OnClickListener clearbutton = new OnClickListener()
{
public void onClick(View v)
{
TextView mainText = (TextView)findViewById(R.id.mainText);
mainText.setText("");
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.select8icons: setContentView(R.layout.layout_8);
break;
case R.id.select24icons: setContentView(R.layout.layout_24);
break;
case R.id.select63icons: setContentView(R.layout.layout_63);
break;
}
return true;
}
}
If anyone can help or has a better way to run the code, I love to hear your ideals. I try to research but every way I try gave me a error or something. Thanks in advance.
Your button will not work until TextToSpeech calls onInit. So you should disable btnSpeak until then.
Your TTS stuff looks fine. However, I dont see where you are binding any button to your onClick method and neither does your Activity seem to implement the onClickListener interface. You would need to do one or the other to get that onClick method to run.
So basically, I dont see any way your onClick method will ever get called.
Assuming you have some view/button in your layout the user is supposed to click to hear the tts, I think you want something like:
Button btnSpeak = (Button)findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView textSpeak = (TextView) findViewById(R.id.mainText);
tts.speak(textSpeak.getText(), TextToSpeech.QUEUE_FLUSH, null);
}
});

Categories

Resources