Android - Back button behavior - android-layout

I have a project with 2 activities, the first one is the "SplashActivity" - where I load some network data - the second one, the MainActivity.
Inside of my MainActivity I have a fragment and inside of this fragment a webview. My first point is, when the user clicks on back button, the SplashScreen is open again.
The back button should behave like:
When the user doesn't navigate inside of my webview, close the app.
When the user navigates in webview, use the back history of the browswer.
I read about back stack here: http://developer.android.com/training/implementing-navigation/temporal.html#back-webviews
I didn't understand at all how it should work, because I have all cases "mixed". Anyone knows what should I do to fix this problem?
Any idea or sample code will be appreciate!

Define Webview wb as a global variable. Then try this;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(wb.canGoBack() == true){
wb.goBack();
}else{
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Application will be closed")
.setMessage("Close app?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}

Related

Toast Message will not display if placed at the beggining of the try catch

I am having an issue with displaying a toast message. I want it to display when a button is initially clicked, so that the user is aware the app is working( in my case, generating a QR code). If I place the toast at the beginning of the try catch it does not display right away when the button is clicked. It displays the toast only after the QR code is generated and displayed. Furthermore, the toast is displayed(after QR code is displayed) on my Android emulator but not at all on my physical android device(I have allowed app permissions) if I place it at the beginning of the try catch. It will only display on my physical device if the toast is at the end of the try catch. This has me puzzled. I attempted to use a ProgressBar that would run on the button click and terminate after the QR code was displayed but found this difficult to implement. I thought the toast would be an easy alternative as I have used them through out my project without any issues until now. If anyone can help me understand how I can get the toast to display right away when the button is clicked instead of displaying after the QR code is generated and displayed, it would much appreciated. Alternatively, if someone could assist me with including a progress bar(circle) to run once the button is clicked and stop once the QR code is displayed that would also be very much appreciated, as I believe this would be the most ideal solution.
Please see code below:
public class Generate extends AppCompatActivity {
public final static int QRcodeWidth = 500 ;
private static final String IMAGE_DIRECTORY = "/QR_Code_Generated";
Bitmap bitmap;
private EditText etQr;
private ImageView ivGenerated;
private Button btn;
private Button clrBtn;
private Button shareBtn;
private ProgressBar progressBar;
private int progressStatus = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generate);
ivGenerated = (ImageView) findViewById(R.id.iv_generated);
etQr = (EditText) findViewById(R.id.generate_input);
btn = (Button) findViewById(R.id.button);
clrBtn = (Button) findViewById(R.id.clearButton);
shareBtn = (Button) findViewById(R.id.shareButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etQr.getText().toString().trim().length() == 0) {
} else {
try {
Toast toast1 = Toast.makeText(Generate.this, "Please Wait, Your QR Code is Generating & will be Saved to your Device... ", Toast.LENGTH_SHORT);
toast1.show();
bitmap = TextToImageEncode(etQr.getText().toString());
ivGenerated.setImageBitmap(bitmap);
String path = saveImage(bitmap); //give read write permission
// Toast.makeText(Generate.this, "QR Code saved to -> " + path, Toast.LENGTH_SHORT).show(); (if I include this second toast it does not display the first toast1)
} catch (WriterException e) {
e.printStackTrace();
}
}
}
});
I dont find any issue with your code for toast pop up, you can try adding a delay of 250ms after toast.show(), maybe it . would be a work around for you.
And for progress bar, its very simple. Create a progress bar in your .xlm file n place it at the center of your View.Layout you willing to show it & make its visibility as FALSE.
You can try this,
progressbar = = (ProgressBar) findViewById(R.id.progressbar);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressbar.setVisibility(VISIBLE); // or try View.VISIBLE
if (etQr.getText().toString().trim().length() == 0) {
} else {
try {
Toast toast1 = Toast.makeText(Generate.this, "Please Wait, Your QR Code is Generating & will be Saved to your Device... ", Toast.LENGTH_SHORT);
toast1.show();
bitmap = TextToImageEncode(etQr.getText().toString());
ivGenerated.setImageBitmap(bitmap);
String path = saveImage(bitmap); //give read write permission
// Toast.makeText(Generate.this, "QR Code saved to -> " + path, Toast.LENGTH_SHORT).show(); (if I include this second toast it does not display the first toast1)
} catch (WriterException e) {
e.printStackTrace();
}
finally {
progressbar.setVisibility(INVISIBLE); // or try View.INVISIBLE
}
}
}
});

Soft keyboard not closing when dialog is cancelled

