How to validate to rating bar on Button click in Android? - java

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
}

Related

NullPointerException when I select Items on Spinner

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

Change button background color based on previous color

I have a very simple problem
consider I'm retrieving a string value online using getText() Method
Now depending upon value of string I have set my button background to red and blue.
If string value is red then button background is red and if it is blue then blue.
Now if I implement onClicklistener to same button I would like to changes it's Background color. If it was Red then change it to blue and if it was blue then change it to red as long as user presses key.
mSolved = (Button) itemView.findViewById(R.id.book_solved);
mSolved.setText(g.getColorvalue());
if("Blue".equals(holder.mSolved.getText())){
mSolved.setBackgroundColor(BLUE);
}
if("Red".equals(holder.mSolved.getText())){
.mSolved.setBackgroundColor(RED);
}
mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Background color is already BLue)
{
change to Red
}
else
{
Change to Blue
}
}
Try using FLAG variables. Something similar to this.
mSolved = (Button) itemView.findViewById(R.id.book_solved);
mSolved.setText(g.getColorvalue());
boolean IS_BLUE = false;
boolean IS_RED = false;
if("Blue".equals(holder.mSolved.getText())){
mSolved.setBackgroundColor(BLUE);
IS_BLUE = true;
}
if("Red".equals(holder.mSolved.getText())){
mSolved.setBackgroundColor(RED);
IS_RED = true;
}
mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(IS_BLUE)
{
mSolved.setBackgroundColor(RED);
IS_RED = true;
IS_BLUE = false;
}
else if(IS_RED)
{
mSolved.setBackgroundColor(BLUE);
IS_BLUE = true;
IS_RED = false;
}
}
Try this code:
mSolved = (Button) findViewById(R.id.book_solved);
mSolved.setBackgroundColor(Color.parseColor("#009900"));
mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View tView) {
ColorDrawable buttonColor = (ColorDrawable) mSolved.getBackground();
int colorId = buttonColor.getColor();
// Log.i("INFO", "find color value for new color " + colorId);
if (colorId == -3407872) { // color is read
mSolved.setBackgroundColor(Color.parseColor("#009900"));
}
else {
mSolved.setBackgroundColor(Color.parseColor("#cc0000"));
}
}
});

Android Broadcast Receiver as inner static class Passing a String

