Add a lot of images dynamically to SQLite Database Android - android

I hope you are good.
I'm developping an application that has to retrieve images from sqlite database, for each row I have one image (using obviously blob as a type), and I was wondering if I could not only add one image but a lot, without knowing how much images the user wants to add, for example: User1 wants to add 3 images to database. User2 5 images and so on. How can I store them? is there a kind of Blob[] or something? And if possible how can I choose more than one image from galery?
I'm not used to make posts in english so I hope I explained well ^^'.
Thank you.

Save the images in a list as base64 strings like:
String img1 = Base64.encode(value_of_image, Base64.DEFAULT);
.
.
.
String img25 = Base64.encode(value_of_image, Base64.DEFAULT);
List<String> imagesListActivity = new ArrayList();
imagesList.add(img1);
.
.
.
imagesList.add(img25);
and in your save method in helper class, you can do sth like:
public void saveImageList(List<String> images){
ContentValues cv = new ContentValues();
for(int i = 0; i < images.length; i++){
cv.put(COL_NAME, images[i);
}
}
and in activity class, try this by passing the actual list like below:
DBHelper dbHelper = new DBHelper();
dbHelper.saveImageList(imagesList);

Related

How to insert a list of values in a column in excel sheet using aspose library in android?

I am using aspose.cell library in my android application to create excel sheets as an output in sdcard.
Here is my code:
void insertData() throws Exception {
//Get the SD card path
String sdPath = Environment.getExternalStorageDirectory().getPath() + File.separator;
Workbook wb = new Workbook();
Worksheet worksheet = wb.getWorksheets().get(0);
Cells cells = worksheet.getCells();
ArrayList<String> arr = new ArrayList<String>();
arr.add("one");
arr.add("two");
arr.add("three");
int i = 0;
for(String value : arr){
//Put some values into cells
//Log.i("rubanraj", value);
Cell cell = cells.get("A"+String.valueOf(++i)); //for A1,A2,A3...
cell.putValue(value);
}
wb.save(sdPath + "Cells_InsertRowsAndColumns.xlsx",SaveFormat.XLSX);
}
I have a set of data in arrayList, as final i need to insert that values in to a column in my worksheet. For that, i have used one for loop to get the cell position like A1,A2,A3.. from worksheet and inserting data one by one.
Everything is fine, but i havent used aspose lib before so i dont know much things. Actually what i required here is, how to insert the arraylist of values directly to a Column like (A,B,C...) in excel sheet using this aspose.cell lib?
Here I ll give some links which i referred for this work.
https://github.com/asposecells/Aspose_Cells_Android/blob/master/Examples/QuickStart/InsertRowsAndColumns/src/com/example/insertrowsandcolumns/MainActivity.java
https://github.com/asposecells/Aspose_Cells_Android
I have already tried apache POI and jxl libraries, but i am feeling aspose is easy to use compared to other libs.
Aspose.Cells provides some means and data import techniques which you may try. For example, you may directly try Cells.importArrayList() method to import your underlying ArrayList to the worksheet in Excel file, see the sample code here for your reference:
e.g
Sample code:
Workbook wb = new Workbook();
Worksheet worksheet = wb.getWorksheets().get(0);
Cells cells = worksheet.getCells();
ArrayList<String> arr = new ArrayList<String>();
arr.add("one");
arr.add("two");
arr.add("three");
//Importing the contents of ArrayList vertically (A1:A3).
cells.importArrayList(arr,0,0,true);
//Importing the contents of ArrayList horizontally (A10:C10).
cells.importArrayList(arr,9,0,false);
Please see the document for your complete reference.
I am Developer evangelist at Aspose.

add large amount of data in SQLite android

I am new to android and maybe its a silly question but i am not getting it. See i am designing a game in which we give scores to some persons. So i want to store the names of the persons in a database while installation and then their scores set to 0 initially which will be updated according to what the users select. Here i am not able to figure out that how should i enter the data as it will be around 100 names and their scores. Using INSERT INTO() statement will make it like 100 statements. So is there any short method like can we do it through strings or something. Just guessing though. Any help would be appreciated.
You don't hard-code names or scores into your SQL statements. Instead, you use parameters.
var command = new SQLiteCommand()
command.CommandText = "INSERT INTO Scores (name, score) VALUES(#name, #score)";
command.CommandType = CommandType.Text;
foreach (var item in data)
{
command.Parameters.Add(new SQLiteParameter("#name", item.Name));
command.Parameters.Add(new SQLiteParameter("#score", item.Score));
command.ExecuteNonQuery();
}
and then just loop through all of the names and scores.
I recommend you using a transaction.
You can archive this stating you want to use a transaction with beginTransaction(), do all the inserts on makeAllInserts() with a loop and if everything works then call setTransactionSuccessful() to do it in a batch operation. If something goes wrong, on the finally section you will call endTransaction() without setting the success, this will execute a rollback.
db.beginTransaction();
try {
makeAllInserts();
db.setTransactionSuccessful();
}catch {
//Error in between database transaction
}finally {
db.endTransaction();
}
For the makeAllInserts function, something like this could work out:
public void makeAllInserts() {
for(int i = 0; i < myData.size(); i++) {
myDataBase = openDatabase();
ContentValues values = new ContentValues();
values.put("name", myData.get(i).getName());
values.put("score", myData.get(i).getScore());
myDataBase.insert("MYTABLE", nullColumnHack, values);
}
}
If you also want to know about the nullColumnHack here you have a good link -> https://stackoverflow.com/a/2663620/709671
Hope it helps.

Saving multiple data one at a time in database in Android

I want to save multiple files to my database one by one.
And what happen here using my codes is this:
What I want to happen is like this one:
here is my code:
//Arraylist for getting the multiple brand code
ArrayList<String> content = new ArrayList<String>();
for (int j=0; j<checkSelected.length; j++) {
if(checkSelected[j]==true) {
String values = BrandListAdapter.mListItems.get(j);
//content.add(values);
Cursor rSubBrand = databaseHandler.getReport_SubBrandCode(values);
String SubBrandCode = rSubBrand.getString(rSubBrand.getColumnIndex(Constants.SUBBRAND_CODE));
content.add(SubBrandCode);
//Casting and conversion for SubBrand Code
String subBrand = content.toString();
//SAVE SUBBRAND
databaseHandler.SaveSubBrand(new Cons_iReport (ReportCode, subBrand));
Toast.makeText(getApplicationContext(), subBrand, Toast.LENGTH_LONG).show();
}
}
Mistakes:
content.add(SubBrandCode);
do you know how to remove the '[ ]' in the saved data? (e.g. [AC001]) All I want to save is the AC001 only.
Solutions:
Call clear() method of ArrayList before adding new values into it.
Its giving you [AC001] as you are subBrand by doing content.toString();. Don't convert it to string, instead use content.getString(position) and it will give you String value.

Alphabet Indexed ListView Without a cursor

I receive data from a server using JSON and I want to order them alphabetically with alphabet indexed section and store them in a ListView.
Maybe something that will happen in :
for(int i=0;i<jArray.length();i++){
// here
}
I read that you can order elements like that only using a cursor. In my case would be very inefficient to store the elements from the server in the database and read them again. Waste of time and memory.
So, I am asking you if there could be any solution for my problem : order alphabetically with alphabet indexed section string received from JSON .
EDIT: I want my listview to look like this http://eshyu.wordpress.com/2010/08/15/cursoradapter-with-alphabet-indexed-section-headers/ . I mean with those sections . All tutorials I found said that you need to fetch information with a cursor. My question was if I could't do this wihout a cursor, because it would be a waste of memory to store them in the local database too.
You may need to parse the JSON Array :
List<Project> list = new ArrayList<Project>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = (JSONObject) jArray.get(i);
project = new Project();
project.setId( Long.parseLong(obj.get("id").toString()));
project.setKey(obj.get("key").toString());
project.setName(obj.get("name").toString());
list.add(project);
}
You can use the comparator class like this to sort them :
Collections.sort(list), new Comparator<Project>() {
public int compare(Project p1, Project p2) {
return p1.getKey().compareToIgnoreCase(p2.getKey());
}
});
You can also have Project class and implements Comparable:
public class Project implements Comparable<Project> {
private long id;
private String key;
private String name;
public int compareTo(Project p) {
if (this.key > p.key)
return -1;
else if (this.key < p.key)
return 1;
return 0;
}
}
And then sort the list by Collections.sort(list);
My suggestion is try to sort the data in the Server-side, because the memory of the phone is limited and it may make you application time consuming to show the data, but you do not have memory limitation problem in the Server-side.
use a comparator to sort the arraylist as described here . And then use an ArrayAdapter to show the items in Listview

