i need to close and activity and start another only when the user presses back twice. I am using this code
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
Log.e("Entering","Yes");
DatabaseHandler db=new DatabaseHandler(AddBreakfastActivity.this);
db.deleteTodaysUnsavedMenu(Integer.parseInt(newDay),Integer.parseInt(newIntMonth));
Intent intent=new Intent(AddBreakfastActivity.this,ProvidersUpdateActivity.class);
startActivity(intent);
finish();
}
else {
this.doubleBackToExitPressedOnce = true;
Log.e("BOOLEANVALUE", String.valueOf(doubleBackToExitPressedOnce));
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
On pressing back once the app exits and shows the Toast message.
It doesnt wait for the second press. How can i resolve this?
Thank you.
EDIT
Found it to be working as expected when the back button is pressed. However shows aforesaid issue when called from
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home){
onBackPressed();
}
}
you can also do this with on keydown event as code below remove backpressed
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==KeyEvent.ACTION_DOWN && keyCode==KeyEvent.KEYCODE_BACK)
{
if (doubleBackToExitPressedOnce) {
Log.e("Entering","Yes");
DatabaseHandler db=new DatabaseHandler(AddBreakfastActivity.this);
db.deleteTodaysUnsavedMenu(Integer.parseInt(newDay),Integer.parseInt(newIntMonth));
Intent intent=new Intent(AddBreakfastActivity.this,ProvidersUpdateActivity.class);
startActivity(intent);
finish();
}
else {
this.doubleBackToExitPressedOnce = true;
Log.e("BOOLEANVALUE", String.valueOf(doubleBackToExitPressedOnce));
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
return false;
}
}
return super.onKeyDown(keyCode, event);
}
Here's an example of "Press Twice to Exit" with fragments:
boolean doublePressToQuit = false;
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
if (doublePressToQuit) {
DashBoardActivity.this.finish();
} else {
this.doublePressToQuit = true;
Toast.makeText(this, getString(R.string.quit_notification), Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doublePressToQuit = false;
}
}, 2000);
}
}
}
Include super.onBackPressed(); inside your IF statement to override the onBackPressed() event.
Try the below code, it works for me
boolean firstBackPressed = false;
.
.
.
#Override
public void onBackPressed() {
if (!firstBackPressed) {
firstBackPressed = true;
Toast.makeText(MainMenu.this, "Press back again to exit", Toast.LENGTH_SHORT).show();
} else {
super.onBackPressed();
}
}
Please find this
private boolean isShownExit;
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
drawerLayout.closeDrawer(Gravity.LEFT);
isShownExit = false;
return;
} else {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
if (!isShownExit) {
isShownExit = true;
showToast(this, "Press again to exit");
} else {
hideSoftKeyboardDialogDismiss(this);
startAnotherActivityHereWhichDoYouwant();
}
} else {
getSupportFragmentManager().popBackStack();
}
}
}
Related
I am not too good at android applications so most of the code are from the Youtube videos I watched while trying to learn how to code android application. I made some adjustment to what I want.
Here I am stuck trying to create a library management system. Every thing seems to be
working, except for the fact that I can't create a new user or sign in.
Code is running fine, but still do not understand the errors. From my Sign Activity there seems to be a misplacement of code, which I don't understand.
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout editName;
private TextInputLayout editEnrollNo;
private TextInputLayout editCardNo;
private TextInputLayout editPass1;
private TextInputLayout editID;
private TextInputLayout editPass;
private Button buttonRegister;
private TextView toSignIn;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private CheckBox check1;
private FirebaseFirestore db;
private Spinner userType;
private String type;
private int type1;
private int temp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editID = (TextInputLayout) findViewById(R.id.editID);
editPass = (TextInputLayout) findViewById(R.id.editPass);
editPass1=(TextInputLayout)findViewById(R.id.editPass1);
editName=(TextInputLayout)findViewById(R.id.editName);
editEnrollNo=(TextInputLayout)findViewById(R.id.editEnrollNo);
editCardNo=(TextInputLayout)findViewById(R.id.editCardNo);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
toSignIn = (TextView) findViewById(R.id.toSignIn);
progressDialog=new ProgressDialog(this);
progressDialog.setCancelable(false);
check1=(CheckBox)findViewById(R.id.check1);
userType=(Spinner)findViewById(R.id.userType);
List<String> list = new ArrayList<>();
list.add("Select Account Type");
list.add("User");
list.add("Admin");
ArrayAdapter adapter =new ArrayAdapter(this,android.R.layout.simple_spinner_dropdown_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
userType.setAdapter(adapter);
userType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).toString().equals("Select Account Type"))
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(false);
editPass.setEnabled(false);
editName.setEnabled(false);
editID.setEnabled(false);
editEnrollNo.setEnabled(false);
editCardNo.setEnabled(false);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
else if(parent.getItemAtPosition(position).toString().equals("User"))
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(true);
editPass.setEnabled(true);
editName.setEnabled(true);
editID.setEnabled(true);
editEnrollNo.setEnabled(true);
editCardNo.setEnabled(true);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
else
{
type=parent.getItemAtPosition(position).toString();
editPass1.setEnabled(true);
editPass.setEnabled(true);
editName.setEnabled(true);
editID.setEnabled(true);
editEnrollNo.setEnabled(false);
editCardNo.setEnabled(false);
editCardNo.setErrorEnabled(false);
editEnrollNo.setErrorEnabled(false);
editID.setErrorEnabled(false);
editName.setErrorEnabled(false);
editPass.setErrorEnabled(false);
editPass1.setErrorEnabled(false);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
FirebaseApp.initializeApp(this);
firebaseAuth=FirebaseAuth.getInstance();
db=FirebaseFirestore.getInstance();
buttonRegister.setOnClickListener(this);
toSignIn.setOnClickListener(this);
check1.setOnClickListener(this);
}
private boolean verifyName()
{
String name=editName.getEditText().getText().toString().trim();
if(name.isEmpty())
{ editName.setErrorEnabled(true);
editName.setError("Name Required");
return true;
}
else
{
editName.setErrorEnabled(false);
return false;
}
}
private boolean verifyCardNo()
{
String cardNo=editCardNo.getEditText().getText().toString().trim();
if(cardNo.isEmpty())
{ editCardNo.setErrorEnabled(true);
editCardNo.setError("Card No. Required");
return true;
}
else
{
editCardNo.setErrorEnabled(false);
return false;
}
}
private boolean verifyEnrollNo()
{
String enrollNo=editEnrollNo.getEditText().getText().toString().trim();
if(enrollNo.isEmpty())
{ editEnrollNo.setErrorEnabled(true);
editEnrollNo.setError("Enrollment No. Required");
return true;
}
else
{
editEnrollNo.setErrorEnabled(false);
return false;
}
}
private boolean verifyEmailId()
{
String emailId=editID.getEditText().getText().toString().trim();
if(emailId.isEmpty())
{ editID.setErrorEnabled(true);
editID.setError(" Email ID Required");
return true;
}
else if(!emailId.endsWith("#iiitnr.edu.in"))
{
editID.setErrorEnabled(true);
editID.setError(" Enter Valid Email ID");
return true;
}
else
{
editID.setErrorEnabled(false);
return false;
}
}
private boolean verifyPass()
{
String pass=editPass.getEditText().getText().toString().trim();
if(pass.isEmpty())
{ editPass.setErrorEnabled(true);
editPass.setError(" Password Required");
return true;
}
else
{
editPass.setErrorEnabled(false);
return false;
}
}
private boolean verifyPass1()
{
String pass1=editPass1.getEditText().getText().toString().trim();
String pass=editPass.getEditText().getText().toString().trim();
if(pass1.isEmpty())
{ editPass1.setErrorEnabled(true);
editPass1.setError("Confirm Password Required");
return true;
}
else if(pass.equals(pass1))
{
editPass1.setErrorEnabled(false);
return false;
}
else
{
editPass1.setErrorEnabled(true);
editPass1.setError("Passwords do not match");
return true;
}
}
private boolean verifyType()
{
if (type.equals("Select Account Type"))
{
Toast.makeText(this, "Please select account type !", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
private boolean verifyCard1()
{
db.collection("User").whereEqualTo("card",Integer.parseInt(editCardNo.getEditText().getText().toString().trim())).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
temp=task.getResult().size();
}
}
});
if(temp==0)
return false;
else
return true;
}
private void registerUser()
{
if(verifyType())
return;
if(type.equals("User"))
{
boolean res= (verifyName()|verifyCardNo()|verifyEmailId()|verifyEnrollNo()|verifyPass()|verifyPass1());
if(res==true)
return;
}
if(type.equals("Admin"))
{
boolean res= (verifyName()|verifyEmailId()|verifyPass()|verifyPass1());
if(res==true)
return;
}
String id=editID.getEditText().getText().toString().trim();
String pass=editPass.getEditText().getText().toString().trim();
if(type.equals("User")){
type1=0;
}
else
type1=1;
progressDialog.setMessage("Registering User ... ");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(id,pass).addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
String id=editID.getEditText().getText().toString().trim();
String name=editName.getEditText().getText().toString().trim();
if(type1==0)
{
int enroll=Integer.parseInt(editEnrollNo.getEditText().getText().toString().trim());
int card=Integer.parseInt(editCardNo.getEditText().getText().toString().trim());
db.collection("User").document(id).set(new User(name,id,enroll,card,type1)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.cancel();
Toast.makeText(SignUpActivity.this,"Registered Successfully !",Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignUpActivity.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
}
});
}
else {
db.collection("User").document(id).set(new Admin(type1,name,id)).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.cancel();
Toast.makeText(SignUpActivity.this,"Registered Successfully !",Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignUpActivity.this, "Please Try Again !", Toast.LENGTH_SHORT).show();
}
});
}
}
else
{ progressDialog.cancel();
if(task.getException() instanceof FirebaseAuthUserCollisionException)
{
Toast.makeText(SignUpActivity.this,"Already Registered ! ",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(SignUpActivity.this, "Registration Failed ! Try Again ", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View v) {
if(v==check1)
{
if(check1.isChecked())
buttonRegister.setEnabled(true);
else
buttonRegister.setEnabled(false);
}
else if(v==buttonRegister)
registerUser();
else if(v==toSignIn) {
startActivity(new Intent(getApplicationContext(),SignInActivity.class));
finish();
}
}
}
Please can any one help?
When you return from a function, the code written after is never executed. In your method registerUser() every if condition that is true, returns. That means the actual code to register user is never reached.
Is their any way to get click event of keyboard in android? Actually I am developing one app and need the click event of the keyboard. Example, if user press the alphabets 'a' from keyboard in android phone then I want the click event of 'a'. Recently I came across the onKeyListener and used the various KeyCode, but eventually it didn't helped me.
public class KeyCode {
private Context con;
private EditText edt;
private ArrayList<String> array;
public KeyCode(Context con, final ArrayList<String> array, final EditText edt)
{
// TODO Auto-generated constructor stub
this.array=array;
this.con=con;
this.edt=edt;
edt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode==event.KEYCODE_A)
{
if(event.isCapsLockOn())
{
edt.append(array.get(0));
}
else
{
edt.append(array.get(26));
}
}
if(keyCode==event.KEYCODE_B)
{
if(event.isCapsLockOn())
{
edt.append(array.get(1));
}
else
{
edt.append(array.get(27));
}
}
if(keyCode==event.KEYCODE_C)
{
if(event.isCapsLockOn())
{
edt.append(array.get(2));
}
else
{
edt.append(array.get(28));
}
}
if(keyCode==event.KEYCODE_D)
{
if(event.isCapsLockOn())
{
edt.append(array.get(3));
}
else
{
edt.append(array.get(29));
}
}
if(keyCode==event.KEYCODE_E)
{
if(event.isCapsLockOn())
{
edt.append(array.get(4));
}
else
{
edt.append(array.get(30));
}
}
if(keyCode==event.KEYCODE_F)
{
if(event.isCapsLockOn())
{
edt.append(array.get(5));
}
else
{
edt.append(array.get(31));
}
}
if(keyCode==event.KEYCODE_G)
{
if(event.isCapsLockOn())
{
edt.append(array.get(6));
}
else
{
edt.append(array.get(32));
}
}
if(keyCode==event.KEYCODE_H)
{
if(event.isCapsLockOn())
{
edt.append(array.get(7));
}
else
{
edt.append(array.get(33));
}
}
if(keyCode==event.KEYCODE_I)
{
if(event.isCapsLockOn())
{
edt.append(array.get(8));
}
else
{
edt.append(array.get(34));
}
}
if(keyCode==event.KEYCODE_J)
{
if(event.isCapsLockOn())
{
edt.append(array.get(9));
}
else
{
edt.append(array.get(35));
}
}
if(keyCode==event.KEYCODE_K)
{
if(event.isCapsLockOn())
{
edt.append(array.get(10));
}
else
{
edt.append(array.get(36));
}
}
if(keyCode==event.KEYCODE_L)
{
if(event.isCapsLockOn())
{
edt.append(array.get(11));
}
else
{
edt.append(array.get(37));
}
}
if(keyCode==event.KEYCODE_M)
{
if(event.isCapsLockOn())
{
edt.append(array.get(12));
}
else
{
edt.append(array.get(38));
}
}
if(keyCode==event.KEYCODE_N)
{
if(event.isCapsLockOn())
{
edt.append(array.get(13));
}
else
{
edt.append(array.get(39));
}
}
if(keyCode==event.KEYCODE_O)
{
if(event.isCapsLockOn())
{
edt.append(array.get(14));
}
else
{
edt.append(array.get(40));
}
}
if(keyCode==event.KEYCODE_P)
{
if(event.isCapsLockOn())
{
edt.append(array.get(15));
}
else
{
edt.append(array.get(41));
}
}
if(keyCode==event.KEYCODE_Q)
{
if(event.isCapsLockOn())
{
edt.append(array.get(16));
}
else
{
edt.append(array.get(42));
}
}
if(keyCode==event.KEYCODE_R)
{
if(event.isCapsLockOn())
{
edt.append(array.get(17));
}
else
{
edt.append(array.get(43));
}
}
if(keyCode==event.KEYCODE_S)
{
if(event.isCapsLockOn())
{
edt.append(array.get(18));
}
else
{
edt.append(array.get(44));
}
}
if(keyCode==event.KEYCODE_T)
{
if(event.isCapsLockOn())
{
edt.append(array.get(19));
}
else
{
edt.append(array.get(45));
}
}
if(keyCode==event.KEYCODE_U)
{
if(event.isCapsLockOn())
{
edt.append(array.get(20));
}
else
{
edt.append(array.get(46));
}
}
if(keyCode==event.KEYCODE_V)
{
if(event.isCapsLockOn())
{
edt.append(array.get(21));
}
else
{
edt.append(array.get(47));
}
}
if(keyCode==event.KEYCODE_W)
{
if(event.isCapsLockOn())
{
edt.append(array.get(22));
}
else
{
edt.append(array.get(48));
}
}
if(keyCode==event.KEYCODE_X)
{
if(event.isCapsLockOn())
{
edt.append(array.get(23));
}
else
{
edt.append(array.get(49));
}
}
if(keyCode==event.KEYCODE_Y)
{
if(event.isCapsLockOn())
{
edt.append(array.get(24));
}
else
{
edt.append(array.get(50));
}
}
if(keyCode==event.KEYCODE_Z)
{
if(event.isCapsLockOn())
{
edt.append(array.get(25));
}
else
{
edt.append(array.get(51));
}
}
if(keyCode==event.KEYCODE_0)
{
edt.append(array.get(52));
}
if(keyCode==event.KEYCODE_1)
{
edt.append(array.get(53));
}
if(keyCode==event.KEYCODE_2)
{
edt.append(array.get(54));
}
if(keyCode==event.KEYCODE_3)
{
edt.append(array.get(55));
}
if(keyCode==event.KEYCODE_4)
{
edt.append(array.get(56));
}
if(keyCode==event.KEYCODE_5)
{
edt.append(array.get(57));
}
if(keyCode==event.KEYCODE_6)
{
edt.append(array.get(58));
}
if(keyCode==event.KEYCODE_7)
{
edt.append(array.get(59));
}
if(keyCode==event.KEYCODE_8)
{
edt.append(array.get(60));
}
if(keyCode==event.KEYCODE_9)
{
edt.append(array.get(61));
}
/*if(keyCode==event.KEYCODE_DEL)
{
edt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
edt.setText(s);
}
});
}*/
/*if(keyCode==event.KEYCODE_SPACE)
{
edt.append(" ");
}*/
if(keyCode==event.KEYCODE_COMMA)
{
edt.append(",");
}
if(keyCode==event.KEYCODE_PERIOD)
{
edt.append(".");
}
if(keyCode==event.KEYCODE_EQUALS)
{
edt.append("=");
}
if(keyCode==event.KEYCODE_LEFT_BRACKET)
{
edt.append("(");
}
if(keyCode==event.KEYCODE_RIGHT_BRACKET)
{
edt.append(")");
}
if(keyCode==event.KEYCODE_SEMICOLON)
{
edt.append(";");
}
if(keyCode==event.KEYCODE_APOSTROPHE)
{
edt.append("'");
}
if(keyCode==event.KEYCODE_GRAVE)
{
edt.append("~");
}
if(keyCode==event.KEYCODE_SLASH)
{
edt.append("/");
}
if(keyCode==event.KEYCODE_NUMPAD_DIVIDE)
{
edt.append("/");
}
if(keyCode==event.KEYCODE_NUMPAD_MULTIPLY)
{
edt.append("*");
}
if(keyCode==event.KEYCODE_NUMPAD_SUBTRACT)
{
edt.append("-");
}
if(keyCode==event.KEYCODE_NUMPAD_ADD)
{
edt.append("+");
}
return true;
}
});
}
}
This is what my java class is. I have an array of certain characters and I do pass it to this java file to replace the default characters with characters contained in array. The characters are replaced but when the key is pressed from the laptop keyboard not from the keyboard of the android phone.
public class ChangeFont extends ActionBarActivity {
private EditText edt;
private ImageView img1,img2,img3,img4,img5;
private ListView lst, savelist;
private TextView txtNew,txtSave;
private DataBaseHelper data;
private ArrayList<String> category;
private ArrayList<String> styleArray;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_font);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Fonts");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
data=new DataBaseHelper(this);
edt=(EditText)findViewById(R.id.edit_text);
img1=(ImageView)findViewById(R.id.image1);
img2=(ImageView)findViewById(R.id.image2);
img3=(ImageView)findViewById(R.id.image3);
img4=(ImageView)findViewById(R.id.image4);
img5=(ImageView)findViewById(R.id.image5);
lst=(ListView)findViewById(R.id.list);
savelist=(ListView)findViewById(R.id.savelist);
txtNew=(TextView)findViewById(R.id.textnew);
txtSave=(TextView)findViewById(R.id.textsave);
category=new ArrayList<String>();
styleArray=new ArrayList<String>();
try {
data.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c=data.getSample();
if (c.moveToFirst())
{
while(!c.isAfterLast())
{
String cat = c.getString(c.getColumnIndex(DataBaseUtil.SAMPLE));
category.add(cat);
c.moveToNext();
}
}
/*l=data.getAllLockType();
if (l.moveToFirst())
{
while(!l.isAfterLast())
{
String cat=l.getString(l.getColumnIndex(DataBaseUtil.LOCK_TYPE));
Log.i("String",""+cat);
locktype.add(cat);
l.moveToNext();
}
}
Log.i("Lock Array",""+locktype);*/
SampleStyleAdapter aa=new SampleStyleAdapter(getApplicationContext(), category);
lst.setAdapter(aa);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
data.openDataBase();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);
final String stylename = category.get(position).toString();
Toast.makeText(getApplicationContext(), "" + stylename + "position" + position, Toast.LENGTH_SHORT).show();
List<DataBaseModel> sy = data.getStyle(position);
styleArray = new ArrayList<String>();
for (DataBaseModel model : sy) {
String vimal = model.getStyle();
styleArray.add(vimal);
}
Log.i("Style Array", "" + styleArray);
KeyCode key=new KeyCode(getApplicationContext(),styleArray,edt);
//Log.i("Called Key Code","Class");
}
});
edt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lst.setVisibility(View.GONE);
savelist.setVisibility(View.GONE);
txtNew.setVisibility(View.VISIBLE);
txtSave.setVisibility(View.VISIBLE);
edt.requestFocus();
edt.setCursorVisible(true);
//InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);
}
});
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
lst.setVisibility(View.VISIBLE);
savelist.setVisibility(View.GONE);
txtNew.setVisibility(View.GONE);
txtSave.setVisibility(View.GONE);
edt.setCursorVisible(false);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);
}
});
img2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
lst.setVisibility(View.GONE);
txtNew.setVisibility(View.VISIBLE);
txtSave.setVisibility(View.VISIBLE);
edt.requestFocus();
edt.setCursorVisible(true);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);
}
});
img3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(ChangeFont.this, EmojiTabbed.class);
startActivity(i);
}
});
img4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lst.setVisibility(View.GONE);
savelist.setVisibility(View.VISIBLE);
txtNew.setVisibility(View.GONE);
txtSave.setVisibility(View.GONE);
edt.setCursorVisible(false);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);
}
});
img5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(ChangeFont.this, Share.class);
startActivity(i);
}
});
}
#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_change_font, menu);
return false;
}
#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();
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Intent i=new Intent(this, Home.class);
NavUtils.navigateUpTo(this, i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Whether this thing is possible or not?
Click event occur for mouse click or touch down and for you need to capture key down event like this
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (i == KeyEvent.KEYCODE_BACK) {
//back button key up
}
return super.onKeyUp(keyCode, event);
}
and for click event you should use this
yourControl.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// your code
}
});
i hop this will help you
You can get the clicked key characters by keycodes :
List<Key> keys = getKeyboard().getKeys();
for (Key key : keys) {
if (key.codes[0] == 65) { //A
} }
For Reference
http://www.fampennings.nl/maarten/android/09keyboard/index.htm
When I close my app by pressing the BACK button (onBackPressed() called), the CountDownTimer doesn't stop, until it is done with counting. How can I put the CountDownTimer cancel(); in my onBackPressed()?
Because, when I quit my application (shown below with descriptions) I don't want counter toasts on my screen anymore.
On top of my code:
boolean network_connected = false;
What's in my onCreate():
if (check_network.isInternetAvailable(this)) {
network_connected = true;
new connect_task_main().execute("");
} else {
network_connected = false;
}
if (network_connected == false) {
new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
global.toast.setText("No Internet Connection!" + "\n" + "Automatic Refresh In: " + millisUntilFinished / 1000); //set text for toast
global.toast.show(); //show toast
}
public void onFinish() {
if (network_connected == false) {
global.cancel_toast(0); //stop all toasts
finish(); //quit activity
startActivity(new Intent(main_activity.this, main_activity.class)); //start activity
} else {
}
}
}.start(); //start the countdowntimer
} else {
network_connected = true;
}
onBackPressed() method
#Override
public void onBackPressed() {
if (page_number > global.page_number_min) { //does not matter
page_number--; //does not matter
global.cancel_toast(0); //stop all toasts
network_connected = true;
finish();
} else {
global.cancel_toast(0);
network_connected = true;
finish(); //quit activity
super.onBackPressed(); //quit application
}
}
Thanks.
Create a global object of CountDownTimer eg.
On top of the main_activity class set: CountDownTimer timer; after that do the things below.
timer = new CountDownTimer(11000, 1000)
{
public void onTick(long millisUntilFinished)
{
global.toast.setText("No Internet Connection!" + "\n" + "Automatic Refresh In: " + millisUntilFinished / 1000); //set text for toast
global.toast.show(); //show toast
}
public void onFinish()
{
if (network_connected == false)
{
global.cancel_toast(0); //stop all toasts
finish(); //quit activity
startActivity(new Intent(main_activity.this, main_activity.class)); //start activity
}
else
{
}
}
}.start(); //start the countdowntimer
}
and on onBackPressed call timer.cancel(); like
#Override
public void onBackPressed()
{
if (page_number > global.page_number_min)
{ //does not matter
page_number--; //does not matter
global.cancel_toast(0); //stop all toasts
network_connected = true;
finish();
}
else
{
global.cancel_toast(0);
network_connected = true;
finish(); //quit activity
super.onBackPressed(); //quit application
}
timer.cancel();
}
I am following the patterns that are used in the Compass example in a new project and have most of the logic working. However, when I tap while my live card is displayed I hear the 'click' noise but my menu activity doesn't display. I think that I am missing a piece of the puzzle, but I have not been able to figure out what as of yet.
When I tap, besides the click, I also see this in logcat:
01-08 10:02:26.796: I/ActivityManager(196): START {flg=0x10008000 cmp=com.example.speeddisplay/.SpeedDisplayMenuActivity} from pid -1
So it looks like it should be starting my activity, but it doesn't show up. Here are some pieces of relevant code...although I am not sure where the issue is.
Service portion in AndroidManifest.xml:
<service
android:name="com.example.speeddisplay.service.SpeedService"
android:enabled="true"
android:icon="#drawable/ic_drive_50"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
</intent-filter>
<meta-data
android:name="com.google.android.glass.VoiceTrigger"
android:resource="#xml/voiceinput_speeddisplay" />
</service>
onStartCommand method in SpeedService.java:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Constants.DEBUG) {
Log.d(TAG, "onStartCommand");
}
if (liveCard == null) {
liveCard = timelineManager.createLiveCard(LIVE_CARD_ID);
speedRenderer = new SpeedRenderer(this, speedManager);
liveCard.setDirectRenderingEnabled(true);
liveCard.getSurfaceHolder().addCallback(speedRenderer);
// Display the options menu when the live card is tapped.
Intent menuIntent = new Intent(this, SpeedDisplayMenuActivity.class);
menuIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
liveCard.setAction(PendingIntent.getActivity(this, 0, menuIntent, 0));
liveCard.publish(PublishMode.REVEAL);
if(Constants.DEBUG){
Log.d(TAG, "liveCard published");
}
}
return START_STICKY;
}
Here is my SpeedDisplayMenuActivity.java. None of these methods are getting called.
public class SpeedDisplayMenuActivity extends Activity {
private SpeedService.SpeedBinder speedService;
private boolean mResumed;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (Constants.DEBUG) {
Log.e("Service Stuff", "Service connected.");
}
if (service instanceof SpeedService.SpeedBinder) {
speedService = (SpeedService.SpeedBinder) service;
openOptionsMenu();
}
if (Constants.DEBUG) {
Log.e("Service Stuff", "service was an instance of " + service.getClass().getName());
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
// Do nothing.
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(Constants.DEBUG){
Log.e("Menu", "Created.");
}
super.onCreate(savedInstanceState);
bindService(new Intent(this, SpeedService.class), mConnection, 0);
}
#Override
protected void onResume() {
if(Constants.DEBUG){
Log.e("Menu", "Resumed.");
}
super.onResume();
mResumed = true;
openOptionsMenu();
}
#Override
protected void onPause() {
if(Constants.DEBUG){
Log.e("Menu", "Paused.");
}
super.onPause();
mResumed = false;
}
#Override
public void openOptionsMenu() {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open");
}
if (mResumed && speedService != null) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open with correct params");
}
super.openOptionsMenu();
} else {
if (Constants.DEBUG) {
Log.e("Options Menu", "Open with INCORRECT params");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Created");
}
getMenuInflater().inflate(R.menu.speed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Item Selected");
}
switch (item.getItemId()) {
// case R.id.read_aloud:
// mCompassService.readHeadingAloud();
// return true;
case R.id.stop:
if (Constants.DEBUG) {
Log.e("Options Menu", "Stop");
}
stopService(new Intent(this, SpeedService.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onOptionsMenuClosed(Menu menu) {
if (Constants.DEBUG) {
Log.e("Options Menu", "Closed");
}
super.onOptionsMenuClosed(menu);
unbindService(mConnection);
// We must call finish() from this method to ensure that the activity
// ends either when an
// item is selected from the menu or when the menu is dismissed by
// swiping down.
finish();
}
Does anybody see what I am missing?
That is right, declaring the SpeedDisplayMenuActivity is the problem in this case.
I have seen cases where many other types of exceptions / crash that normally happens in Android environment is gracefully handled in Glass.
That is definitely good for the user experience, but makes little tough on development. Hopefully some kind of settings come in future to enable exceptions as well in future!
How can I configure the back button to be pressed twice before the app exits? I want to trigger
#Override
public void onBackPressed() {
//custom actions
//display toast "press again to quit app"
super.onBackPressed();
}
Try this:
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press twice to exit", Toast.LENGTH_SHORT).show();
}
This snippet handle also the reset state when the activityis resumed
I see this question is a bit old but I though this might help some people looking for an alternative to the answers already given.
This is how I handle backing out of my applications. If someone has a better -- or a Google suggested -- method of accomplishing this I'd like to know.
Edit -- Forgot to mention this is for Android 2.0 and up. For previous versions override onKeyDown(int keyCode, KeyEvent event) and check for keyCode == KeyEvent.KEYCODE_BACK. Here is a good link to check out.
private boolean mIsBackEligible = false;
#Override
public void onBackPressed() {
if (mIsBackEligible) {
super.onBackPressed();
} else {
mIsBackEligible = true;
new Runnable() {
// Spin up new runnable to reset the mIsBackEnabled var after 3 seconds
#Override
public void run() {
CountDownTimer cdt = new CountDownTimer(3000, 3000) {
#Override
public void onTick(long millisUntilFinished) {
// I don't want to do anything onTick
}
#Override
public void onFinish() {
mIsBackEligible = false;
}
}.start();
}
}.run(); // End Runnable()
Toast.makeText(this.getApplicationContext(),
"Press back once more to exit", Toast.LENGTH_SHORT).show();
}
}
You could do what you're asking with a global integer and just count it, if > 2, quit.
But you could take a better (IMO) approach, where you question the user if they would like to quit or not:
private void questionQuit(){
final CharSequence[] items = {"Yes, quit now", "No, cancel and go back"};
builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Are you sure you want to quit?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0:
quit();
break;
case 1:
default:
break;
}
}
}).show();
AlertDialog alert = builder.create();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK :
int i = 0 ;
if(i == 1 )
{
finish();
}
i++;
return true;
}
}
return super.onKeyDown(keyCode, event);
}