Android Radio Button Not selected giving error - android

I have a Android Radio button, i need to display the error message if the Radio button is not selected. Hence i included the below Java code, but its giving the below error.
Logcat ERROR:
07-12 16:00:08.139: E/AndroidRuntime(8282): Uncaught handler: thread main exiting due to uncaught exception
07-12 16:00:08.149: E/AndroidRuntime(8282): java.lang.NullPointerException
07-12 16:00:08.149: E/AndroidRuntime(8282): at com.example.triviality.QuizActivity$1.onClick(QuizActivity.java:67)
In the 67th Line the below sentence is there
String answerval = (String) answer.getText();
Please find the Partial Java Code:
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
String answerval = (String) answer.getText();
if (answerval == "")
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuizActivity.this);
alertDialog.setTitle(" ");
alertDialog.setIcon(R.drawable.wrong);
alertDialog.setMessage("Please select one Option");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
}
});
alertDialog.show();
}
}

You want to display error message when no RadioButton are selected.
If that's the case then grp.getCheckedRadioButtonId() will return -1 and hence answer will be null.
Then if you try to do answer.getText() you will get a NullPointerException because you are caling getText on a null object.
EDIT:
Replace
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
String answerval = (String) answer.getText();
if (answerval == "")
with
if(grp.getCheckedRadioButtonId()==-1)

Related

Add a value to a list everytime the user answers correctly

I have a code written where a user has to answer a question true or false. What I want to do is everytime when a user answers correctly I add +1 to my arraylist. And then at the end of the game I display the number of answered questions. I tried to do it my way, however I get an error.
Here is how I create my list:
final ArrayList<Integer> points = new ArrayList<Integer>();
This is the button if the user presses True(For better understanding: When a user presses true a pop up window opens with the answer correct or false and the correct answer of the question. When the user clicks on the closepopup button an if method runs and checks if he pressed the right button and if its not the last question. If not, it shows the next question and adds the +1 to the list):
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopupWindow();
if(type.get(count[0])){
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!");
} else {
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!");
}
//Show the first answer on first button click.
((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer);
// When PopUp button closes open the next question with the if/else conditions.
btnClosePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if the question is true show next question/ else close app
if (type.get(count[0])) {
points.add(1); // if the answer is correct add +1 to the list.
if(questions.size()-1 == count[0]) // if you count[0] is init to 0
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("WInner");
builder.setMessage("You won, play again?");
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// just close dialog
dialog.cancel();
}
});
builder.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
mResult.setText(points.size());// here I try to print the number of answered questions.
}
});
// Create dialog from builder
AlertDialog alert = builder.create();
// Show dialog
alert.show();
count[0]=0;
}
else if(questions.size()-1 < count[0])
try {
throw new Exception("Invalid ");
} catch (Exception e) {
e.printStackTrace();
}
else
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
} else {
count[0]++;
mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore
pwindo.dismiss();
}
}
});
}
});
EDITED!!!
I figured out why SetText shows a blank textview. I want to show the answered question count in activity before the questions. I have a menuActivity>LevelselectActivity>GameActivity. In game activity I add to the list values. How to post them in LevelselectActivity? Should I use shared preferences? I have no idea now..

Android Facebook - Login / Logout Dialog

