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
Related
I made a calculator app and I made a clear Button that clears the TextView.
private TextView _screen;
private String display = "";
private void clear() {
display = "";
currentOperator = "";
result = "";
}
I got this code from Tutorial and set the clear button onClick to onClickClear, so it do that part of the code and it works. Now I have made this code delete only one number at a time and it don't work. What can be done to delete only one number at a time?
public void onClickdel(View v) {
display = "";
}
Below code will delete one char from textView.
String display = textView.getText().toString();
if(!TextUtils.isEmpty(display)) {
display = display.substring(0, display.length() - 1);
textView.setText(display);
}
You are modifying the string and not the textview.
To clear the TextView use:
_screen.setText("");
To remove the last character:
String str = _screen.getText().toString();
if(!str.equals(""))
str = str.substring(0, str.length() - 1);
_screen.setText(str);
String display = textView.getText().toString();
if(!display.isEmpty()) {
textView.setText(display.substring(0, display.length() - 1));
}
I am an android noobie. What I am trying to do is to make this String an ArrayList. This is done. When i Print it On (with tv.setText) , the result is what i need but in this if i have right below i cannot find the "1".
The result i want to have is to store the text between the noumbers inside another ArrayList but to go there i have to be able to read the strings from the ArrayList.
public class MainActivity extends AppCompatActivity {
String text = "1Hello12People22Paul22Jackie21Anna12Fofo2";
TextView tv;
List<String> chars = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
PrinThemNow();
}
public void PrinThemNow(){
chars = Arrays.asList(text.split(""));
tv.setText(toString().valueOf(chars));
for(int i=0;i<chars.size();i++){
if(toString().valueOf(chars.get(i)) == " 1"){
Toast.makeText(this,"I found One",Toast.LENGTH_LONG).show();
//This if is not working while the TV's text shows " 1"
}
}
}
}
First, just a tip, from string to char[] you can use
char[] chars = myString.toCharArray();
because it has no sense to save a char array as a string ArrayList
but now the problem. you have your string and you wanna print the text between the numbers.
It's not really clear what is your goal but lets try.
I will suppose you used the char[] because it's 10 times better and easier
case 1) you wanna print text betweens "1"s
//lets loop the chars
bool firstOneFound = false;
int firstOccurrence = -1;
int secondOccurrence = -1;
int i = 0;
for(char c : chars){
//is it equals to 1?
if(c.equals('1')){
//check if we are already after the first 1
if(firstOneFound){
//if yes, we found the final one
secondOccurrence = i;
break;
}
else{
//this is the first occurrence
firstOccurrence = i;
firstOneFound = true;
}
}
i++;
}
if(firstOccurrence != -1 && secondOccurrence != -1){
String myFinalString = myString.subString(firstOccurrence, secondOccurrence);
}
case 2) you wanna print all text except numbers (maybe with a space instead)
for(char c : chars){
//check if it's a number
if(c >= '0' && c <= '9'){
//replace the number with anything else
c = ' '; //if you wanna have it as a space
}
}
//print the final string
String myFinalString = new String(chars);
NOTE:
You can also use ArrayList of string, just replace ' with "
hope it helps
I want to get a text that it is a part of an string.For example: I have a string like "I am Vahid" and I want to get everything that it's after "am".
The result will be "Vahid"
How can I do it?
Try:
Example1
String[] separated = CurrentString.split("am");
separated[0]; // I am
separated[1]; // Vahid
Example2
StringTokenizer tokens = new StringTokenizer(CurrentString, "am");
String first = tokens.nextToken();// I am
String second = tokens.nextToken(); //Vahid
Try:
String text = "I am Vahid";
String after = "am";
int index = text.indexOf(after);
String result = "";
if(index != -1){
result = text.substring(index + after.length());
}
System.out.print(result);
Just use like this, call the method with your string.
public String trimString(String stringyouwanttoTrim)
{
if(stringyouwanttoTrim.contains("I am")
{
return stringyouwanttoTrim.split("I am")[1].trim();
}
else
{
return stringyouwanttoTrim;
}
}
If you prefer to split your sentence by blank space you could do like this :
String [] myStringElements = "I am Vahid".split(" ");
System.out.println("your name is " + myStringElements[myStringElements.length - 1]);
So if you are adding in a string, you can just add them via += method(the one i know and using atm). but how can you delete a word in a string/string array?
example: i have a string
String="Monday,Tuesday,Wednesday"
how do you make it into
String="Monday,Wednesday"
any help please?
You could use the replace method.
String sentence = "Monday,Tuesday,Wednesday";
String replaced = sentence.replace("Tuesday,", "");
its easy
just use
yourString = yourString.replaceAll("the text to replace", ""); //the second "" show empty string so the text will get replace by empty string
finally yourString will contain the text u desire Thats it :)
You can use the "public String replace(char oldChar, char newChar)" method if you want to remove "Tuesday" and not the second element
https://stackoverflow.com/questions/16702357/how-to-replace-a-substring-of-a-string
I think, i will use it for simplicity otherwise go to other suggested answer...
Use Arraylist for storing days:
ArrayList<String> days = new ArrayList<String>();
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
Use it for creating days string:
public String getDays() {
String daysString = "";
for (int i = 0; i < days.size(); i++) {
if (i != 0)
daysString += ", ";
daysString += days.get(i);
}
return daysString;
}
And whenever you want to remove use
days.remove(1);
or
days.remove("Tuesday");
then again call getDays();
IInd Method if you want to use only string:
String list = "Monday,Tuesday,Wednesday";
System.out.println("New String : " + removeAtIndex(list, 1));
and
public String removeAtIndex(String string, int index) {
int currentPointer = 0;
int lastPointer = string.indexOf(",");
while (index != 0) {
currentPointer = string.indexOf(',', currentPointer) + 1;
lastPointer = string.indexOf(',', lastPointer + 1);
index--;
}
String subString = string.substring(currentPointer,
lastPointer == -1 ? string.length() : lastPointer);
return string.replace((currentPointer != 0 ? "," : "") + subString
+ (currentPointer == 0 ? "," : ""), "");
}
Something like this using a regular expression:
String contents = "Monday,Tuesday,Wednesday";
contents = contents.replaceAll("[\\,]+Tuesday|^Tuesday[\\,]*", "");
I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);