I am trying to configure a simple form . I have 3 editexts and after a user ends input, i want to show up checked icon if it's valid (and goes to the next field) and error if not and the user can correct.
My main issue is I can only input 1 character and then it shows me or error or checked icon and it goes to the next field.
What do I do wrong?
Here is my code:
public class ConTct extends Activity implements OnClickListener, OnTouchListener{
Button mButton;
EditText mFullName, mEmail, mDialZone, mPhone;
static WebView mWebView;
static ProgressBar mProgressBar;
EditText mBrokerId, mIP, mAreaPhonePrefix, mLastName, mPassWord, mCampaign, mSubCampaign, mCountryID, mCity, mAdress, mIsDemo;
private String inputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.contct);
registerViews();
}//oncreate()
private void registerViews(){
mFullName = (EditText) findViewById(R.id.firstName);
mFullName.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus){
//do nothing
}else{
if(!Validation.hasText(mFullName)){
mFullName.setError("You have to input at least 3 characters");
mFullName.requestFocus();
}else{
mFullName.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
mFullName.clearFocus();
mEmail.requestFocus();
}
}
}
});
mEmail = (EditText) findViewById(R.id.email);
mEmail.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus){
//do nothing
}else{
if(!Validation.isEmailAddress(mEmail, true)){
mEmail.setError("wrong email");
mEmail.requestFocus();
}else{
mEmail.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
mEmail.clearFocus();
mPhone.requestFocus();
}
}
}
});
mPhone = (EditText) findViewById(R.id.phoneNumber);
mPhone.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if(hasFocus){
//do nothing
}else{
if(!Validation.isPhoneNumber(mPhone, true)){
mPhone.setError("wrong email");
mPhone.requestFocus();
}else{
mPhone.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.llgr, 0);
mPhone.clearFocus();
}
}
}
});
mButton = (Button) findViewById(R.id.SubmitRegisterButton);
mButton.setOnClickListener(this);
}
private void submitForm() {
// Submit your form here. your form is valid
Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
}
private boolean checkValidation() {
boolean ret = true;
if (!Validation.hasText(mFullName)){
ret = false;
}
if (!Validation.isEmailAddress(mEmail, true)){
ret = false;
}
if (!Validation.isPhoneNumber(mPhone, true)){
ret = false;
}
if (!Validation.hasText(mPhone)){
ret = false;
}
return ret;
}//checkValidation
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if ( checkValidation () ){
submitForm();
Intent i = new Intent(getApplicationContext(), ThanksZuser.class);
startActivity(i);
finish();
//send to our crm
grabURL(myURL);
}else
Toast.makeText(ConTct.this, "Form contains error", Toast.LENGTH_LONG).show();
}
}//ConTct.class
Validation class:
package com.Signals4Trading.push.android;
import java.util.regex.Pattern;
import android.widget.EditText;
public class Validation {
// Regular Expression
// you can change the expression based on your need
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
// private static final String PHONE_REGEX = "\\d{3}-\\d{7}";
// private static final String PHONE_REGEX = "(\\d{3})-(\\d{3})-(\\d{4})";
private static final String PHONE_REGEX = "([0-9-( )]+)";
// Error Messages
private static final String REQUIRED_MSG = "Invalid name. You have to input at least 3 characters";
private static final String EMAIL_MSG = "Invalid email";
private static final String PHONE_MSG = "Invalid number";
// call this method when you need to check email validation
public static boolean isEmailAddress(EditText editText, boolean required) {
return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
}
// call this method when you need to check phone number validation
public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
/*
// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {
String text = editText.getText().toString().trim();
// clearing the error, if it was previously set by some other values
editText.setError(null);
// text required and editText is blank, so return false
if ( required && !hasText(editText) ) return false;
// pattern doesn't match so returning false
if (required && !Pattern.matches(regex, text)) {
editText.setError(errMsg);
return false;
};
if ( required && !hasNumber(editText)) return false;
return true;
}
*/
// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean bRequired) {
// text required and editText is blank, so return false
String sText = editText.getText().toString().trim();
// clearing the error, if it was previously set by some other values
editText.setError(null);
if (sText.length() == 0) {
if (bRequired) {
editText.setError("*Field required");
return false;
}
} else {
// filled field
// pattern doesn’t match so returning false
if (!Pattern.matches(regex, sText)) {
editText.setError(errMsg);
return false;
}
}
return true;
}
// check the input field has any text or not
// return true if it contains text otherwise false
public static boolean hasText(EditText editText) {
String text = editText.getText().toString().trim();
editText.setError(null);
// length less that 3 means there is no text
if (text.length() <= 3 && text.length() > 12) {
editText.setError(REQUIRED_MSG);
return false;
}
return true;
}
public static boolean hasNumber(EditText editText) {
String text = editText.getText().toString().trim();
editText.setError(null);
// length less that 6 and more than 11 means not available
if (text.length() <= 6 && text.length() >= 11) {
editText.setError(PHONE_MSG);
return false;
}
return true;
}
}//Validation
My main issue is I can only input 1 character and then it shows me or
error or checked icon and it goes to the next field.
Issue is:
You are calling the validation method in onTextChanged. So its going in hasText method, determines there is less than 3 characters, and shows error. In your case, its better to implement using OnFocusChangeListener
Example:
myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
//do nothing
}else {
// validate here and show error if invalid and set focus to this element again using requestFocus.
}
}
});
Hope this helps.
Related
I have two spinners, one with a list of countries(countrySpinner) and the other with a list of provinces(stateSpinner). I want the stateSpinner to be active only if Nigeria is selected on the countrySpinner, and for the other countries on to be selectable without selecting item on the stateSpinner. My code seam to work when I select Nigerian on the countrySpinner and a corresponding state, but I GET THIS NullPointerException : println needs a message, anytime I select a country other than Nigeria on the countrySpinner. Not quite sure of what to do to get pass here. I Would appreciate any help. My code below.enter code here
public class RegisterActivity extends AppCompatActivity {
Spinner countrySpinner, stateSpinner;
List<String> countryList;
ArrayList<String> stateList;
ArrayAdapter<String> stateAdapter;
String countrySelected, stateSelected, gender;
TextInputLayout name, email, password, confirmPw;
RadioGroup genderOptionGroup;
RadioButton genderOptionBtn;
TextView countryUnCheckedWarning;
Button nextButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);
countryUnCheckedWarning = findViewById(R.id.countrySelectW);
genderOptionGroup = findViewById(R.id.gender_group);
name = findViewById(R.id.fullNameInputLayout);
email = findViewById(R.id.emailInputLayout);
password = findViewById(R.id.pwInputLayout);
confirmPw = findViewById(R.id.cpwInputLayout);
countrySpinner = findViewById(R.id.countryDropDown);
stateSpinner = findViewById(R.id.stateDropDown);
stateList = new ArrayList<String>(Arrays.asList("Select State of Residence", "Abia", "Abuja", "Adamawa", "Akwa Ibom", "Anambra",
"Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Enugu", "Edo",
"Ekiti", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara",
"Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto",
"Taraba", "Yobe", "Zamfara", "Territory"));
stateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stateList);
stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stateSpinner.setAdapter(stateAdapter);
countryList = new ArrayList<String>();
countryList.add(0, "Select Country");
countryList.add("Gambia");
countryList.add("Sierra Leone");
countryList.add("Liberia");
countryList.add("Ghana");
countryList.add("Nigeria");
countryList.add("South Africa");
ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countryList);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countrySpinner.setAdapter(countryAdapter);
// Country Spinner
countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!(parent.getItemAtPosition(position).equals("Nigeria")) && !(parent.getItemAtPosition(position).equals("Select Country"))){
// Country other than Nigeria has been selected
countrySelected = parent.getItemAtPosition(position).toString();
Log.i("Country Selected is",countrySelected);
nextButton.setEnabled(true);
nextButton.setBackgroundColor(getResources().getColor(R.color.red));
}else if (parent.getItemAtPosition(position).equals("Nigeria")){
// Nigeria is selected
stateSpinner.setAlpha(1);
countrySelected = "Nigeria";
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
}else {
countrySelected = "";
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// State SpinnerGroup
stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getItemAtPosition(position).equals("Select State of Residence")) {
nextButton.setEnabled(false);
nextButton.setBackgroundColor(getResources().getColor(R.color.silverash));
} else {
stateSelected = parent.getItemAtPosition(position).toString();
nextButton.setEnabled(true);
nextButton.setBackgroundColor(getResources().getColor(R.color.red));
Log.i("State Selected", stateSelected);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
// Name, Email and Password Validation MTDs Below
private boolean validateName() {
String nameInpute = name.getEditText().getText().toString().trim();
// check for non empty field
if (nameInpute.isEmpty()) {
name.setError("Name Field Can't be empty");
return false;
} else if (nameInpute.length() < 5) {
name.setError("Name is too short");
return false;
} else {
name.setError(null);
return true;
}
}
private boolean validateEmail() {
String emailInpute = email.getEditText().getText().toString().trim();
// Now we check for non empty field
if (emailInpute.isEmpty()) {
email.setError("E-mail Field Can't be empty");
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(emailInpute).matches()) {
email.setError("Please enter a valid email address");
return false;
} else {
// Remove Error and return true
email.setError(null);
return true;
}
}
private boolean validatePassword() {
String passwordInpute = password.getEditText().getText().toString().trim();
// check for non empty field
if (passwordInpute.isEmpty()) {
password.setError("Password Field Can't be empty");
return false;
} else if (passwordInpute.length() > 15) {
password.setError("Password is too long");
return false;
} else {
password.setError(null);
return true;
}
}
private boolean validateCPassword() {
String passwordInpute = password.getEditText().getText().toString().trim();
String confirmPWInpute = confirmPw.getEditText().getText().toString().trim();
// check for non empty field
if (confirmPWInpute.isEmpty()) {
confirmPw.setError("Password Field Can't be empty");
return false;
} else if (!confirmPWInpute.equals(passwordInpute)) {
confirmPw.setError("Password does not match");
return false;
} else {
password.setError(null);
return true;
}
}
public void moveToNextOnReg(View view) {
// check for or validations
if (!validateName() | !validateEmail() | !validatePassword() | !validateCPassword()) {
return; }
// put whatever result needed here
String fullName = name.getEditText().getText().toString().trim();
String emailRegistered = email.getEditText().getText().toString().trim();
String passwordRegistered = password.getEditText().getText().toString().trim();
Log.i("Name", fullName);
Log.i("E-mail", emailRegistered);
Log.i("Password", passwordRegistered);
Log.i("Country", countrySelected);
Log.i("State", stateSelected);
Log.i("Sex", gender);
Intent intentNext = new Intent(getApplicationContext(),ToNextActivity.class);
startActivity(intentNext);
}
public void backToOnboarding(View view) {
Intent intent = new Intent(getApplicationContext(), OnboardingActivity.class);
startActivity(intent);
finish();
}
public void onGenderSelected(View view){
int radioId = genderOptionGroup.getCheckedRadioButtonId();
genderOptionBtn = findViewById(radioId);
gender = genderOptionBtn.getText().toString();
Log.i("Gender Selceted", genderOptionBtn.getText().toString());
}
}
You don't seem to initialize nextButton in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);nextButton = findViewById(R.id.createAccNext);
countryUnCheckedWarning = findViewById(R.id.countrySelectW);
genderOptionGroup = findViewById(R.id.gender_group);
name = findViewById(R.id.fullNameInputLayout);
email = findViewById(R.id.emailInputLayout);
password = findViewById(R.id.pwInputLayout);
confirmPw = findViewById(R.id.cpwInputLayout);
countrySpinner = findViewById(R.id.countryDropDown);
stateSpinner = findViewById(R.id.stateDropDown);
//here.....
nextButton = findViewById(...............);//what ever the id is in xml
I'm new to Android and Java and I'm busy editing an existing app. I am trying to hide a button if no text is getting pulled in from a webservice. I have made it work with another button when the text is being populated
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
but when I used:
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
nothing seems to happen.
I don't know if the code snippet is in the wrong place or something else is overwriting the code. Here is my activity code:
package com.example.dsouchon.myapplication;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
if(Local.isSet(getApplicationContext(), "LoggedIn"))
{
String loggedInUser = Local.Get(getApplicationContext(), "LoggedIn");
if(loggedInUser.length()>0)
{
buttonEventSetup.setVisibility(View.VISIBLE);
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
if(Local.isSet(getApplicationContext(), "EventName"))
{
String event = Local.Get(getApplicationContext(), "EventName");
TextView textEvent = (TextView) findViewById(R.id.textEventName);
textEvent.setText( event);
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(true);
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
}
else
{
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(false);
}
if(Local.isSet(getApplicationContext(), "EventImage"))
{
TextView textEvent = (TextView) findViewById(R.id.textEventName);
String result = Local.Get(getApplicationContext(), "EventImage");
ImageView imageViewEventImage = (ImageView)findViewById(R.id.imageViewEventImage);
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageViewEventImage.setImageBitmap(decodedByte);
}
}
#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_main2, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setupEvent(View view) {
Intent intent = new Intent(MainActivity.this, SetupEvent.class );
finish();
startActivity(intent);
}
public void accessControl(View view) {
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.GONE);
Intent intent = new Intent(MainActivity.this, MainActivity21.class );
finish();
startActivity(intent);
}
public void Logoff(View view) {
Local.Set(getApplicationContext(), "LoggedIn", "");
}
public void Login(View view) {
final AlertDialog ad=new AlertDialog.Builder(this).create();
MySOAPCallActivity cs = new MySOAPCallActivity();
try {
EditText userName = (EditText) findViewById(R.id.editUserName);
EditText password = (EditText) findViewById(R.id.editPassword);
String user = userName.getText().toString();
String pwd = password.getText().toString();
LoginParams params = new LoginParams(cs, user, pwd);
Local.Set(getApplicationContext(), "UserName", user);
Local.Set(getApplicationContext(), "Password", pwd);
new CallSoapLogin().execute(params);
// new CallSoapGetCurrentEvents().execute(params);
} catch (Exception ex) {
ad.setTitle("Error!");
ad.setMessage(ex.toString());
}
ad.show();
}
public class CallSoapLogin extends AsyncTask<LoginParams, Void, String> {
private Exception exception;
#Override
protected String doInBackground(LoginParams... params) {
return params[0].foo.Login(params[0].username, params[0].password);
}
protected void onPostExecute(String result) {
// TODO: check this.exception
// TODO: do something with the feed
try {
TextView loginResult =(TextView)findViewById(R.id.labelLoginResult);
loginResult.setVisibility(View.VISIBLE);
loginResult.setText(result);
// Button buttonUnsetEvent = (Button)findViewById(R.id.buttonUnsetEvent);
// buttonUnsetEvent.setEnabled(true);
//Spinner spinner2 = (Spinner)findViewById(R.id.spinner2);
//spinner2.setEnabled(true);
boolean LoginSuccessful = false;
if(result.toLowerCase().contains("success"))
{
LoginSuccessful = true;
}
if (LoginSuccessful)
{
String user = Local.Get(getApplicationContext(), "UserName");
Local.Set(getApplicationContext(), "LoggedIn", user);
LinearLayout layoutLoggedIn = (LinearLayout)findViewById(R.id.layoutLoggedIn);
layoutLoggedIn.setVisibility(View.VISIBLE);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.VISIBLE);
LinearLayout layoutLogIn = (LinearLayout)findViewById(R.id.layoutLogIn);
layoutLogIn.setVisibility(View.VISIBLE);
}
} catch (Exception ex) {
String e3 = ex.toString();
}
}
}
private static class LoginParams {
MySOAPCallActivity foo;
String username;
String password;
LoginParams(MySOAPCallActivity foo, String username, String password) {
this.foo = foo;
this.username = username;
this.password = password;
}
}
}
You are getting the length of Textview that will not work.Use the text length.This should work
String event = Local.Get(getApplicationContext(), "EventName");
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (event.length() > 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (event.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
In your code above textEvent is not a string value. It is an Object of type TextView. length() in this case will not return the length of the text contained within that element. You will need to explicitly get the text string before you can get the length of it. This is acquired using the getText() method on the TextView.
Your code should look like the following:
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.getText().length() >= 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (textEvent.getText().length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
You also have INVISIBLE on both cases in your posted code example.
Note that your code also does not handle cases where the text length == 1. You could simplify the whole block with the following.
Note: any value != 0 is classed as true
buttonEventSetup.setVisibility(textEvent.getText().length() ? View.VISIBLE : View.INVISIBLE);
I have problems with android programming in java, because it does not want to read from a text file. The problem is that the buttons do not add the text which I am trying to do in the async-class. Furthermore, the buttons which will show the text does not work, because when I press on a button the application stops working.
Short introduction of the program:
The application starts with a value sent to gameAction from a spinner, and from there it wil invoke a name on text-file which will be loaded into strings in an array-list, the class QuestionBox. Lastly it will questions will be made in GameAction class.
If something was unclear, please comment. And any help is appreciated! Excuse me for adding a lot of code, but I added it due to not knowing how to do.
public class QuestionBox extends AsyncTask<Object, Void, Object>{
private Context context;
private Callback callback;
private List<Question> mQuestions;
public QuestionBox(Context context,Callback callback)
{
mQuestions = new ArrayList<Question>();
this.callback=callback;
this.context= context;
}
public Callback getCallback(){
return callback;
}
#Override
protected Object doInBackground(Object... params) {
InputStream iS = null;
try {
iS = context.getAssets().open("hogskoleprovet.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Hit kom du");
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
String question, answer, answerOne, answerTwo, answerThree, answerFour;
try {
while (reader.readLine() != null) {
//reading some lines from resource file
question = reader.readLine();
answer = reader.readLine();
answerOne = reader.readLine();
answerTwo = reader.readLine();
answerThree = reader.readLine();
answerFour = reader.readLine();
Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
mQuestions.add(q);
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
System.out.println("Hit kom du3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public interface Callback{
public void notify_result(List<Question> question_list);
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
public int getQuestionsLeft() {
return mQuestions.size();
}
public Question getRandomQuestion() {
Random random = new Random();
int index = random.nextInt(mQuestions.size());
Question newQuestion = mQuestions.get(index);
mQuestions.remove(index);
return newQuestion;
}
}
Here is another method which the strings will be sent to:
public class gameAction extends ActionBarActivity implements QuestionBox.Callback{
private QuestionBox mQuestionBox;
private Question mCurrentQuestion;
private Context context;
private Callback callback;
#Override
public void notify_result(List<Question> question_list) {
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_action);
//Kod som kollar vad som skickades med när aktiviteten startades
Intent callingIntent = getIntent();
int index = callingIntent.getIntExtra("INDEX",0);
//Bestäm filnamn beroende på vad som skickades med
if(index==0){
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
else {
if (index == 1 ) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 1) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 2) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
}
}
public void setNewQuestion()
{
//Hämta en slumpmässig fråga från vår QuestionBox
//och lagra den i mCurrentQuestion
mCurrentQuestion = mQuestionBox.getRandomQuestion();
//Se till så att textfält och knappar visar den aktuella
//frågan
TextView questionTextView = (TextView) findViewById(R.id.questionTextView);
questionTextView.setText(mCurrentQuestion.getQuestion());
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(true);
buttonTwo.setEnabled(true);
buttonThree.setEnabled(true);
buttonFour.setEnabled(true);
buttonNew.setVisibility(View.INVISIBLE);
buttonOne.setText(mCurrentQuestion.getOptionOne());
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
buttonThree.setText(mCurrentQuestion.getOptionThree());
buttonFour.setText(mCurrentQuestion.getOptionFour());
}
public void quitTheGame(View v){
Intent intent = new Intent (this, MainActivity.class);
Button butttonQuit = (Button) findViewById(R.id.buttonFive);
startActivity(intent);
}
public void answerClick(View V)
{
Button answerButton = (Button)V;
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(false);
buttonTwo.setEnabled(false);
buttonThree.setEnabled(false);
buttonFour.setEnabled(false);
buttonNew.setVisibility(View.VISIBLE);
}
public void newClick(View v){
if(mQuestionBox.getQuestionsLeft()>0){
setNewQuestion();
}
else
{
Context context = getApplicationContext();
String text = "Slut på frågor!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
#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_main, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the class for putting answer to correct options:
package com.example.arnpet.ultimatehogskoleprovet;
public class Question {
private String question;//Lagrar frågan
private String optionOne; //Lagrar svarsalternativ
private String optionTwo;
private String optionThree;
private String optionFour;
private String correctAnswer; //Lagrar det korrekta svaret
//konstruktor
public Question (String question, String optionOne, String optionTwo,
String optionThree, String optionFour, String correctAnswer)
{
this.question = question;
this.optionOne = optionOne;
this.optionTwo = optionTwo;
this.optionThree = optionThree;
this.optionFour = optionFour;
}
public String getQuestion() {
return question;
}
public String getOptionOne() {
return optionOne;
}
public String getOptionTwo() {
return optionTwo;
}
public String getOptionThree() {
return optionThree;
}
public String getOptionFour() {
return optionFour;
}
}
while (reader.readLine() != null)
Here you are reading a line of the file and throwing it away. Not what you want, unless your file is strangely structured with ignorable junk lines every so often.
The usual loop looks like this:
while ((line = reader.readLine()) != null)
and then using line in the controlled block.
Secondly, this is the only place you check for null, yet you have several other readLine() calls, any one of which can return null. So you run some risk of NPEs later in your code.
hey how can i know that the below checkbox when clicked is from which row of the list.
is there any way of knowing that. Every time yo is returning false which is its default value.
checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
callBlockOptions callBlockOptions = (callBlockOptions) cb.getTag();
callBlockOptions.setChecked( cb.isChecked() );
String yo;
if(callBlockOptions.getPosition()=="0")
{
callBlockOptions.setAllCalls();
}
if(callBlockOptions.getAllCalls() ==true)
yo="true";
else
yo="false";
Toast.makeText(getContext(), callBlockOptions.getPosition(), Toast.LENGTH_LONG).show();
}
});
}
After seeing your code, one thing you might want to try is setting listeners for the individual children within the ListView. You could do something like this:
ListView listView = (ListView)findViewById(R.id.listView);
int count = listView.getChildCount();
for (int x = 0; x < count; x++)
{
Class<? extends View> c = listView.getChildAt(x).getClass();
if (c == CheckBox.class)
{
CheckBox checkBox = (CheckBox)(listView.getChildAt(x));
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoutButton, boolean isChecked) {
// TODO Auto-generated method stub
callBlockOptions.isChecked = isChecked;
}
});
}
else if (c == TextView.class)
{
TextView textView = (TextView)(listView.getChildAt(x));
textView.setOnEditorActionListener(new OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView tView, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
callBlockOptions.name = tView.getText().toString();
return true;
}
});
}
You probably want your other class to be like this:
public class callBlockOptions {
public static String name;
public static Boolean isChecked;
}
Then you can get and set name and isChecked like this:
callBlockOptions.isChecked = false;
Boolean boolVal = callBlockOptions.isChecked;
I want to validation on RatingBar in Android. I have 5 rating Bar and 1 Button. I don't want to submit the data without pressed the rating bar. I want to take validation on Rating bar.
Can someone help me. How to take validation on Rating bar?
Here is my Activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rating_baar);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
addListenerOnRatingBar_one();
addListenerOnRatingBar_two();
addListenerOnRatingBar_three();
addListenerOnRatingBar_four();
addListenerOnRatingBar_five();
addListenerOnButton();
}
#SuppressLint("SimpleDateFormat")
public void addListenerOnButton() {
buttonSubmitRate = (Button) findViewById(R.id.button_SubmitRate);
buttonSubmitRate.setOnClickListener(new OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
if((etTaskName.getText().toString().isEmpty()))
etTaskName.setError("Field Can Not Be Empty !");
else if (!etTaskName.getText().toString().trim().matches("[a-zA-Z{ }]+"))
etTaskName.setError("Accept Alphabets Only.");
else {
strEmpName = textViewNAme.getText().toString().trim();
strTaskName = etTaskName.getText().toString().trim();
String strCurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println("strCurrentDate = " + strCurrentDate);
String strCurrentMonth = new SimpleDateFormat("MMM").format(new Date());
System.out.println("strCurrentDate = " + strCurrentMonth);
String strCurrenYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("strCurrenYear = " + strCurrenYear);
System.out.println("__________________________________________________________________________________");
databaseHelper.insertPerformance_Details(intentStr1, strEmpName,
strTaskName, rateVal_one,
rateVal_two, rateVal_three,
rateVal_four,rateVal_five,
strCurrentDate,strCurrentMonth,
strCurrenYear);
System.out.println("Data Add SuccesFully !!!!");
etTaskName.setText("");
Intent i = new Intent(RatingBaar_Class.this, Rating_Msg.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
}
}
});
}
public void addListenerOnRatingBar_one() {
ratingBar_one = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar_one.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rateVal_one = String.valueOf(rating);
System.out.println(" rateVal_one = " + rateVal_one);
}
});
}
/* Exactly the same methods for four other rating bars, except for variable names */
public void addListenerOnRatingBar_two() { ... }
public void addListenerOnRatingBar_three() { ... }
public void addListenerOnRatingBar_four() { ... }
public void addListenerOnRatingBar_five() { ... }
At first set all rating bar to 0 value. Then on click to button, check if the value has altered in all of them. If so, only valid else invalid.
Also you can use listener to each rating bar and change value of some boolean variable to true
Example:
boolean flag1 = false;
boolean flag2 = false;
.... //similarly upto 5
Then in rating bar listener1
{
flag1 = true;
}
Similarly for all set flag to be true
And in button onClickListener do the following:
if(flag1 && flag2 && flag3 && flag4 && flag5){
//do your work
}else{
//display message that one of the rating bar hasn't been touched
}