I've managed to successfully implement Facebook login into my Android app.The issue I'm facing is,on my logout,whenever I click the logout button,I would like to capture the click of "Cancel / Logout" options.How do I go about doing this?Below are images attached for a much clearer illustration.
As shown in the images,how do I go about capturing the clicks in the highlighted red circles?
Below attached are my codes for the login/logout activity as well.Thank you :)
View view = inflater.inflate(R.layout.splash, container, false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.login_button);
authButton.setFragment(this);
// Get more permissions
authButton.setPublishPermissions(Arrays
.asList("publish_actions,read_stream"));
authButton.setFragment(getParentFragment());
I now this post is very old but...
I had the same problem as you, what I did was:
(only sure for facebook sdk v2.0)
1. Go to package com.facebook.widget;
2. Open the file LoginButton.java;
3. Go to line 819 inside the public void onClick(View v);
4. See the allert Dialog? I just comented the code as follows:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openSession.closeAndClearTokenInformation();
}
});
/*.setNegativeButton(cancel, null);*/
builder.create().show();
And it is done!, no more annoying cancel button on dialog.
(You can also remove the whole dialog)
I got the same problem and searched some many answers,but they doesnot work,so I just write some new codes in LoginButton.java in facebook sdk,my frist step:
public interface LogoutListener{
public void afterLogin();
}
private LogoutListener mLoginoutListener;
public void setLogoutListener(LogoutListener loginoutListener){
this.mLoginoutListener = loginoutListener;
}
second step:find 811 lines in LoginButton.java and you will see the code just like this:
private class LoginClickListener implements OnClickListener {
#Override
public void onClick(View v) {
Context context = getContext();
final Session openSession = sessionTracker.getOpenSession();
if (openSession != null) {
// If the Session is currently open, it must mean we need to log out
if (confirmLogout) {
// Create a confirmation dialog
String logout = getResources().getString(R.string.com_facebook_loginview_log_out_action);
String cancel = getResources().getString(R.string.com_facebook_loginview_cancel_action);
String message;
if (user != null && user.getName() != null) {
message = String.format(getResources().getString(R.string.com_facebook_loginview_logged_in_as), user.getName());
} else {
message = getResources().getString(R.string.com_facebook_loginview_logged_in_using_facebook);
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openSession.closeAndClearTokenInformation();
// here is what I added
if(mLoginoutListener != null){
mLoginoutListener.afterLogin();
}
}
})
.setNegativeButton(cancel, null);
builder.create().show();
} else {
openSession.closeAndClearTokenInformation();
}
third step,and this is how I use :
LoginButton floginButton = (LoginButton)findViewById(R.id.flogin_button);
floginButton.setLogoutListener(new LogoutListener() {
#Override
public void afterLogin() {
// do what you want ,when user click the "OK" button.
}
});
I changed a little bit codes in facebook sdk,and it worked for me,I hope this can help you.

Return Boolean value from Android AlertDialog function

In my app i have a function that checks the entered text from a displayed AlertDialog with an input text. If the text is equal to a string variable, return True, else return False, and catch this resulting value to continue conditional code.
But it seems its a little difficult to do this as i've read in other posts asking how to solve the same problem.
I've already done this:
private boolean checkAdministratorPassword() {
final enterPasswordResult[0] = false;
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Confirm action");
alert.setIcon(R.drawable.ic_launcher);
alert.setMessage("Enter administrator pass to continue");
final EditText input = new EditText(mContext);
input.setPadding(5, 0, 5, 0);
alert.setView(input);
alert.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strPass = input.getEditableText().toString();
if (strPass.length() == 0) {
dialog.cancel();
}
if (strPass.equalsIgnoreCase(Constantes.ADMIN_PASS)) {
enterPasswordResult[0] = true;
dialog.cancel();
} else {
Toast.makeText(mContext, "Invalid pass..!!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
return enterPasswordResult[0];
}
And i call the function this way:
If ( checkAdministratorPassword() == True ){
//true conditions
}
But the problem is that the check function doesnt wait for the result to continue with the code, it just continue by itself and i dont get the appropiate behavior.
The issue is you're trying to handle an async event in the logcal flow of your program. You can do this if you make the Dialog it's own class and use an Interface to callback to your host activity. Check out the documentation on DialogFragment.
public interface PasswordCheckListener{
public void valid(boolean check);
}
private static class PasswordDialog extends DialogFragment {
private PasswordCheckListener listener;
public static PaswordDialog newInstance(PasswordCheckListener listener){
this.listener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Put your dialog creation code here
}
private checkAdminPassword(){
//Whatever your check passowrd code is
listener.valid(result);
}
}
I realize I didn't implement all the code for you but that's the general idea. By using an interface you can call back to your host Activity or Fragment when the user enters the password and presses submit. You can then handle the event as it happens, rather than having to deal with it in your program flow.
Thank you all for your answers!! i've found the right way to achieve this problem by creating an Activity whith theme "Theme.Dialog", an input text and two buttons (Accept, Cancel), i start this activity for result asking the user to enter the administrator pass to continue, checking the string and then returning again to onActivityResult() from previous activity with the correct information to proceed.

Android AlertDialog EditText dismiss error

I have to get a password from user via AlertDialog and EditText. When user opens this AlertDialog and then presses Cancel or back button, it disappears normally. However when user opens this AlertDialog again, application will be broken. My code here, where am I making mistake?
sifrePencere.setTitle("Çıkış");
sifrePencere.setMessage("Uygulamayı kapatmak için lütfen şifreyi giriniz:");
sifrePencere.setView(sifre);
sifrePencere.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String girilenSifre = sifre.getText().toString();
SQLiteDatabase db = vt.getReadableDatabase();
Cursor kayit = db.rawQuery("SELECT sifre FROM CocukTableti", null);
kayit.moveToFirst();
if (girilenSifre.equals(kayit.getString(0))) {
android.os.Process.killProcess(android.os.Process.myPid());
} else {
dialog.dismiss();
dialog.cancel();
Toast.makeText(getApplicationContext(), "Girilen şifre hatalı!", Toast.LENGTH_SHORT).show();
}
}
});
sifrePencere.setNegativeButton("Vazgeç", null);
sifrePencere.show();
I was showing this AlertDialog in OptionsMenu. But I defined the variables on top of my codes. So, error comes from here. I defined these variables into OnOptionsItemClick, it fixed!
On top of your code write
mybuilder = new AlertDialog.Builder(this);
and before
sifrePencere.show():
write this statement
myAlertDialog = mybuilder.create();

