What data type is - java

i've created a function and set it to onClick, so every time i hit the button this function is called. It is called, but the value of 4 other functions i can't get them in setMessage() function(when we create a dialog box). So the logic is like, after hitting the button first we check which radioId1 is equal to which id, and call the appropriate fucntion(video,cons,news,pict).These 4 funct. return some string. Then i want to add these strings to some text in my dialog box, like ....SetMessage(checkMyId() + "Some text").SetPositiveButton(...)...
but the problem is my function checkMyId is set to onClick, so it recieves an argument View v, and when i call it "mannualy" in SetMessage() it shows error, because i don't know what to put inside that parenthesis. So the question is, what type of data(or whatever) is that View ? i saw some documentation and didn't understood much or at least how to implement that in my problem.
public void checkMyId(View v) {
int radioId1 = radioGroup.getCheckedRadioButtonId();
if (radioId1 == R.id.radio_one) {
video();
} else if (radioId1 == R.id.radio_two) {
pict();
} else if (radioId1 == R.id.radio_three) {
cons();
} else news();
}
EDITED
Picture of the error

sir you have 2 way
first try this ( HINT : Don't forget to implement ONCLICK in activity )
public void checkMyId(View v) {
switch (v.getId()) {
case R.id.radio_one:
video();
break;
case R.id.radio_two:
pict();
break;
case R.id.radio_three:
cons();
break;
default:
news();
break;
}
}
sec you can use it in OnCreate ( HINT : this on radio group ) HERE
(findViewById(R.id.radio_one)).setOnCheckedChangeListener(new
OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
}
});
____ READ This also for single RB

Related

Why is the text in TextViews changing two times when I am calling it only once at a time?

