I am trying to colour text for my android app depending on a value entered into the SQLite database. I have set up 3 textviews and have different text colours for all of these.
The code looks like this
String arr[] = data.split("..\n\n");
for(int i = 0; i < arr.length; i++)
{
System.out.println("arr["+i+"] = " + arr[i].trim());
if(arr[i].contains("High Severity"))
{
// String highArr = arr[i];
textView.setVisibility(View.VISIBLE);
textView.setText(highArr+"\n");
textView.setTextColor(Color.RED);
}
else if(arr[i].contains("Low Severity"))
{
textView3.setVisibility(View.VISIBLE);
textView3.setText(arr[i]+"\n");
textView3.setTextColor(Color.GREEN);
}
else if(arr[i].contains("Medium Severity"))
{
textView2.setVisibility(View.VISIBLE);
textView2.setText(arr[i]+"\n");
textView2.setTextColor(Color.rgb(255, 136, 0));
}
}
I have parsed the string which has all the values for my database table, but when I try my for loop it only prints out the latest entered values.
It looks like it could be that your arr[] is only got one entry in it. You should use the debugger to see how many times your loop actually runs and what the actual lenght of the array is.
EDIT:
I just realized that you only have three textviews. Of course the textview is displaying the last one because each time your calling the settext method its reseting the text. There are a few ways to do what you are trying but Im not sure how your app is set up. You should try dynamically creating the textview, setting the text to it, then adding that textview to a linearlayout or relativelayout that you have set up. Or you could do this inside of a listview using a custom implementation of a baseadapter or any of the other adapters depending on your needs.
I would change my code like this:
String arr[] = data.split("..\n\n");
String Hseverity = "", Mseverity = "", Lseverity = "";
for(int i = 0; i < arr.length; i++)
{
System.out.println("arr["+i+"] = " + arr[i].trim());
if(arr[i].contains("High Severity"))
{
// String highArr = arr[i];
textView.setVisibility(View.VISIBLE);
Hseverity += arr[i] +"\n";
textView.setText(Hseverity);//do this to save each High Severity entry
//same for the other severity levels
textView.setTextColor(Color.RED);
}
else if(arr[i].contains("Low Severity"))
{
textView3.setVisibility(View.VISIBLE);
Lseverity += arr[i]+"\n";
textView3.setText(Lseverity);
textView3.setTextColor(Color.GREEN);
}
else if(arr[i].contains("Medium Severity"))
{
textView2.setVisibility(View.VISIBLE);
Mseverity += arr[i] + "\n";
textView2.setText(Mseverity);
textView2.setTextColor(Color.rgb(255, 136, 0));
}
}
Related
This type of formatting i need i don't want to use \n or br because my string is dynamic and i want to fix any text in this this format
This is my first textview
This is my second
textview this
is my third
textview
You can do it programmatically using this function
val text = "This is my first text view this is my second textview this is my third textview"
textView.text = proxyWifi.textFormation(text)
copy/paste this code do your project :)
public String textFormation(String text){
String result = "";
String[] sentenceWords = text.split(" ");
List<String> newSentenceWords = new ArrayList<>();
textRec(sentenceWords, newSentenceWords, sentenceWords.length -1, 0, "");
int spacing = 0;
for(int i = newSentenceWords.size() -1 ; i >= 0 ; i--){
if(i == newSentenceWords.size() -1)
result = newSentenceWords.get(i);
else{
result += "\n";
spacing += (newSentenceWords.get(i + 1).length() - newSentenceWords.get(i).length())/2;
for(int j = 0 ; j < spacing ; j++){
result += " ";
}
result += newSentenceWords.get(i);
}
}
return result;
}
public void textRec(String[] words, List<String> newWords, int indexWords, int indexNewWords, String sentence){
Log.e("sentence", sentence);
if(indexWords >= 0){
if(indexNewWords == 0) {
newWords.add(words[indexWords]);
textRec(words, newWords, indexWords - 1, ++indexNewWords, "");
}else{
if(newWords.get(indexNewWords - 1).length() >= sentence.length())
if(sentence.isEmpty())
textRec(words, newWords, indexWords - 1, indexNewWords, words[indexWords]);
else
textRec(words, newWords, indexWords - 1, indexNewWords, words[indexWords] + " " + sentence);
else {
newWords.add(sentence);
textRec(words, newWords, indexWords , ++indexNewWords, "");
}
}
}else{
if(sentence.isEmpty()){
return;
}else{
newWords.set(indexNewWords - 1 ,sentence + " " + newWords.get(indexNewWords - 1)) ;
}
}
}
OUTPUT
There is no default implementation for this. Also, you can't find the line number to do this.
So you have to split the sentence into multi lines.Use \n for next line. Set gravity center to your textView.
if you use \n then your next line will be start from
This is my first textview
<here>
<not here>
So, basically you need multiple TextViews.
First devide your text String to multiple parts(Note:- (n+1)th part should be less than nth part and deff. should be both end space).
Second Create a LinearLayout with vertical orientation and center gravity.
Third loop on that array.
and in loop create a new textview with gravity center, and set the text to it.
and add this TV to linearLayout.
thats it.
I tried to give you result as you want
This may work
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context="com.ap.mytestingapp.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/strTV"
android:text="hello world!"
android:gravity="center" />
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.strTV);
//pass string whatever you want to show
String apStr = printString("This is my first textview This is my second textview this is my third textview");
//you need to define text size according to your requirement
// I took here 25
tv.setTextSize(25);
tv.setText(apStr);
}
private String printString(String responseString) {
String str = responseString;
String resultStr = "";
//you need to define cutLength Value according to your textView's textSize
// I took it 35 when textView's textSize is 25
int cutLength = 35;
int count = 0;
int from = 0;
for(int i = 0 ; i < str.length(); i++){
//increment of count
count++;
//check count value with cutLength so that we can add \n to string
if(count == cutLength){
// adding \n to substring
resultStr = resultStr + str.substring(from, i) + "\n";
// assigning from = i
from = i;
// reduce cutLength value
cutLength = cutLength-10;
// assigning count = 0
count = 0;
} else if(i == str.length()-1){
// adding \n to substring
resultStr = resultStr + str.substring(from) + "\n";
}
}
//return resulting string
return resultStr;
}
}
I want show list of strings in TextView and I get this list from server.
List from json :
"stars": [
{
"name": "Elyes Gabel"
},
{
"name": "Katharine McPhee"
},
{
"name": "Robert Patrick"
}
]
I want show this names such as this sample :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
I should setText from this TextView in Adapter.
With below code I can show name :
model.get(position).getStars().get(0).getName();
But just show me Elyes Gabel !!!
I want show me such as this :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
How can I it? Please help me
Here is the correct answer you might be after,
Lets just say you have the above JSON and you have converted that in a String array.
So array will look something like below:
String stars[] = {Elyes Gabel, Katharine McPhee, Robert Patrick}
TextView textView = // initialise the textview here or however you do.
StringBuilder builder = new StringBuilder();
for (String star: stars) {
builder.append(star);
builder.append(", ");
}
textView.setText(builder.toString());
You will get the desired output...
You need to loop through all "Star" elements and build the string yourself. You should have something like this:
String concatenatedStarNames = "";
List<Star> stars = model.get(position).getStars(); // I assume the return value is a list of type "Star"!
for (int i = 0; i < stars.size(); i++) {
concatenatedStarNames += stars.get(i).getName();
if (i < stars.size() - 1) concatenatedStarNames += ", ";
}
And then you set the text of the text view to concatenatedStarNames.
You can build it yourself with a StringBuilder, something like:
final Collection<Star> stars = models.get(position).getStars();
final StringBuilder builder = new StringBuilder();
boolean first = true;
for (Star star : stars) {
final String name = star.getName();
if(first) {
first = false;
builder.append(name);
} else {
builder.append(", ").append(name);
}
}
final String allStarNames = builder.toString();
you can just do - (with your same logic of accessing stars)
String strNames;
for (int i=0; i<starsCount; i++){ //starsCount = No of stars in your JSON
strNames += model.get(position).getStars().get(i).getName();
if( i != starsCount-1)
strNames += ", ";
}
textViewVariable.setText(strNames);
i want to show json in html tag below mycode im getting json and show in two diffrent textview but i want to show in single lines and show all getJSONObject(i).getString("name")); name in bold color and all getJSONObject(i).getString( "sub_ingredients")); in simple text do not want to use two textview i want toshow insingle text view what wil ido? i want to show as html tag
"dish_ingredient":
[
{"name":"Salt","sub_ingredients":""},
{"name":"Sesame Seeds","sub_ingredients":""},
{"name":"Calcium Sulfate","sub_ingredients":""},
{"name":"Brown Sugar","sub_ingredients":""},
{"name":"Salt","sub_ingredients":""},
{"name":"Hamburger Bun","sub_ingredients":""},
{"name":"Cheese-cultured pasteurized milk","sub_ingredients":""},
{"name":"Hamburger Bun","sub_ingredients":"Wheat, Niacin, Eggs"}]}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
row4 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row4.findViewById(R.id.name)).setText(school5
.getJSONObject(i).getString("name"));
((TextView) row4.findViewById(R.id.subingredients))
.setText(school5.getJSONObject(i).getString( "sub_ingredients"));
table3.addView(row4);
}
If I understand correctly you want to display the JSON as formatted above in one TextView but with certain highlighting. Check out this post. If you want to keep the JSON in its original format I would just get the initial JSONArray, call toString(), and then replace the words "name" and "sub-ingredient" with text fomatted the way you want.
If I misunderstood and you want to extract the values for each JSONObject you just need to loop through the JSONArray
//format these to look like whatever you want
SpanableString nameTitle = "Name: "
SpanableString subIngredientTitle = " Sub-ingredient: ";
String concatProduct = "";
int arraySize = jsonArray.length();
for(int i = 0; i < arraySize; i++){
JSONObject thing = jsonArray.getJSONObject(i);
String name = thing.getString("name");
String subIngredient = thing.getString("sub-ingredient");
if(i == 0){
concatProduct = nameTitle + name + subIngredientTitle + subIngredient;
} else {
concatProduct += " " + nameTitle + name + subIngredientTitle + subIngredient;
}
}
textView.setText(concatProduct);
Something like this would let you process the JSONArray and build one string that you could set to one TextView. The formatting is up to you.
I am automating a product using robotium. I need to do some dat validation kind of task there.
Scenario is like:
We click on a list, select some items in the list and do some operation.
I want to put the names of the items selected into an array. Such that i can compare it later.
I used the following code:
for(i=0; i<=n;i++)
{
solo.clickInList(i);
Array1[i]=solo.getText(i).toString();
}
But sadly, this statement is not extracting the text of the textView selected but the id of the textView.
Please help me by giving an example of how to get the text of the TextView selected.
At a fix!!
if you have only listview with texts, it should work for you (I didn't test it):
ListView listView = solo.getView(ListView.class, 0);
String text = listView.getItemAtPosition(position));
Another way will be like this:
ArrayList<TextView> result = solo.clickInList(line);
String text = "";
for (int i = 0; i < result.size(); i++) {
text += result.get(i).getText().toString() + " ";
}
if (text.length() > 0) {
text = text.substring(0, text.length() - 1); // remove last space
}
I'm new android/java programmer and I can't find anywhere how to set default varriable value only on first call. My console log delete after second call. My code looks like:
public class Ftp {
[...]
//Console
String console_strings[] = new String [15];
int console_line = 0;
//
[...]
public void drawConsole(String msg){
CharSequence time = DateFormat.format("hh:mm:ss", d.getTime());
String message = "["+time+"] "+msg;
TextView console = (TextView)((Activity)context).findViewById(R.id.console);
String newString = "";
for(int i = 0; i < console_strings.length; i++){
if(console_strings[i] != null)
newString += console_strings[i] + "\n";
else
{
console_strings[i] = message;
newString += console_strings[i] + "\n";
break;
}
}
console.setText(newString);
}
}
Whenever I want to add something to the console, it delete old text value.
There are multiple ways to do this. The problem you are having is that you are setting the entire textview's text at once. You could do one of a few things. You could do
console.setText(console.getText() + newString);
or
console.append(newString);
Both of these would work. There are multiple other ways, but those should do it for you.
TextView has also an append method