Beginner Button click event - java

I am new to Android, i am writing a program where when a user clicks a button a Alert Dialog to appear. This alert dialog has 2 buttons, Yes and No. Upon clicking Yes/No, i need to sysout the response.
The code i have so far; Can someone help me add the Alert Dialog;
public class HelloWorldProjectActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myFirstScreen);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==(R.id.button1)){
System.out.println("first button clicked");
// I need a Alert Dialog to appear here, and that will have 2 buttons YES and NO, the users response should be printed to the console.
}
}

You cannot System.out.print().
There are several methods to display the result. One is to use Toast. It will briefly show a text message and then disappear.
new AlertDialog.Builder(this)
.setMessage("Are you sure?")
.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "YES CLICKED",
Toast.LENGTH_LONG).show();
}
}).setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "NO CLICKED",
Toast.LENGTH_LONG).show();
}
}).show();
Modify your code as follows:
The activity class doesn't have to implement OnClickListener.
Thus, remove onClick() method
Go to the layout file, add an attribute android:onClick="click" in the button declaration.
Add public void click(View view) with the previous code.

First of all, there really isn't any system.out to print to in android. What you should try instead is printing to the log. For information on how to print to the log, check this out. To then see the activity of the log (including messages you printed to it), checkout the logcat.
Second, for information on creating an alert dialog, please view this documentation.

Related

How to modify AlertDialog (Android)?

I'm a beginner for Java as well as for Android Studio so, here my problem is: I had created a alert dialog window for an activity with positive button being "OK" and negative button being "No thanks". As shown in the code below.
if(Times==0) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setTitle("Warning");
builder1.setMessage("Rooting of a phone may void your Warranty in most of the cases,so it is adviced to proceed at your own risk");
builder1.setCancelable(true);
builder1.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Times += 1;
dialog.cancel();
}
});
builder1.setNegativeButton(
"No Thanks",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
}
It was going fine but now the catch is I want it to be displayed only once if the user clicks the "OK" button and don't want to show it again if the user clicked "OK". I had created a variable times in my class and initialised it to zero as shown below.
public class rootingRooting extends AppCompatActivity {
int Times=0;
and put the complete AlertDialog in the if loop and incremented it's value when the user clicked "OK" so that the loop may execute only once if the user clicked "OK", but it is of no use whenever I open the activity the alert box is being displayed inspite of clicking "OK". So, now the things i want to do happen is:
The alert box should not be displayed if the user once clicked "OK".
If the user clicked the "no Thanks" button, I want to take him to the home activity. So, how should I use the intent with the "no thanks" button?
Thank you.
You need to use SharedPreferenes to save data persistently, local variables will not help.
something like this:
EDIT As per your request, I have added a sample activity class to show the whole process. See the comments in between for more info
EDIT 2 See the code after //Second Edit comment
public class MainActivity extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//When the activity starts, we look into the shared prefs and get an int of name "ok_clicked" from it.
//0 will be the default value of the int if there is no int stored in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
int times = prefs.getInt("ok_clicked", 0);
//if the times value is 0, we will open the dialog, otherwise nothing happens
if (times==0){
openDialog();
}
}
//Read This comment First: We will create a Method, which create an alert Dialog.
private void openDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Test").setMessage("Lorem ipsum dolor");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When OK button is clicked, an int with value of 1 will be saved in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("ok_clicked", 1);
editor.apply();
}
});
dialog.setNegativeButton("No Thanks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Second Edit: To open another acitivty on No Thanks Button
Intent intent = new Intent(MyActivity.this, HomeActivity.class);
startActivity(intent);
}
});
dialog.show();
}
}

How to show a dialog with Android?

Total noob here. Went through Google's developer reference but didn't find enough detail for me to understand. I am trying to make a dialog box appear when hitting an Action Bar item.
I have 2 classes. The first one is only the DialogFragment, using a AlertDialog builder with a positive button and a negative button.
The 2nd class is the Activity, in which I would like to call my DialogFragment and display the dialog, however I when I try to do that under the OnOptionsItemSelected function, using the following code:
DialogFragment newFragment = new CreateWordListDialog();
newFragment.show(getSupportFragmentManager(), "createWordList");
I get a "cannot resolve method" line error on the 2nd line. Where should this line be placed? I must be missing something here.
Inside the function OnOptionsItemSelected you can construct your AlertDialog, you don't need to create another class for this.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.title) //
.setMessage(R.string.message) //
.setPositiveButton(getString(R.string.positive), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO
dialog.dismiss();
}
}) //
.setNegativeButton(getString(R.string.parking_no_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO
dialog.dismiss();
}
});
builder.show();
In Android studio android.support.v4 etc are not encluded by default. So either add these dependencies manually or use getFragmentManager() instead of getSupportFragmentManager() and the issue will be solved

Where to put activity code?

