android sqlite doesn' support arabic - android

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);

Related

How to read an CSV file in android?

I am reading a CSV file which have format: "col1"\t"col2". As my understanding there are two methods to read an CSV file and add to array.
1. ReadByLine.
2. ReadNext.
In Readbyline I face issue if col2 have \n in between the string, and that is added to my second index. like ("Hi how r u" "I am \n fine")
In readNext I face issue when my column1 is empty it return col2 value lile ("" "I am fine"). readNext return "I am fine".
Can any one suggest any best approach to work with this format.
Each line in a CSV file uses , as a delimiter. You should read the file line by line and split the line with the above delimiter:
try {
File f = new File("source.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
while( ( line = br.readLine() ) != null ) {
String[] tokens = line.split(",");
}
} catch (IOException e) {
e.printStackTrace();
}
Then, tokens.length will give you the size.
If you have spaces the use:
String newString = tokens[x].trim();

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
}

Import multiple .csv file into android sqlite database

I am now trying to import csv files from a certain directory in sd card from an android device. Recently, I can successfully import a single csv files. However, I have no ideas on how to get the list of all csv files and then using a loop to import the csv file one by one.
This is the my code for importing single csv:
button_import_csv.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
try{
FileReader file = new FileReader("/sdcard/downloadedfolder/A1/adv_sales_order.csv");
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues=new ContentValues();
String line = "";
String tableName ="adv_sales_order";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split("\t");
contentValues.put("order_date", str[0]);
contentValues.put("cust_code", str[1]);
contentValues.put("customer_ref_no", str[2]);
contentValues.put("line_no", str[3]);
contentValues.put("item_code", str[4]);
contentValues.put("tran_code", str[5]);
contentValues.put("order_qty", str[6]);
db.insert(tableName, null, contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
}catch (IOException e){
}
}
});
The columns for different csv fileS are not the same.(For example,some may has 4 columns named A,B,C,D and the other one may has columns named as C,D,E,F) Besides hard coding all columns for each csv file, are there any possible ways?
Can anyone tell me any solution???Thank you.
There are two possibilities I can think of...
First: If you are in control of the filenames then give them names with a sequential numeric aspect, e.g., file1.csv, file2.csv etc You can then simply use a for loop to build the filenames and process them. Example...
// Lets say you have 5 files named file1.csv thru file5.csv
for(int i = 1; i < 6; i++) {
String filename = "file" + i + ".csv";
// Process the file which has the above filename
}
Second: Get all of the files in the directory using the listFiles() method. Example...
// This code assumes you have a File object for the directory called dir
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
String filename = files[i].getAbsolutePath();
if (filename.endsWith(".csv")) {
// Process the file which has the above filename
}
}
I'm not sure if either of the code blocks above are perfect but basically they both simply use a for loop. There are other ways but those are the most straight-forward.
EDIT:
Some csv files use the first line to describe the column names. In some ways this is a bit like a schema of a dataset. Example (using comma-separated values)...
A,B,C,D
valueA,valueB,valueC,valueD
...
Using this approach means you can get access to the column names by reading the first line and splitting it to make an array. You can then use a for loop to put the ContentValues. Try the following...
// Read the first line separately and split to get the column names
line = buffer.readLine();
String[] cols = line.split("\t");
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split("\t");
for (int i = 0; i < cols.length; i++) {
contentValues.put(cols[i], str[i]);
}
db.insert(tableName, null, contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
BTW I notice you're splitting on "\t" so make sure your column names on the first line are tab-delimited (obviously).

StringBuilder related issue

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);
.....
}

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