StringBuilder related issue - android

i have following code in which, i am fetching the data from the sqlite database. I am able to get all the values well whenever the data is upgraded but cant able to upgrade the values stored into a StringBuilder.So whenever the data is upgraded StringBuilder show the first data of the data base.
private void showData(Cursor cursor) {
StringBuilder stbuilder = new StringBuilder();
while(cursor.moveToNext())
{
start_time = cursor.getString(1);
end_time = cursor.getString(2);
duration_time = cursor.getString(3);
phone_option = cursor.getString(4);
phone_mode = cursor.getString(5);
stbuilder.append(start_time+" "+end_time+" "+duration_time+" "+phone_option+" "+phone_mode);
Log.i("STARTtttDB", ""+start_time);
Log.i("enddddDB", ""+end_time);
Log.i("duratonnn", ""+duration_time);
Log.i("OpTIONnnnn",""+phone_option);
Log.i("M O D E ",""+phone_mode);
String data=stbuilder.toString();
Log.i("Data OUtput",data);
}

You should create a new StringBuilder for each iteration, or reset it using:
stBuilder.setLength(0).
Also, instead of using string concatenation (+) inside of StringBuilder.append(), you should probably have a series of appends:
stBuilder.append(start_time);
stBuilder.append(" ");
stBuilder.append(end_time);
...
Also note that you can safely forgo the use of StringBuilder altogether as the compiler optimizes string concatenation using StringBuilder anyway. Here is a performance study I found.

You need to reset the StringBuilder with a call to setLength(0);
while(cursor.moveToNext())
{
stBuilder.setLength(0);
.....
}

Related

How to assign StringBuilder to String value at Android?

I have a dynamic message Stringbuilder value in my codes.
But i want to create temp string and i want to save message value to temp value and than clean message value:
For example:
StringBuilder messages;
StringBuilder [] temp = new StringBuilder[1000];
...///other part of codes
temp[i]=message;
String text=intent.getStringExtra("theMessage");
i++;
messages.delete(0, messages.length());
A mean, when my messages come 34 i want to save temp[0] and clean message and i want to increase i with i++ and than message come 23 than temp[1]=23 and so on... How can i do this at android ?
Its as simple as following:
StringBuilder [] temp = new StringBuilder[1000];
int index = 0;
if(messages.length() == 34){
temp[index] = new StringBuilder(messages);
messages.delete(0, messages.length());
}
...
If temp[] is of type String then simply
temp[index] = new StringBuilder(messages.toString())

Populate a SQLite database from a website

I searched a bit and couldn't find anything so I'm asking it here:
It'd be great if there's a tutorial or example project where I can look at. So far I've only found on how to populate this database using the data that is generated locally, by programmer's input.
Question:
I have an URL to a website that is a .txt with some data, how do I parse it, populate it to a SQLite database that I'll create in my Android application?
Edit:
This is the format:
Item1 <newline>
Description <newline>
LocalFilePathToPicture1<newline>
Item2 <newline>
Description <newline>
LocalFilePathToPicture2<newline>
...
Ok as your comments and latest edits, lets say your text file url is something like this
http://www.example.com/myTextFile.txt
What you can do something like this
StringBuffer myString = new StringBuffer("");
try {
// Create a URL
URL url = new URL("http://www.example.com/myTextFile.txt");
// Read the text
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String string;
while ((string = in.readLine()) != null) {
// string is one line of text; readLine() reads the newline
myString.append("__"+string);
}
in.close();
}
catch (Exception e) {
}
return myString;
And here is a sample of doInBackground() method inside your AsyncTask class where you will be splitting the string and inserting them into sqlite
#Override
protected String doInBackground(String... params) {
String myString = params[0];
String[] splitedString = myString.split("__");
ContentValues cv=new ContentValues();
cv.put("firstline", splitedString[0]); //where firstline is your column name
cv.put("secondline", splitedString[1]);
db.insert(yourTable, null, cv); //where db is your instance of writable database
db.close(); //Close the connection
}

Saving a string of data separated by commas

Before I begin to work on this project, I have a couple of editTexts and when user enters the text I want to save it(as a string and add the values from additional edittexts in that string separated by commas). What is the best way to save data like this.
Another thing the previous data will not be needed when the user launches the app the next time.
There's probably a hundred different ways to make a delimited list, but to literally answer your question I'll give you three easy ways
String:
String someString = someString + "," + SOMESTRINGFROMEDITTEXT;
StringBuilder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(SOMESTRINGFROMEDITTEXT + ",");
String someString = stringBuilder.toString();
ArrayList:
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> arrayListOfStrings = new ArrayList<String>();
arrayListOfStrings.add(SOMESTRINGFROMEDITTEXT);
for (String s : arrayListOfStrings) {
stringBuilder.append(s + ",");
}
String someString = stringBuilder.toString();

Named placeholders in Android

In my android app
in message if i give message "hi #name,welcome your username:#username and password:#password" and in message #name,#username,#password are to be replaced with values iam reading from csv file
and it should send message as example:"hi praveen,welcome your username:neevarp and password:12345"
and those values are from csv .while searching i got some link
Named placeholders in string formatting
Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
but in android
StrSubstitutor
class is not there i think so is there any way to implement this
here is my code of reading values from csv and sending messages by replacing place holders
public void sendingSms(String message, String file_path) {
File file = new File("", file_path);
// Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int iteration = 0;
while ((line = br.readLine()) != null) {
if (iteration != 0) {
StringBuilder text = new StringBuilder();
text.append(line);
String[] contact = text.toString().split(",");
String phoneNumber = contact[4];
String name = contact[1];
String username = contact[2];
String password = contact[3];
//here i have to replace place holders with name,username,password values
//message.replace("#name", name);
//message.replace("#user", username);
Toast.makeText(Message.this, "" + message,
Toast.LENGTH_SHORT).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null,
null);
}
iteration++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
You should really be using the built in string formatting Android provides via string resources: http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
The functionality that you want is built right into the String class itself if you want to design your own StrSubstitutor class. Essentially building/designing a foreach with your Mapped values into the function.
String result = inputString.replace(valueString, replacedValueString);
But I am unaware of the function that you are requesting being built-in. Alex Fu as well has provided alternate means by which you could handle your string replacement.

Android cursor charc to array

I hope i explain the correctly...
What i want to do is be able to run a query and then get the first record of that query and put the characters into an character array, then i want to get the second query and put that into the same array depending on where it is suppose to be inserted into the array.
So for example...the first record from the query will have the string 'hello', i want this to be inserted into the array at position one. Then i want record two which will be 'you' to be inserted at position 6. so when the character array is out put it will display 'hello you'
How do i go about doing this?
SQLiteDatabase db = dbs.getReadableDatabase();
String SQL = "SELECT * FROM Table";
Cursor cursor = db.rawQuery(SQL, null);
startManagingCursor(cursor);
char charac_array[];
charac_array = new char[10];
while (cursor.moveToNext()) {
???
}
That's what you probably want:
StringBuilder sb = new StringBuilder();
while (cursor.moveToNext()) {
String s = cursor.getString(...);
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(s);
}
String helloYou = sb.toString();
UPDATE
To fill a char array from String
StringBuilder sb = new StringBuilder();
char[] charArray = new char[10];
while (c.moveToNext()) {
String s = getFromCursor(c);
s.getChars(0, 10, charArray, 0); // <-- this copies 10 chars from s to charArray
sb.append(charArray);
}
You'll have to take care when s is less than 10 characters though.

Categories

Resources