Probably you want to jump to Update 2 and check the code if needed
I am building a barcode scanner and having difficulty in passing data that I have captured from an inner class that extends BroadcastReceiver to MainActivity class, I do understand the difference between static and non static objects, but I got stuck.
Cant invoke my logic method from the inner class.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState){...}
public void Logic(String result){// Do something...}
//Inner Class
public static class ScanResultReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {...
// data here captured fine!
// Here I want to send my data to MainActivity Logic(result)
Logic(result);
}
}
If I make "Logic()" as Static method, I get a lot of errors regards to calling non static from static method from Toaster/variables..etc
Update
This method is inside MainActivity, I do want to call it from the inner class
public void Logic(String result) throws Exception {
//prepare the results
if (mDecodeResult.decodeValue.substring(0, 1).equals("{") && mDecodeResult.decodeValue.substring(mDecodeResult.decodeValue.length() - 1).equals("}")) {
if (!(mDecodeResult.decodeValue.equals("SCAN AGAIN"))) {
mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(1);
mDecodeResult.decodeValue = mDecodeResult.decodeValue.substring(0, mDecodeResult.decodeValue.length() - 1);
}
}
if (mDecodeResult.decodeValue.equals("SCAN AGAIN")) {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received! Please Scan Again", Toast.LENGTH_SHORT);
toast.show();
} else if (mDecodeResult.decodeValue != null && tourFlag) {
String formattedDate = getTime();
String scanContent = mDecodeResult.decodeValue;
boolean found = false;
if (ForcedOrRandom.equals("Random")) {
String[] b;
for (String l : ToBeScanned) {
b = l.split(":");
if (scanContent.equals(b[0])) {
Log.d("remove", "scanned: " + scanContent);
Log.d("remove", "remove : " + b[0]);
found = true;
}
}
} else if (ForcedOrRandom.equals("Forced")) {
String[] b;
for (String I : FTobeScannedNext) {
b = I.split(":");
if (scanContent.equals(b[0])) {
Log.d("remove", "scanned: " + scanContent);
Log.d("remove", "remove : " + b[0]);
found = true;
}
}
}// end Skip/Forced
if (listLoaded && found) {
theResult[resultCount].setTourID(currentTourId);
theResult[resultCount].setBarcode(scanContent);
BarcodeObject a = getBarcodeInfo(scanContent);
if (ForcedOrRandom.equals("Random")) {
} else {
if (myTimer != null) {
myTimer.cancel();
Timer = (TextView) findViewById(R.id.timertext);
Timer.setText("");
PlayOrPause.setVisibility(View.INVISIBLE);
}
boolean isTimed = a.getForceNextBarCode().equals("");
if (!(isTimed)) {
PlayOrPause = (ImageButton) findViewById(R.id.PlayPause);
PlayOrPause.setVisibility(View.VISIBLE);
PlayOrPause.setImageResource(R.drawable.pause);
final AlertDialog.Builder timealert = new AlertDialog.Builder(this);
PlayOrPause.setEnabled(true);
long duration = Integer.parseInt(a.getForceNextBarCode());
duration = duration * 60000;
myTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisuntilFinished) {
int seconds = (int) (millisuntilFinished / 1000) % 60;
int minutes = (int) ((millisuntilFinished / (1000 * 60)) % 60);
Timer = (TextView) findViewById(R.id.timertext);
Timer.setText(minutes + ":" + seconds);
timeLeft = millisuntilFinished;
}
String value = "";
#Override
public void onFinish() {
Timer = (TextView) findViewById(R.id.timertext);
theResult[resultCount].setScanstatus(scanStatusTimeElapsed);
timealert.setTitle("Site Secure");
timealert.setMessage("Time Elapsed! Enter reason");
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity.this);
timealert.setView(input);
timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString();
// Do something with value!
while (value.equals("")) {
timealert.setView(input);
timealert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText().toString();
}
});
}
theResult[resultCount].setComments(value);
}
});
timealert.setIcon(android.R.drawable.ic_dialog_alert);
timealert.show();
Timer.setText(R.string.Time_Elapsed);
}
};
myTimer.start();
}
}
theResult[resultCount].setBarcodeID(a.getBarCodeId());
theResult[resultCount].setDateScanned(formattedDate);
theResult[resultCount].setSkipped(getResources().getString(R.string.Scanned));
}// end big if listLoaded && found
contentTxt.setText(scanContent);
Toaster(getResources().getString(R.string.TScan_Complete));
if (mainScanCounter == 0) {
if (tourDecider(scanContent)) {//tour decider is called to determine if this is boolJanamScanner random or forced tour
tourId = scanContent;
if (!(readFileOffline(siteSecurePath + "/doneTourNumber.txt").equals(""))) {
SYNC.setEnabled(true);
}
}
} else if (mainScanCounter > 0) {
if (ForcedOrRandom.equals("Random")) {
ListManager(scanContent);
} else {
ForcedListManager(scanContent);
}
}
} else if (mDecodeResult.decodeValue != null && officerScanFlag) {
TextView officertextview = (TextView) findViewById(R.id.officerid);
UserObject theofficer = getUserInfo(mDecodeResult.decodeValue);
if (theofficer == null) {
popUps("Error", "Invalid Officer ID, Please Rescan", "TITLE");
officerScan.setEnabled(true);
} else if (theofficer != null) {
// officer ID found need to store it for backup
officerId = theofficer.getOfficerid();
makeFileOffline(officerId, "officerID");
officertextview.setText(theofficer.getUsername());
officerScanFlag = false;
startTimersOfficerID = getTime();
tourBtn.setEnabled(true);
}
}
if (mDecodeResult.decodeValue != null && exceptionFlag) {
Log.d("check", "exception was clicked");
String ex_result = mDecodeResult.decodeValue;
for (int i = 0; i < theExceptions.length; i++) {
if (!(theExceptions[i].getBarcode().equals(ex_result))) {
String refnum = theExceptions[i].getRefNum();
i = theExceptions.length;
theResult[resultCount - 1].setException(refnum);
}
}
exceptionFlag = false;
Toaster(getResources().getString(R.string.TScan_Complete));
}
} // Logic Ends
Update 2
Not sure if I need to have another thread for this but I will put what I have found, my issue have narrowed to the following:
I am waiting on an intent called
<action android:name="device.scanner.USERMSG" />
with a permission
android:permission="com.permission.SCANNER_RESULT_RECEIVER"
now my issue
if a user tap button and released in less than .5 second onKeyup() event will be fired before my onReceive() that is inside the static class which is extends BroadcastReceiver, and that causes problem because Logic() will be invoked before updating the String inside onReceive()
if user hold the button long enough, onReceive will be invoked and everything is good and happy.
How can I make sure that onReceive() always invoked first?
public boolean onKeyUp(int keycode, KeyEvent event) {
if (keycode == 221 || keycode == 220 || keycode == 222) {
Logic(result);
}
return true;
}
Move this line of code:
public void Logic(String result){// Do something...}
inside your class ScanResultReceiver and it will work for sure. Your code should look like this:
public static class ScanResultReceiver extends BroadcastReceiver {
public ScanResultReceiver() {
//empty constructor
}
#Override
public void onReceive(Context context, Intent intent) {...
// data here captured fine!
// Here I want to send my data to MainActivity Logic(result)
Logic(result);
}
public void Logic(String result){/* ... */}
}

hide button if text length is < 1 in android studio

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);