so I have a code that checks something and I put it in the onCreate() of an Activity. I want to know if it's correct to put it there and also, for some reason the code that checks the Main Activity doesn't work at all, the second one which has a toast works. I think the problem may be in an AlertDialog. Here's the one with the toast:
AlertDialog.Builder Dial = new AlertDialog.Builder(Screen.this);
Dial.setTitle(R.string.Dial_Tit);
Dial.setMessage(R.string.Dial_Mes);
Dial.setPositiveButton("OK", PosBC());
Dial.setNegativeButton(R.string.Dial_NegBC, NegBC());
Dial.show();
Note: both buttons have methods, I just didn't post them. The problem is that the alert doesn't even show. And also for some reason the toast does work, it like automatically clicks thebutton, even thought the method has an intent which doesn't work.
More code as requested:
private DialogInterface.OnClickListener NegBC() {
Intent moveToStart;
moveToStart = new Intent(Screen.this, Launch.class);
startActivity(moveToStart);
return null;
}
private DialogInterface.OnClickListener PosBC() {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
Toast.makeText(getApplicationContext(), R.string.settingsToast, Toast.LENGTH_LONG).show();
return null;
}
Update: I've added the create() method which shows the dialog but it goes like this : when activity is created shows toast, press back goes to settings, press back from settings shows dialog, buttons don't work.
onCreate() will be called whenever you start the application and if it is not cached in the device's RAM.
I do not understand what you are trying to achieve other than that, please edit your post by adding more of your code and I will also edit my answer to be more detailed.
use this code to display alertDialog in android on clicking a button:
package .....; // name of your package.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AlertDialogActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAlertTwoBtns = (Button) findViewById(R.id.button1);
btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Creating alert Dialog with two Buttons
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle(" "); //type your title here insid the quotes.
// Setting Dialog Message
alertDialog.setMessage(" "); //type the message which is to be displayed
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_launcher); // set the icon from drawable folder just put the icon file in drawable folder.
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show(); // just a sample code to tell that what things you can do here
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
}
Write your AlertDialog code in OnCreateDialog and Start a in OnCreate AsynTask for Checking purpose and once your task is finished, inside onPostExecute close the Dialog.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog(0x01);
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder Dial;
switch (id) {
case 0x01:
Dial = new AlertDialog.Builder(Screen.this);
Dial.setTitle(R.string.Dial_Tit);
Dial.setMessage(R.string.Dial_Mes);
Dial.setPositiveButton("OK", PosBC());
Dial.setNegativeButton(R.string.Dial_NegBC, NegBC());
Dial.create();
break;
default:
break;
}
return super.onCreateDialog(id);
}
Ok, I solved it myself, turns out it was just logic missing :D. Sorry!

Android alert dialog Issue

In my android application, I use one alert dialog to display some information to the user, and if the user click the dialog , it should finish the activity. My code is
offer.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
AlertDialog alert=new AlertDialog.Builder(offer.this).create();
alert.setTitle("SVSugar Mill");
alert.setMessage("Offer Number is "+offer_no.getText().toString());
alert.setButton("Click to Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
//return;
}
});
alert.show();
}
});
It doesn't wait for the user response to finish(). Instead it will be called even if the user didn't click the Alert dialog. I know this is asynchronous, but I need to do this.(The OfferNO should be displayed to the user. When the user click the alert dialog it should finish the activity). Is there any way to do this?
Someone help me
Edit:
The activity will be finished without waiting for the user to click the alert dialog
public void ShowDialog(final Context context) {
new AlertDialog.Builder(context)
.setTitle(android.R.string.dialog_alert_title)
.setMessage(UContext.getContext().getString(R.string.network_error))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
this.finish();
}
}).show();
}
The problem is that you created two AlertDialog instances here:
alertDialog=builder.create();
builder.create().show();
Then you called dismiss() on the dialog that is not actually shown. This should fix the problem:
alertDialog=builder.show();

alertDialog button go to URI

As the title says, I want to make a button in my alertDialog of my app go to a certain URI, and I was wondering how i would do this?
heres and excerpt of the code:
// Add a neutral button to the alert box AND assign a listener for said button...
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener(){
// click listener for box
public void onClick(DialogInterface arg0, int arg1){
// Button was clicked!!
Toast.makeText(getApplicationContext(), "Dialog closed successfully!", Toast.LENGTH_LONG).show();
}
});
// Add a Forums button to take user to forums...
alertbox.setPositiveButton("Forums", new DialogInterface.OnClickListener(){
//listener for button
public void onClick(DialogInterface arg0, int arg1){
// Button Pressed!
Toast.makeText(getApplicationContext(), "Oops...this button is broke!", Toast.LENGTH_LONG).show();
}
});
// show it!!!
alertbox.show();
instead of making display the toast info saying the button is broke, I actually want it to launch the browser and take the user to a URI.
There has to be a way...
Ideas?
Thanks!
Updated with more code..
Start intent in onClick() handler:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://website.com"));
startActivity(intent);

Categories

Resources