Check all TextViews in an Activity - android

I was wondering if it is possible to run a check against all the TextViews in an Activity/View and make ones which don't have any content in them invisible? I don't really want to wrap a if statement around each of the TextViews when setting text.
I currently have an activity that will populate a range of TextViews with content from a Database. However there is a chance that some fields in the database will not have any content and to keep a clean UI I want to simply make these fields invisible instead of them just sitting blank.
Here is where I am setting the content:
public void settingContent() {
eventTitle.setText(event.EventTitle);
eventLocation.setText(event.SiteName);
organiser.setText(event.Organiser);
eventType.setText(event.setEventTitle());
DateFormatter dateFormatter = new DateFormatter();
String startDate = dateFormatter.getFormattedDate(event.StartDateTime);
String endDate = dateFormatter.getFormattedDate(event.CloseDateTime);
String eventDates = startDate + " - " + endDate;
dates.setText(eventDates);
cost.setText(event.FeeDetails);
bookingContact.setText(event.BookingContactName);
stewardContact.setText(event.StewardContactName);
unitTypes.setText(event.MaxUnits);
mapReference.setText(event.MapReference);
eventNumber.setText(event.EventNumber);
otherInformation.setText(event.OtherInformation);
directions.setText(event.SiteRouting);
if(event.isTempHoliday()) {
eventIcon.setImageResource(R.drawable.icon_holidaysites_card);
} else {
eventIcon.setImageResource(R.drawable.icon_clubmeets_card);
}
}
So is this possible or is it a case of just having to check each individual TextView before setting?

List<TextView> lstTexts = new ArrayList<TextView>();
lstTexts.add(cost);
lstTexts.add(bookingContact);
lstTexts.add(stewardContact);
lstTexts.add(unitTypes);
lstTexts.add(mapReference);
lstTexts.add(eventNumber);
lstTexts.add(otherInformation);
lstTexts.add(directions);
//then you can run this method
boolean empty = checkAllTV(lstTexts);
This is the method for it.
public boolean checkAllTV(List<TextView> allTV){
for(TextView tv : allTV){
if(tv.getText().toString().equals("")||tv.getText().toString()==null)
return false;
}
return true;
}
I am on Mobile so I am not able to check the code! but you can get the idea.
Hope it Helps.

Related

Trying to perform a text change in my textview at a reoccurring time on daily basis in my android project