Method of one class not getting called from another class

I have written a class inside one activity to display a hh:mm:ss timer in my activity:
This is code of the class designed to show the timer:
//class to display on screen timer
class ShowTimer
{
long mMilliseconds = 120000;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
CountDownTimer mCountDownTimer = new CountDownTimer(mMilliseconds, 1000) {
#Override
public void onFinish() {
mTextView.setText(mSimpleDateFormat.format(0));
}
public void onTick(long millisUntilFinished) {
mTextView.setText(mSimpleDateFormat.format(millisUntilFinished));
}
};
}
This is how I am trying to access the class:
mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
mTextView = (TextView) findViewById(R.id.timer_textView);
mCountDownTimer.start();
I am getting an error like this:
mCountDownTimer cannot be resolved
The full activity is here:
public class SpeedTestExamActivity extends Activity {
String xmlContent=null;
String duration=null;
//strings for use
String answer_str, option1_str,option2_str,option3_str,option4_str;
//text views for quiz layout
TextView question_view;
TextView question_sr_no;
RadioButton option1;
RadioButton option2;
RadioButton option3;
RadioButton option4;
int counter=0;
int loop_checker=0;
int i;
//buttons on UI
Button prevQuestion;
Button nextQuestion;
Button resetQuestion;
Button endTest;
// XML node keys
static final String KEY_LIST = "List"; // parent node
static final String KEY_SR_NO = "SRNo";
static final String KEY_EXAM_SET_ID="ExamSetId";
static final String KEY_Q_ID="QId";
static final String KEY_QT_ID="QTId";
static final String KEY_QUESTION = "Question";
static final String KEY_MARKS = "Marks";
static final String KEY_NEGATIVE_MARKS = "NegativeMark";
static final String KEY_ATTEMPTED_TIME = "AttemtedTime";
static final String KEY_IDLE_TIME = "IdleTime";
static final String KEY_ELAPSED_TIME = "ElapsedTime";
static final String KEY_LAST_Q_INDEX = "LastQIndex";
static final String KEY_SUBJECT_NAME = "SubjectName";
static final String KEY_OPTION1 = "Option1";
static final String KEY_OPTION2 = "Option2";
static final String KEY_OPTION3 = "Option3";
static final String KEY_OPTION4 = "Option4";
static final String KEY_CORRECT = "Correct";
//variables to run the timer
int test_duration;
//object of the handler class
Handler handler;
//textview for timer
TextView mTextView;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_test_exam);
//getting previously received content as xml
xmlContent=getFromPreference("SpeedTestContent");
//getting previously saved exam duration from preference
duration=getFromPreference("exam_duration");
//setting time for timer to finish activity after test duration is over
test_duration=Integer.parseInt(duration.toString())*60000;
//makeAToast("Test duration is ms: "+test_duration);
mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
mTextView = (TextView) findViewById(R.id.timer_textView);
mCountDownTimer.start();
//starting timer
runTimer();
//assigning objects to layouts
question_view=(TextView)findViewById(R.id.question_textView);
question_sr_no=(TextView)findViewById(R.id.question_id_textView);
option1=(RadioButton)findViewById(R.id.option1_radioButton);
option2=(RadioButton)findViewById(R.id.option2_radioButton);
option3=(RadioButton)findViewById(R.id.option3_radioButton);
option4=(RadioButton)findViewById(R.id.option4_radioButton);
//calling function to populate ui
populating_textview(counter);
//onclick opt 1
option1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option1_str=option1.getText().toString();
if (answer_str.equalsIgnoreCase(option1_str))
{
//makeAToast("Correct!");
//calling function to populate ui with next question
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 2
option2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option2_str=option2.getText().toString();
String answer=answer_str;
if (answer.equalsIgnoreCase(option2_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 3
option3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option3_str=option3.getText().toString();
String answer1=answer_str;
if (answer1.equalsIgnoreCase(option3_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 4
option4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option4_str=option4.getText().toString();
String answer2=answer_str;
if (answer2.equalsIgnoreCase(option4_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick next button
nextQuestion = (Button) findViewById(R.id.next_question_button);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
counter++;
if (counter<=loop_checker)
{
populating_textview(counter);
}
else
{
makeAToast("Game Over!");
}
}
});
//onclick previous button
prevQuestion = (Button) findViewById(R.id.previous_question_button);
prevQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(counter!=0)
{
counter--;
}
if (counter<loop_checker)
{
populating_textview(counter);
}
if(counter==loop_checker)
{
counter--;
populating_textview(counter);
}
if(counter==0)
{
makeAToast("No more questions!");
}
}
});
//onclick reset button
resetQuestion = (Button) findViewById(R.id.reset_question_button);
resetQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
}
});
//onclick end test button
endTest = (Button) findViewById(R.id.end_test_button);
endTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//deactivating timer before finishing activity
handler.removeCallbacksAndMessages(null);
finish();
Intent intent = new Intent(SpeedTestExamActivity.this, RateUsActivity.class);
SpeedTestExamActivity.this.startActivity(intent);
}
});
}
//deactivating back button
#Override
public void onBackPressed() {
}
//getting content from preferences
public String getFromPreference(String variable_name)
{
String get_content;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
get_content = preferences.getString(variable_name,"");
return get_content;
// makeAToast(xmlContent);
}
// function to populate ui with question counter
void populating_textview(int count_questions)
{
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
//String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xmlContent); // getting DOM element
//count_questions=2;
NodeList nl = doc.getElementsByTagName(KEY_LIST);
// looping through all item nodes <item>
for ( i = 0; i < nl.getLength();i++) {
loop_checker=i;
// while(counter< nl.getLength())
// {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(count_questions);
// adding each child node to HashMap key => value
map.put(KEY_LIST, parser.getValue(e, KEY_LIST));
map.put(KEY_SR_NO, parser.getValue(e, KEY_SR_NO));
question_sr_no.setText(parser.getValue(e, KEY_SR_NO)+".");
map.put(KEY_QUESTION, parser.getValue(e, KEY_QUESTION));
question_view.setText(parser.getValue(e, KEY_QUESTION));
map.put(KEY_OPTION1, parser.getValue(e, KEY_OPTION1));
//option1_str =parser.getValue(e, KEY_OPTION1);
option1.setText(parser.getValue(e, KEY_OPTION1));
map.put(KEY_OPTION2, parser.getValue(e, KEY_OPTION2));
option2.setText(parser.getValue(e, KEY_OPTION2));
//option2_str =parser.getValue(e, KEY_OPTION2);
map.put(KEY_OPTION3, parser.getValue(e, KEY_OPTION3));
option3.setText(parser.getValue(e, KEY_OPTION3));
//option3_str =parser.getValue(e, KEY_OPTION3);
map.put(KEY_OPTION4, parser.getValue(e, KEY_OPTION4));
option4.setText(parser.getValue(e, KEY_OPTION4));
//option4_str =parser.getValue(e, KEY_OPTION4);
map.put(KEY_CORRECT, parser.getValue(e, KEY_CORRECT));
// makeAToast(parser.getValue(e, KEY_ANSWER));
answer_str =parser.getValue(e, KEY_CORRECT);
// adding HashList to ArrayList
menuItems.add(map);
}
}
//method to run timer
public void runTimer()
{
handler = new Handler();
// run a thread after a particular time seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
makeAToast("Your time is up!");
Intent intent = new Intent(SpeedTestExamActivity.this, RateUsActivity.class);
finish();
SpeedTestExamActivity.this.startActivity(intent);
}
}, test_duration); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
//method to show toast
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
//class to display on screen timer
class ShowTimer
{
long mMilliseconds = 120000;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
CountDownTimer mCountDownTimer = new CountDownTimer(mMilliseconds, 1000) {
#Override
public void onFinish() {
mTextView.setText(mSimpleDateFormat.format(0));
}
public void onTick(long millisUntilFinished) {
mTextView.setText(mSimpleDateFormat.format(millisUntilFinished));
}
};
}
}
The problem is that, I already have the time in ms, I cannot use any hard coded values.
I had followed the tutorial in here.
Where am I going wrong? What should I do to implement the timer?
Thanks in advance
Try this:
ShowTimer showTimer = new ShowTimer();
showTimer.mCountDownTimer.start();
Or better use an accessor in ShowTimer:
showTimer.getCountDownTimer().start();
The getCountDownTimer returns mCountDownTimer:
public CountDownTimer getCountDownTimer() {
return mCountDownTimer;
}
You have mCountDownTimer declared in the inner class rather than the main class. If you move it up into your SpeedTestExamActivity class you'll be able to access it.
mCountDownTime is an instance field so therefore you need an instance of ShowTimer on which to access the field.

Categories

Resources