I know setText just changes the text only once but I can't seem to find the reason why the text in it changes before I move on to the next question in the quizActivity
What I have made is an app with one activity in it which has a quiz in it, a question is displayed along with 4 options. When the user selects an option, if that option is correct then it becomes green and red otherwise and additionally, I then open a dialog box showing whether the answer was right or wrong and then the question is changed when the user clicks Next on the dialog box.
But what is happening that when the user selects an option, in between the process of clicking the option and then clicking next on the dialog box, the text in the questions and the options changes and I can't seem to figure out why is that happening. In total, the question and options change two times when they should change only once, the unexpected change is when the user clicks on an option and the dialog box opens.
Here's the code:
#Override
public void onClick(View view) {
int selectedOption = 0;
switch (view.getId()) {
case R.id.option_1_tile:
selectedOption = 1;
break;
case R.id.option_2_tile:
selectedOption = 2;
break;
case R.id.option_3_tile:
selectedOption = 3;
break;
case R.id.option_4_tile:
selectedOption = 4;
break;
default:
}
checkAnswer(selectedOption, view);
}
Here's the function which checks the answer:
private void checkAnswer(int selectedOption, View view) {
if (selectedOption == selected_questions.get(quesNum).getAnswer()) {
//Right Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
quizReference.child(selected_questions.get(quesNum).getId()).child("correct_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getCorrect_attempts()) + 1));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
score++;
correctDialog();
} else {
//Wrong Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
switch (selected_questions.get(quesNum).getAnswer()) {
case 1:
options[0].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 2:
options[1].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 3:
options[2].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 4:
options[3].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
}
wrongDialog ();
}
}
Here's the function which changes the question:
private void changeQuestion() {
resetColor ();
if (quesNum < selected_questions.size() - 1) {
quesNum++;
playAnim(question, 0, 0);
playAnim(option1_text, 0, 1);
playAnim(option2_text, 0, 2);
playAnim(option3_text, 0, 3);
playAnim(option4_text, 0, 4);
qCount.setText(String.valueOf(quesNum + 1) + "/" + String.valueOf(selected_questions.size()));
} else {
// Go to Score Activity
Intent intent = new Intent(quizActivity.this, scoreActivity.class);
intent.putExtra("SCORE", String.valueOf(score) + "/" + String.valueOf(selected_questions.size()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Here's the function which sets the text and animation:
private void playAnim(final View view, final int value, final int viewNum) {
view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(500)
.setStartDelay(100).setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
if (value == 0) {
switch (viewNum) {
case 0:
((TextView) view).setText(selected_questions.get(quesNum).getQuestion());
break;
case 1:
((TextView) view).setText(selected_questions.get(quesNum).getOption1());
break;
case 2:
((TextView) view).setText(selected_questions.get(quesNum).getOption2());
break;
case 3:
((TextView) view).setText(selected_questions.get(quesNum).getOption3());
break;
case 4:
((TextView) view).setText(selected_questions.get(quesNum).getOption4());
break;
}
if (viewNum != 0)
(view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#E99C03")));
playAnim(view, 1, viewNum);
}
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
Here's the code for the dialog boxes:
public void wrongDialog() {
final Dialog dialogWrong = new Dialog(quizActivity.this);
dialogWrong.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogWrong.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogWrong.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogWrong.setContentView(R.layout.dialog_wrong);
dialogWrong.setCancelable(false);
dialogWrong.show();
TextView wrongText = (TextView) dialogWrong.findViewById(R.id.wrongText);
Button buttonNext = (Button) dialogWrong.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogWrong.dismiss();
//reset the color of buttons back to white
resetColor();
//Change question
changeQuestion();
}
});
}
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(quizActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
Button buttonNext = (Button) dialogCorrect.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//reset the color of buttons back to white
resetColor();
//it will increment the question number
changeQuestion();
}
});
}
I have tried to explain it to my best ability though I would be glad to answer any additional information/code you may want. Also, this is the link for the project if you have the time to run it and understand the problem better.
I have checked your code. you have placed an addValueEventListener in setUpdates method. When you select an option, you update the firestore database by setting fields like total attempts. As a result, eventListener gets triggered and "selectQuestionSet" function is called.
Hence, every time you select an option, selectQuestionSet function is called. You should make sure that its called only once at the start.

how to use onClick function within a condition or calling it in a function? Android

i want to use my PlayerClick(view v) inside a if condition . but it gives me null Exception. it has to retrieve button id.
//Main Code where i wan to call
while (gameLoop > 0){
while(PlayerClick(null) != 1){
if( WinnerCheck(currentUser.getSymbolValue()) == 1 || WinnerCheck(currentUser.getSymbolValue()) == 0 ){
return currentUser;
}
if (gameLoop % 2 == 0)
currentUser = me;
else
currentUser = opponent;
}
gameLoop--;
}
Function Is here
public int PlayerClick(View v) {
//
switch(v.getId()){
case R.id.btnone:
return -1;
case R.id.btntwo:
return -1;
}
return 1;
}
Aim to do this just to pause a while loop while right button is being clicked
im using android:onclick = "PlayerClick" for four buttons in XML
i want to use my PlayerClick(view v) inside a if condition . but it
gives me null Exception.
Because you are passing null to PlayerClick method.
To get it work you should pass Button view which is pressed by user as parameter in PlayerClick method.
findViewById(android.R.id.yourlayout) pass this in PlayerClick()
like
PlayerClick(findViewById(android.R.id.yourlayout))
Do
button.setOnClickListener(this);
Let your activity implement OnClickListener
And when you get onClick(View v) of activity, do as below
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_nativex:
PlayerClick(v);
break;
default:
break;
}
}
public int mPlayerClick;
public void PlayerClick(View v) {
int viewId = v.getId();
if (viewId == R.id.btnone) { mPlayerClick = -1; }
if (viewId == R.id.btntwo) { mPlayerClick = -1; }
else mPlayerClick = 1;
}
And then.
while (gameLoop > 0){
while(mPlayerClick != 1){
...
I don't understand what you are trying to do though, so this might be wrong. This way mPlayerClick will be set to 1 (and stop your loop) only if the user clicks on some button that is not either btnone or btntwo.
Of course all of your buttons need to call PlayerClick() on click.

Can't get my if statement to work?

I know this has got to be simple. But for the life of me i don't know why i can't get this right.
Ok so I want to go from a listview page (got that) then click a switch to make it go to the next page (also got that.) Then I want a int to tell me which position I am on form the last page (might be working?) now i can't get the If Else statement to work in the page.
public class NightmareParts extends Activity
{
public int current_AN_Number = NightmareList.AN_position_num;
private TextView edit_title;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.part_layout);
// isn't working here. Why?
// test_edit = (TextView)findViewById(R.id.directions_tv);
// test_edit.setText(R.string.directions_text_two);
// works without this being in here.
setDoneButtonListener();
}
//Set up the Done button to initialize intent and finish
private void setDoneButtonListener()
{
Button doneButton = (Button) findViewById(R.id.back_button);
doneButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
finish();
}
});
}
private void editTitle()
{
if (current_AN_Number = 1)
{
edit_title = (TextView)findViewById(R.id.part_title);
edit_title.setText(R.string.AN_title_1);
}
}
}
The current_AN_number is coming from the last page.
Your if statement is incorrect:
if (current_AN_Number = 1)
You've used the assignment operator, when you wanted to compare it with the == operator:
if (current_AN_Number == 1)
if (current_AN_Number = 1)
Should be
if (current_AN_Number == 1)
You're not setting current_AN_Number to be 1, you are comparing if it is equal to 1. So use ==.
test_edit = (TextView)findViewById(R.id.directions_tv);
is not working because test_edit is never declared.