Android: having basic problems with sqlite database

I am having some trouble implementing a sqlite database in my simple android application:
a user is displayed a list of animals in a Listview.Upon selecting an animal the user is brought to an activity "Animal",which will display a picture of the animal and give them options to
view Animal Bio
Back
All very simple so far, right?
I have working the database, which will populate the listView of animals.Database currently looks like
Table Animal-
_ID,
Name
Table Biography-
_ID,
Bio
This is where I would welcome any helpful advice on my problem, or on how to improve my implementation.
Currently populating the DB as follows
long populateDB(){
String[] animalName = {"Lion" "Zebra", "Tiger", "Gorilla",...};
String[] animalBios = {"Found in the "...}
ContentValues animalNameVals = new ContentValues();
ContentValues animalBioVals = new ContentValues();
long[] rowIds = new long[animalName.length];
// Populate the animal table
for(int i = 0; i < animalName.length; i++){
animalNameVals.put(KEY_ANIMALNAME, animalName[i]);
rowIds[i] = db.insert(ANIMAL_TABLE, null, animalNameVals);
}
// Populate the Bio table
for(int j = 0; j < bios.length; j++){
animalBioVals.put(KEY_BIO, bios[j]);
rowIds[j] = db.insert(BIOS_TABLE, null, animalBioVals);
}
return rowIds[0];
}
And had planned on being able to tell database which animal on list was selected by passing extras with the intent, eg if position on listItemClick == 1, pass in tiger and retrieve tiger bio from db.
Problems:
Then on the Animal activity page is getExtra() == tiger, telling the activity that tiger was selected from the list and to load this bio from the DB..well, I cannot see an efficient method of implementation for this idea and am struggling to do so.
My second headache comes from adding the bio to the application from the Db.Originally I had a test bio hardcoded in a string, shown in a TextView.Is there a way to retrieve a string from a cursor and add it to the TextView id?I understand I will need some adapter, what I do not understand is why cant it be as simple as setResource(R.id.bio) = bio.
Thanks you for reading and any help is much appriciated.
First problem: First of all, I'm not sure why you don't have the column Bio in the Animal-table? As no Bio would fit to any other animal than itself, you can safely do this. By doing this you can query the database upon selection and pass the entire object (including name of animal and bio) to the next Activity and use this to get your information. If this was somewhat unclear, let me know and I'll try to explain it better.
Second problem: You can get values from tables (there of also Strings) using a Cursor. To get the String you can do something like this where cursor is the Cursor with your result from the database:
String bio;
// Move Cursor to its first element
if(cursor.moveToFirst()) {
// Make sure the cursor is not null
if(cursor != null) {
bio = cursor.getString(cursor.getColumnIndex("Bio")));
}
}
Sidenote: If I read the code correctly, it seems that you use long for ID's? The usual thing to go about ID's is integers as far as I know.

Categories

Resources