let say i will like to automatically change my textview text at 02:00pm everyday how do I implement this functionality.
val df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
val systemDat = Calendar.getInstance(Locale.JAPAN).after(df)
if (systemDat) {
binding.includeTokyoSession.text_one.text = "successful"
} else {
binding.includeTokyoSession.text_one.text = "failure"
}
I suppose you want to change the text of your TextView after a particular time, but it seems that you're not aware of the date when comparing and you have a couple of mistakes in your code.
First, this line of code:
DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
will return a Date instance with this date and time in your local timezone 01-01-1970 02:00:00. However, you need to get a Date instance with today's date and the time 14:00:00.
Second, this line of code:
Calendar.getInstance(Locale.JAPAN).after(df)
this is a wrong usage of the Calendar::after() function, and that's because you can only pass a Calendar object to the function in order to get the right comparison result, otherwise it will always return false.
In your case you're passing a Date object.
Following is the implementation of the Calendar::after() function.
public boolean after(Object when) {
return when instanceof Calendar
&& compareTo((Calendar)when) > 0;
}
If you want to proper compare the current time today with 14:00 (comparing only the time today), here is a modification to your code:
val calendarToCompare = Calendar.getInstance(Locale.JAPAN).apply {
set(Calendar.HOUR_OF_DAY, 14)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val systemDat = Calendar.getInstance().after(calendarToCompare)
if (systemDat) {
textview.text = "successful"
} else {
textview.text = "failure"
}
If you want to perform a lifecycle-aware view update (ex. to set the text of your textview), you can check this gist.

change text color based on value of text

I am trying to figure out how to change the color of TextView based on the value of the text.
TextView has been sent from another activity I have that part working fine. What I want is a way to change the color of the text based on what is in the TextView. So if previous Activity sends a value like "11 Mbps" as TextView then I would like that text color to be yellow, "38 Mbps" green, and 1 Mbps red. I'm using eclipse if that helps at all.
This is how I'm sending the TextView to another activity. "showmsg" is just username sent to another page.
buttonBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
final TextView username =(TextView)findViewById(R.id.showmsg);
String uname = username.getText().toString();
final TextView wifistrength =(TextView)findViewById(R.id.Speed);
String data = wifistrength.getText().toString();
startActivity(new Intent(CheckWiFiActivity.this,DashboardActivity.class).putExtra("wifi",(CharSequence)data).putExtra("usr",(CharSequence)uname));
}
});
And this is how I receive it in the other activity
Intent i = getIntent();
if (i.getCharSequenceExtra("wifi") != null) {
final TextView setmsg2 = (TextView)findViewById(R.id.Speed);
setmsg2.setText(in.getCharSequenceExtra("wifi"));
}
This all works fine but I don't have a clue how to change the color of TextView based of the value of the text. Any help would be really appreciated.
You obviously want to set the color according to the number in the String you received from the previous Activity. So you need to parse it out of the String, save it to an int and then according to what the number is, set the color of your TextView.
String s = in.getCharSequenceExtra("wifi");
// the next line parses the number out of the string
int speed = Integer.parseInt(s.replaceAll("[\\D]", ""));
setmsg2.setText(s);
// set the thresholds to your liking
if (speed <= 1) {
setmsg2.setTextColor(Color.RED);
} else if (speed <= 11) {
setmsg2.setTextColor(Color.YELLOW);
else {
setmsg2.setTextColor(Color.GREEN);
}
Please notice that this is an untested code, it might contain some mistakes.
The way to parse it comes from here.
First, get all of the non-numeric characters out of your String and convert it to an integer. Then use a switch on the new value and set the color accordingly
String color = "blue"; // this could be null or any other value but I don't like initializing to null if I don't have to
int speed = i.getCharSequenceExtra("wifi").replaceAll("[^0-9]", ""); // remove all non-digits here
switch (speed)
{
case (11):
color = "yellow";
break;
case (38):
color = "green";
break;
case(1):
color = "red";
break;
}
setmsg2.setTextColor(Color.parseColor(color);
Here is a little site with some handy information
Color Docs

Android ArrayList TextView does't show text after setText

Hello I got some problems making an app and couldn't find the answer anywhere.
I have an EditText for user input. I have a String word and I have an ArrayList with TextViews in it.
I want to set the text of a TextView based on if the user input equals a character from the String. If a character is equal it must be shown in the right TextView.
The problem now is that if I put in a character that should match with a character from the word, it doesn't show me anything, even when I want to show the StringBuilder in another TextView it looks like it is empty.
I have this:
public void onClickButtons(View view) {
if(view==mBtnGuess) {
String getInput = mEtxtUserInput.getText().toString();
word = "someword";
if(getInput.length()==1) {
List<TextView> txtCharArr= new ArrayList<TextView>();
txtCharArr.add(mChar1);
txtCharArr.add(mChar2);
txtCharArr.add(mChar3);
txtCharArr.add(mChar4);
txtCharArr.add(mChar5);
txtCharArr.add(mChar6);
txtCharArr.add(mChar7);
txtCharArr.add(mChar8);
txtCharArr.add(mChar9);
txtCharArr.add(mChar10);
txtCharArr.add(mChar11);
txtCharArr.add(mChar12);
StringBuilder sb = new StringBuilder();
for(i=0;i<getInput.length();i++) {
if(getInput.equals(Character.toString(word.charAt(i)))) {
txtCharArr.get(i).setText(Character.toString(word.charAt(i)));
sb.append(Character.toString(word.charAt(i)));
}
}
}
}
}
I think instead of word.length() you are using getInput.length()
for(i=0;i<getInput.length();i++) {
if(getInput.equals(Character.toString(word.charAt(i)))) {
txtCharArr.get(i).setText(Character.toString(word.charAt(i)));
sb.append(Character.toString(word.charAt(i)));
}
}
Hence you will only loop once and check the getInput for only the first char of word, which is s.

setText() displaying address instead of a value in Android

I have just started to program in Android and I am still learning. I wanted to check if a year changes automatically when a nextMonth() method is used in case of December and January or whether I should change it with a few if statements. However, I canot display the value of that, instead I get an address. Here is my code:
TextView checkMonValue;
MonthDisplayHelper currentMonth = new MonthDisplayHelper(2012, 11);
MonthDisplayHelper nextMon = currentMonth;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkMonValue = (TextView)findViewById(R.id.monthValue);
checkMonValue.setText(String.valueOf(changeOfYear()));
}
public String changeOfYear(){
nextMon.nextMonth();
return nextMon + "" + nextMon.getYear();
}
And that is what get's displayed: Android.util.MonthDisplayHelper#44ee34e02013
Your are appending nextMon itself in your return value of changeOfYear() method. This way its returning the qualified name and address of nextMon as Android.util.MonthDisplayHelper#44ee34e0 appended with year as 2013.
Please correct to append nextMon.getMonth() and nextMon.getYear()
public String changeOfYear(){
nextMon.nextMonth();
return nextMon.getMonth() + "" + nextMon.getYear();
}
nextMon is an object as your return indicates. When you call nextMonth() you're issuing the command to increment the month but not actually retrieving anything.
Instead do this:
public String changeOfYear(){
nextMon.nextMonth();
return nextMon.getMonth() + " " + nextMon.getYear();
}
Note that I put a space in there where you only had "". You can even see this on your return: Android.util.MonthDisplayHelper#44ee34e02013
This is happening because nextMon is some type you defined, MonthDisplayHelper, and you haven't overridden the toString() method.
You can implement that method to return something meaningful, or, perhaps you meant to concatenate something different in this line:
return nextMon + "" + nextMon.getYear();
Probably something like this is what you want, nextMon.getMonth() or some method on nextMon.

Android Drawable setLevel(); not filling SeekBar appropriately

Okay so I've been able to customize a few SeekBar's to be used as a Bar Graph type of image, but since I need to be able to switch between a Green or Red Image (depending on certain values) which you can see below. The problem is that regardless of what value I use in the setLevel for the Drawable it doesn't fill appropriately (you can see the image below for an example since the green bar should be closer to the right based on the two values)
Below is the code for the section that setups this entire MTD Commission bar section, I don't know how much of the code you would need to see so I just decided to post all of this section.
void setupMTDBarSection() {
//Get Current Date and Number of Days in Current Month
Calendar cal = Calendar.getInstance();
int numberOfDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat today = new SimpleDateFormat("dd");
String currentDate = today.format(new Date());
//Get MTD Goal value from Preferences
String goalString = preferences.getString("keyMonthlyGoal", "0");
float mtdGoalFloat = Float.valueOf(goalString);
Integer mtdGoal = (int)mtdGoalFloat;
MTDGoalValue.setText(NumberFormat.getCurrencyInstance().format(mtdGoalFloat));
//Get Current MTD Value
String mtdString = preferences.getString("keyMTDValue", "0");
float mtdValueFloat = Float.valueOf(mtdString);
Integer mtdValue = (int)mtdValueFloat;
MTDCurrentProgress.setText(NumberFormat.getCurrencyInstance().format(mtdValueFloat));
//Do some math to determine if the Rep is below/above the daily goal
Integer dailyGoal = mtdGoal/numberOfDays;
Integer currentDayGoal = dailyGoal * Integer.valueOf(currentDate);
if (mtdValue >= currentDayGoal) {
MTDGreenTrack.setLevel(mtdValue);
MTDProgressBar.setProgressDrawable(MTDGreenTrack);
MTDProgressBar.setMax(mtdGoal);
MTDProgressBar.setProgress(mtdValue);
}
else {
MTDRedTrack.setLevel(mtdValue);
MTDProgressBar.setProgressDrawable(MTDRedTrack);
MTDProgressBar.setMax(mtdGoal);
MTDProgressBar.setProgress(mtdValue);
}
//Add Percentage to MTD Text
NumberFormat percentFormat = NumberFormat.getPercentInstance();
float percent = mtdValueFloat/mtdGoalFloat;
String percentage = percentFormat.format(percent);
MTDPercentText.setText("(" + percentage + ")");
//Setup MTD Indicator
MTDIndicator.setMax(numberOfDays);
MTDIndicator.setProgress(Integer.valueOf(currentDate));
MTDIndicator.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
});
}
I believe I found the issue. Apparently when you call setProgressDrawable more than once then you need to re-draw the image that is used since it looses the format that was previously there. Also, don't really need to set the level each time of the drawable as well, it matches up with the progress value of the Seekbar. Below is the code that works for me so far
Rect bounds = MTDProgressBar.getProgressDrawable().getBounds();
MTDProgressBar.setProgressDrawable(MTDGreenTrack);
MTDProgressBar.getProgressDrawable().setBounds(bounds);
MTDProgressBar.setProgress(mtdValue);
MTDProgressBar.setMax(mtdGoal);

Categories

Resources