How to create a four digit password Android layout

I want to create a layout for an Android app that has a numeric keypad and takes four digits to determine if it matches a preset passcode value.
I have seen a few applications use this, so I would have thought that it was a high level widget of some description.
The only thing I can find that's remotely close to what I want is this:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="numberPassword" >
<requestFocus />
</EditText>
But this isn't really what I'm looking for.
Any input would be awesome and thanks in advance.
EDIT: Here's an image of the iOS dropbox app start screen that I'd like:
I'm beginner in Android.
when I stuck in coding I always use to refer stackoverflow. I have learnt lot of things from stackoverflow.
This is the first time i have dared to answer this question.
Pardon me if I'm wrong and any suggestion regarding coding or the way of writing code in stackoverflow is highly appreciated.
Thank You..
I have did something like this in Fragments..
Take 4 EditText in and set maxLength attribute to 1 in xml for all 4 EditTexts. You can modify EditText as per your requirement.
Note: OnKey method may or may not be not be invoked for DEL(BackSpace) in Stock Android KeyBoard.
public class VerifyCodeFrag extends Fragment implements TextWatcher,View.OnKeyListener,View.OnFocusChangeListener
{
private EditText et_digit1, et_digit2, et_digit3, et_digit4;//In this et_digit1 is Most significant digit and et_digit4 is least significant digit
private int whoHasFocus;
char[] code = new char[4];//Store the digits in charArray.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment_verify_code, container, false);
initializeView(view);
et_digit1.requestFocus();//Left digit gets focus after adding of fragment in Container
return view;
}
This method is used to intilize views.
private void initializeView(View view)
{
et_digit1 = (EditText) view.findViewById(R.id.et_vfcode_digit1);
et_digit2 = (EditText) view.findViewById(R.id.et_vfcode_digit2);
et_digit3 = (EditText) view.findViewById(R.id.et_vfcode_digit3);
et_digit4 = (EditText) view.findViewById(R.id.et_vfcode_digit4);
setListners();
}
This method is to set the listeners for each EditTexts.
private void setListners()
{
et_digit1.addTextChangedListener(this);
et_digit2.addTextChangedListener(this);
et_digit3.addTextChangedListener(this);
et_digit4.addTextChangedListener(this);
et_digit1.setOnKeyListener(this);
et_digit2.setOnKeyListener(this);
et_digit3.setOnKeyListener(this);
et_digit4.setOnKeyListener(this);
et_digit1.setOnFocusChangeListener(this);
et_digit2.setOnFocusChangeListener(this);
et_digit3.setOnFocusChangeListener(this);
et_digit4.setOnFocusChangeListener(this);
}
These are the override method of interface OnFocusChangeListner by which I'm checking which EditText currently has focus from where it is useful to fetch number from respective EditText Boxes in afterTextChnged method(override method of TextWatcher).
#Override
public void onFocusChange(View v, boolean hasFocus)
{
switch(v.getId())
{
case R.id.et_vfcode_digit1:
whoHasFocus=1;
break;
case R.id.et_vfcode_digit2:
whoHasFocus=2;
break;
case R.id.et_vfcode_digit3:
whoHasFocus=3;
break;
case R.id.et_vfcode_digit4:
whoHasFocus=4;
break;
default:
break;
}
}
These are the override method of TextWatcher Interface.
Here in this afterTextChanged(override method)
I'm fetching number from EdiTexts storing them in respective index of charArray.
And once the user enter the number in EditText the next EditText will get focus by requestfocus method(Example:et_digit2.requestFocus()).
#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)
{
switch (whoHasFocus)
{
case 1:
if(!et_digit1.getText().toString().isEmpty())
{
code[0]= et_digit1.getText().toString().charAt(0);
et_digit2.requestFocus();
}
break;
case 2:
if(!et_digit2.getText().toString().isEmpty())
{
code[1]= et_digit2.getText().toString().charAt(0);
et_digit3.requestFocus();
}
break;
case 3:
if(!et_digit3.getText().toString().isEmpty())
{
code[2]= et_digit3.getText().toString().charAt(0);
et_digit4.requestFocus();
}
break;
case 4:
if(!et_digit4.getText().toString().isEmpty())
{
code[3]= et_digit4.getText().toString().charAt(0);
}
break;
default:
break;
}
}
This method will functionate as delete(BackSpace) key.
In this override method I'm checking whether EditText is empty and DEL(backspace in keypad is pressed).
if true the previous EditText will get focus.
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if (keyCode == KeyEvent.KEYCODE_DEL)
{
switch(v.getId())
{
case R.id.et_vfcode_digit2:
if (et_digit2.getText().toString().isEmpty())
et_digit1.requestFocus();
break;
case R.id.et_vfcode_digit3:
if (et_digit3.getText().toString().isEmpty())
et_digit2.requestFocus();
break;
case R.id.et_vfcode_digit4:
if (et_digit4.getText().toString().isEmpty())
et_digit3.requestFocus();
break;
default:
break;
}
}
}
return false;
}
}
Sample image.
[1]: https://i.stack.imgur.com/DAc9y.jpg
Did you try adding this:
android:maxLength="4"
android:password="true"
This results in a more password like way.
Update: I'd implement four EditText and make them each maxLength="1".
If you align them horizontally this should work :)
I want to create a layout for an Android app that has a numeric keypad
and takes four digits to determine if it matches a preset passcode
value.
Search for a phone client numeric keypad (e.g. SipDroid (dialpad link), IMSDroid), reconstruct the layout to your needs (e.g. removing #, * and other keys you don't need).
use the suggested attributes from #Tim Messerschmidt
Think out of a secure way to store and retrieve that 4 digit pin code.
In the end I created multiple custom widgets.
There is a Keypad widget. It inherits from TableLayout and has four rows of three buttons. Each button modifies a String - either adding digits or removing them.
Another widget I added was called PINEntry. It takes a single int to specify how many digits have been entered and displays that information accordingly.
I use these two widgets together in another View to recreate the passcode screen.

Why cant i get these calculations to display on a textview?

Im trying to make an app that converts distance/area/volume using spinners as a unit selection method. Calculations are meant be done and then the output sent to a textview based on what is entered into the EditText. But the output is only ever 0.0 and nothing else. Can anybody help with this ?
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
switch(pos){
case 0:
option1.setAdapter(length);
option2.setAdapter(length);
return;
case 1:
option1.setAdapter(area);
option2.setAdapter(area);
return;
default:
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
option1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(pos>=0) {
stringInput = edittext1.getText().toString();
if(stringInput == null || stringInput.isEmpty()) {
doubleInput = 0.0;
}
else {
doubleInput = Double.parseDouble(edittext1.getText().toString());
}
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
option2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
switch(pos) {
case 0:
miles = doubleInput * 1;
textview1.setText("" + String.valueOf(miles));
return;
case 1:
km = doubleInput * 1.609344;
textview1.setText("" + String.valueOf(km));
return;
default:
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
At the risk of sounding like a really old man, this looks like your college homework... Is it?
Your code has changed since asking the question, which makes it pretty difficult to answer! Luckily I managed to scrape your code into Eclipse before you changed it... Anyway, in your original code your performing all your operations in the create method, at which point you haven't entered a value for edittext1 (unless it's set to some sensible default, which I presume would be 0, hence always getting zero as your answer?)
// Whilst setting up a view the create method will not have a
// reasonable value for edittext1 - or it will be your default
String stringInput = (edittext1.getText().toString());
if (stringInput.isEmpty()) {
doubleInput = 0.0; // Will always enter this line
} else {
doubleInput = Double.parseDouble(edittext1.getText().toString());
}
You've duplicated the code...
output1 = (TextView) findViewById(R.id.output1);
Actually output1 through to output10 (ie all ten lines) are duplicated.
As to your updated code, is it still giving you a problem? Are you sure that stringInput has a value? I mean have you typed something in? You could check by debugging your program..
The following is also error prone as FloatingCoder suggests, and is likely to break...
doubleInput = Double.parseDouble(edittext1.getText().toString());
A better way to do this (because it catches the exception that Java might throw) is
doubleInput = 0.0;
String inputStr = question.getText().toString();
try {
doubleInput = Double.parseDouble(inputStr);
} catch (NumberFormatException e) {
// This should probably do something more useful? i.e. tell
// the user what they've done wrong...
Log.e("Android",
"Double throws a NumberFormatException if you enter text that is not a number");
}
Oh and Android has some helper utilities for checking strings, see TextUtils, or just my example...
if (!TextUtils.isEmpty(inputStr)) { // checks for "" and null (see documentation)
doubleInput = Double.parseDouble(inputStr);
}
I'd REALLY recommend writing a simple test case for a calculation that looks incorrect, because two text boxes and a button really aren't hard to throw together and are seriously easy to debug without the need for all the spinners getting in the way... Anyway hope this helped, oh and my complete example with two edittexts and a button, I'll just post that here... Hope it helps...
private Button btnCalc;
private EditText question, answer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
answer = (EditText) findViewById(R.id.answer);
question = (EditText) findViewById(R.id.question);
btnCalc = (Button) findViewById(R.id.btnCalc);
// The OnClickListener here will be executed outside the "Create",
// i.e., when you actually click on the button, which will give you
// a chance to enter some values in the question edittext...
btnCalc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
double in = 0.0;
try {
String inputStr = question.getText().toString();
// if you want to check it use
if (!TextUtils.isEmpty(inputStr)) {
in = Double.parseDouble(inputStr);
}
} catch (NumberFormatException e) {
// This should probably do something more useful? i.e. tell
// the user what they've done wrong...
Log.e("Android",
"Double throws a NumberFormatException if you enter text that is not a number");
}
double miles = in * 1.6;
answer.setText(String.valueOf(miles));
}
});
}
It's a little hard to tell from the code you posted, but my guess is that you are setting doubleInput when option 1 is selected. If you are entering the number after you select option 1, it will always be 0.0, as the number was not in the text area when the spinner was changed.
Use a debugger to step through the code and see if you are ever reaching the line
doubleInput = Double.parseDouble(edittext1.getText().toString());
and to check that the number is getting set properly at that point.

Categories

Resources