In my app i have a dialog where the user should enter some text in an edittext. But when I tap outside of the dialog to close the dialog, the dialog closes but the soft keyboard which popped up because i clicked on the edittext stays. It's very weird: when I set windowsoftinputmode to stateAlwaysHidden,the keyboard gets a bit transparent but it doesn't close. I only have this problem in portrait, In landscape it doesn't happen but that could be because the softkeyboard fills the whole screen. I also cant click on the keys of the keyboard it doesn't react. I already tried to set the windowsoftinputmode to different values and I set a oncancellistener on my dialo g which should close the softkeyboard but it doesn't. It's seems to me as a bug.
The code of my dialog
public void create(View view) {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_SWIPE_TO_DISMISS);
dialog.setContentView(R.layout.dialoglayout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = getCurrentFocus();
if (view == null) {
view = new View(getBaseContext());
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
});
editText = dialog.findViewById(R.id.levelname);
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
name = editText.getText().toString();
callables.totaloverwriteFile(name,getApplicationContext(),"newlevelname");
getApplicationContext().startActivity(new Intent(getApplicationContext(), CreatorActivity.class));
return true;
}
return true;
}
});
}```
Try building InputMethodManager from context, something like this (kotlin)
val inputMethodManager = context?.getSystemService<InputMethodManager>()
inputMethodManager?.hideSoftInputFromWindow(view.windowToken,0)

Why does my RotateTransition throw errors after it runs for the first time?

Warning: This is my first time using threads and my first time trying out an animation. Please bear with me.
I want to rotate an ImageView. I set up a thread for it:
public class ThreadAnimation extends Thread
{
private ImageView iv;
private RotateTransition rt;
public ThreadAnimation(ImageView iv)
{
this.iv = iv;
}
#Override
public void run()
{
while (true)
{
RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
r.play();
try
{
sleep(100);
} catch (InterruptedException e)
{
return;
}
}
}
}
I call this inside my controller class, upon pressing a Button.
animation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle (ActionEvent abschicken)
{
ThreadAnimation thread = null; //ANIMATION PIZZA
if (thread == null)
{
thread = new ThreadAnimation(olivenview);
thread.start();
}
}
});
My ImageView olivenview will rotate just like I wanted it to. However it takes quite a long time until it seems to stop (I can see it because the button triggering it still looks triggered for a while) and when I go ahead to press it a second time afterwards, I get a nonstop error stream with a lot of null pointer exceptions. I am very clueless, can anyone help me out? Is this due to my Thread Setup or does the problem lie somewhere else (in code that I didn't post here)?
I believe you do not need threads for this. Notice the .play() method returns immediately and the animation will run in the background.
That being said, try this.
...
//Create your rotation
final RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);
//When the button is pressed play the rotation. Try experimenting with .playFromStart() instead of .play()
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent action) {
r.play();
}
});
...
On an other note I recommend switching to java 8 so that you can use lambda expressions instead of the anonymous class!

Using a button as a boolean switch

I'm trying to make a button in android function as a boolean switch. I want it to do something on the first click and do something else on the second click. On the third click, I want it to do the same thing on the first click et cetera. The main reason I want this due to the text element on the button that changes with each click. Switches and checkboxes have no texts to change.
I've tried finding documentations on doing this online but can't seem to find any previous examples of doing this. Would appreciate if anyone has any ideas or just tell me outright that this is not workable.
yourButton
.setOnClickListener(new View.OnClickListener() {
private boolean state = false;
public void onClick(View v) {
if ( state ) {
state = false;
yourButton.setText("False");
} else {
state = true;
yourButton.setText("True");
}
}
});
You can try something like this, by the way i DIDN'T test this code i'm just trying to show you a way you could try to do it
1. set button to change drawable background and remove
button.setOnClickListener ( new View.OnClickListener () {
private boolean state=false;
#Override
public void onClick(View v) {
if (state){
state=false;
textView.setBackground ( getDrawable(R.drawable.led_mode ) );
}
else{
state=true;
textview.setbackground(null);
}
}
});

Lwuit touch screen strange behaviour

I am making an application using LWUIT.
There is a form
There is a list embedded on the form.
The list has 5 elements.
Initially, when I first load the app, if I choose the 1st element, 2nd gets chosen; when I choose the second the 3rd gets chose and and so on (Weird!)
I am not able to click any button on the screen either
next what I do is, shift to a different from using arrow keys (of the keyboard... I am running the app on a simulator btw)
Then I come back to the first form and now everything works as expected(no weird behaviour).
What could be the issue?
I am using Sun Java Micro Edition SDK 3.0 (default touch screen for testing)
My code is:
List dummy = new List();
dummy.addItem("wewerwer");
dummy.addItem("wewerdswer");
dummy.addItem("wewqweerwer");
dummy.addItem("dscxwewerwer");
dummy.addItem("jhgwewerwer");
mainListForm.setLayout(new BorderLayout());
mainListForm.addComponent(BorderLayout.CENTER,dummy);
mainListForm.show();
What could possible be going wrong here?
UPDATE 1
I think there is a bug here. I have attached the complete code below along with the screen shot
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
public class Demo extends MIDlet implements ActionListener {
private Form mForm;
List abc;
public void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/Test.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0])
);
} catch (Exception e){
System.out.println(e.toString());
}
if (mForm == null) {
Button click = new Button("Press me!");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("I have been pressed");
}
});
abc = new List();
abc.addItem("Str1");
abc.addItem("Str2");
abc.addItem("Str3");
abc.addItem("Str4");
abc.addItem("Str5");
abc.addItem("Str6");
Form f = new Form("Hello, LWUIT!");
abc.addActionListener(this);
f.addComponent(abc);
Command exitCommand = new Command("Exit");
f.addCommand(exitCommand);
f.addCommandListener(this);
f.addComponent(click);
f.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
System.out.println(abc.getSelectedIndex());
}
}
So now when I click on 'Str1' of the list Str2 gets selected and so on.
IDE: Netbeans
Emulator: Default Touch screen phone
On the action event set the list to active again after the event by invoking setHandlesInput(true)
OK....so this is how you resolve it.
After the form is displayed remove the list from the form and again add it to the form and then repaint the form.
Earlier Code
1) form.addComponenet(BorderLayout.center,list);
2) form.show();
Word Around for the problem
1)form.addComponenet(BorderLayout.center,list);
2)form.show();
3)form.setScrollable(false);
I know its kind of strange, but this way the list index selection works smooth for touch screen phones.

Resources