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
}
Related
Hi I have a csv that looks like this:
r1c1|r1c2|r1c3
r2c1|r2c2|r2c3
As you can see it is delimited by the character "|"
In my application, I am trying to explode this using input stream. Here is my code:
String line = "";
String cvsSplitBy = "|";
try {
File initialFile = new File(myfile.txt);
InputStream targetStream = new FileInputStream(initialFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(targetStream));
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(cvsSplitBy);
String c0 = RowData[0];
String c1 = RowData[1];
String c2 = RowData[2];
Toast.makeText(mainactivity.this, c2, Toast.LENGTH_LONG).show();
}
}catch (IOException ex) {
// handle exception
}
Unfortunately, this appears to return each character in the csv as a row. The toast example above returns 1 then 2.
Any ideas how to return the proper column, anyone?
split() splits string around matches of the given regular expression, therefore use of special character (and vertical bar is one of these) requires escaping to strip its "powers".
String cvsSplitBy = "\\|"
See docs: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
I have a sqlite database on my android app and it works fine, but when I try to insert arabic language it shows squares shape like this [] [] [] [] []
I inserted the data on database using a txt file in the assets folder like this:
INSERT INTO user_table (id, name) VALUES (1,'احمد');
I tried saving the txt file in utf8 coding but the app crashes.
I solved the problem by using this code:
BufferedReader reader = new BufferedReader(new InputStreamReader(
ctx.getAssets().open("textFile.txt"), "UTF-8"));
Convert your string to "UTF-8" before insertion like
SQLiteDatabase sq = this.getReadableDatabase();
ContentValues c = new ContentValues();
try {
String Name="نمونہ";
c.put("Name", new String(Name.getBytes(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
sq.insert("tableName", null, c);
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.
Here I am reading file word by word and manipulating List view with these word. Problem here is First name and Last name are appearing in different rows. e.g. Name = "John Clerk" then I am getting "John" in first row and "Clerk" in second row of List view. They must be in single row and so forth for other data. What should I make changes to work it properly? My code...
String myData = "";
String strLine;
String listName = "" ;
FileOutputStream fos;
FileInputStream fstream;
DataInputStream in;
String[] SavedFiles;
BufferedReader br;
public void readFile(String file) throws IOException
{
fstream = openFileInput(file);
Scanner scanFile = new Scanner(new DataInputStream(fstream));
ArrayList<String> words = new ArrayList<String>();
String theWord, theWord1, theWord2;
while (scanFile.hasNext())
{
theWord = scanFile.next();
words.add(theWord);
}
Toast.makeText(getBaseContext(), "" + size, 1000).show();
adapterFriends = new ArrayAdapter<String>(getBaseContext(), R.layout.text, words);
lvFinal.setAdapter(adapterFriends);
adapterFriends.notifyDataSetChanged();
}
Try to use nextLine() instead of next(), as it should return every string between \n chars.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextLine()
hope that helps
If I understand correctly what you need, try this:
while (scanFile.hasNext())
{
String name = scanFile.next();
if (scanFile.hasNext())
{
name = String.format("%s %s", name, scanFile.next());
}
words.add(name);
}
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);
.....
}