How to transfer parameters value from dialog box to activity in android?

I have an activity (Main) and I inserted a button in it.
When button the user press it, a dialog box with 2 Radio boxes appear. I want to set "1" or "0" value to "ntv", based on which radiobutton is selected, and then use "ntv" value in Main activity, but it seems that this doesnot transfer "ntv" value to Main activity, what is wrong with my code?
final CharSequence[] chan = {"Minutes", "Seconds"};
builder = new AlertDialog.Builder(Main.this);
builder.setTitle("Please Select:");
builder.setSingleChoiceItems(chan, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(chan[item]=="Minutes")
{
Toast.makeText(getApplicationContext(), "Minutes", Toast.LENGTH_SHORT).show();
ntv="1";
}
else if (chan[item]=="Seconds")
{
Toast.makeText(getApplicationContext(), "Seconds", Toast.LENGTH_SHORT).show();
ntv="0";
}
}
});
AlertDialog alert = builder.create();
alert.show();
I defined "ntv" as string and this is part of code when "ntv" is compared to check if it is "0" or "1"
ImageView set1= (ImageView) findViewById(R.id.set1);
ImageView set2= (ImageView) findViewById(R.id.set2);
if (ntv.equals("0")) {
set1.setVisibility(View.INVISIBLE);
}
if (ntv.equals("1")) {
set2.setVisibility(View.INVISIBLE);
}
and because neither (set1) nor (set2) doesnot go invisible I realize that "ntv" have no value.
This all looks OK (except the suggestion to use equals() instead of == for the string compares, although, as you say, it does work (it just isn't good practice).
The only thing I can think of (without seeing all the code) is that the scope of variable ntv is wrong. Have you declared the variable inside a method? It needs to be defined as an instance variable in your class (ie: not within a method).
you should be doing .equals on the string comparison NOT ==
It is unlikely that your if statements will trigger because of this.
if(chan[item].equals("Minutes"))
{
Toast.makeText(getApplicationContext(), "Minutes", Toast.LENGTH_SHORT).show();
ntv="1";
}
else if (chan[item].equals("Seconds"))
{
Toast.makeText(getApplicationContext(), "Seconds", Toast.LENGTH_SHORT).show();
ntv="0";
}
it's not clear the complete code you use and how you call the code that change visibility. Below an example
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder builder;
final CharSequence[] chan = {"Minutes", "Seconds"};
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Please Select:");
builder.setSingleChoiceItems(chan, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(chan[item].equals("Minutes")) {
showToast("Minutes");
} else if (chan[item].equals("Seconds")) {
showToast("Seconds");
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showToast(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
instead of showToast function you can use a your function to change visibility

Categories

Resources