Method in Recyclerview is being called everytime i scroll - sqlite

I am using SQLite Database to store some value/items from recyclerview which are coming from Firebase by long press. And in that recyclerview i am changing background of the values/items which are already stored in SQLite database. But problem is that when I long press on any item, it also colors every 21st item in recyclerview. and then colors any random item when scrolling back to top.
OnBindView
holder.Card.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (favDB.isFav(model.getUrl(), model.getName())) {
Toast.makeText(getContext(), "Already in Favorite", Toast.LENGTH_SHORT).show();
} else {
new FavDB(getContext()).addToFav(
model.getName(), model.getType(), model.getUrl(),
model.getBrowser(), model.getImage());
holder.Card.setCardBackgroundColor(R.color.Background);
Toast.makeText(getContext(), "Added to Favorite", Toast.LENGTH_SHORT).show();
}
return true;
}
});
if (favDB.isFav(model.getUrl(), model.getName())) {
try {
Toast.makeText(getContext(), "Coloring", Toast.LENGTH_SHORT).show();
holder.Card.setCardBackgroundColor(R.color.Background);
favDB.close();
}catch (Exception e){
Toast.makeText(getContext(), "Error : " + e, Toast.LENGTH_SHORT).show();
}
}
SQLite Helper
public void addToFav(String name, String type, String url, String browser, String image) {
SQLiteDatabase favDatabase = getReadableDatabase();
String favAdd =
String.format("INSERT INTO fav(name,url) VALUES('%s','%s');",
name, type, url, browser, image);
favDatabase.execSQL(favAdd);
favDatabase.close();
}
public boolean isFav(String url, String name) {
SQLiteDatabase favDatabase = getReadableDatabase();
String masterQuery = String.format("SELECT * FROM fav WHERE (url= '%s' AND name = '%s')",
url, name);
Cursor cursor = favDatabase.rawQuery(masterQuery, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
favDatabase.close();
return true;
}

Related

How can we insert date into the SQLite database

For each data insert in SQLite database, I would like to get insert the current Date as well. How can I do it in Xamarin Forms app ?
Below is my code which now insert some status data into the database.
public void OnOKButtonClicked(object sender, EventArgs e)
{
overlay.IsVisible = false;
DisplayAlert("Result",
string.Format("You entered {0}", EnteredStatus.Text), "OK");
SoccerAvailability soccerAvailability = new SoccerAvailability();
soccerAvailability.SoccerStatus = EnteredStatus.Text;
var dailySoccerStatus = EnteredStatus.Text;
int x = 0;
try
{
if (!string.IsNullOrWhiteSpace(EnteredStatus.Text))
{
//Insert the soccer status to the database:
x = conn.Insert(soccerAvailability);
}
else
{
DisplayAlert("Soccer Availability", "Availability cannot be left blank", "OK");
}
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
Navigation.PushAsync(new Settings(soccerAvailability));
}
DisplaySoccerStatus();
}
just create a CurrentDate DateTime property on your SoccerAvailability model
soccerAvailability.CurrentDate = DateTime.Now;
x = conn.Insert(soccerAvailability);

get value of checked checkbox created dynamically

in this i m fetching data from database i.e. question and answer and accordingly numbers of answer in the database equals to number of checked box created dynamically and i want that the when the user checked the checked box the value of that checked box must me save in sqlite database
public class Multiselect extends Fragment
{
TextView ques;
DefaultHttpClient httpclient;
HttpPost httppost;
HttpResponse httpResponse;
HttpEntity httpEntity;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
String result = null;
StringBuilder sb=null;
BufferedReader reader;
JSONArray jArray;
String line;
String question;
String answer;
int questionno;
int i;
View view;
Context context;
int id=1;
CheckBox checkboxbutton;
final CheckBox[] checkboxbuttons = new CheckBox[50];
LinearLayout l;
//DatabaseMultiselect db;
String text;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.multiselect, container, false);
l=(LinearLayout)view.findViewById(R.id.l1);
/*String l1=l.toString();
String strtext=getArguments().getString("next");
Log.e("str",strtext);*/
StrictMode.enableDefaults();
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//db=new DatabaseMultiselect(getActivity());
// db.open();
getMultiselect();
getAnswer(container);
Log.e("id",""+id);
Log.e("count",""+l.getChildCount());
return view;
}
void getMultiselect()
{
try
{
httpclient=new DefaultHttpClient();
// httppost= new HttpPost("http://10.0.2.2/multiselectandroid.php");
httpResponse = httpclient.execute(httppost);
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
ques.setText("error!!");
}
//convert response to string
try
{
reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
questionno=json_data.getInt("question_no");
question=json_data.getString("question");
Log.e("question",question);
//s=s+""+question;
}
ques.setText(question);
}
catch(JSONException excep)
{
excep.printStackTrace();
//Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
}
catch (ParseException excep)
{
excep.printStackTrace();
}
}
void getAnswer(ViewGroup container)
{
try
{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/multiselectanswer.php?questionno="+questionno);
httpResponse = httpclient.execute(httppost);
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
ques.setText("error!!");
}
//convert response to string
try
{
reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//pairing data
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
answer=json_data.getString("answer");
checkboxbuttons[i] = new CheckBox(container.getContext());
checkboxbuttons[i].setId(id);
l.addView(checkboxbuttons[i]);
checkboxbuttons[i].setText(answer);
checkboxbuttons[i].setTextColor(Color.RED);
int rid=checkboxbuttons[i].getId();
Log.e("rid",""+rid);
id++;
}
/* if(id.getCheckedRadioButton==true)
{
String selected=chk;
Log.e("select",selected);
}*/
}
catch(JSONException excep)
{
excep.printStackTrace();
//Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
}
catch (ParseException excep)
{
excep.printStackTrace();
}
}
}
public class Multiselect extends Fragment
{
//Declaring variables
TextView ques;
TextView condition;
TextView sectionidtext;
TextView instructions;
String instructionset;
int question_no;
String question1;
String surveyName;
String selectedQues;
String username;
int min_answers;
int max_answers;
int id=1;
DatabaseHandler db;
String rating=null;
View view;
final CheckBox[] answercheckbox = new CheckBox[50];
LinearLayout answersettinglayout;
String answertext;
int count=0;
String limit;
String sectionids;
String date=null;
String time=null;
String tablename="multiselect";
String input_answer=null;
String userid;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Getting Question number,user name,survey name,questionnaire name and user id value
Bundle mulitselectBundle=getArguments();
question_no=mulitselectBundle.getInt("questionnum");
surveyName=mulitselectBundle.getString("surveyname");
selectedQues=mulitselectBundle.getString("quesname");
username=mulitselectBundle.getString("username");
userid=mulitselectBundle.getString("userid");
Log.e("mulitselect"," "+question_no);
Log.e("mulitselect",surveyName);
Log.e("mulitselect",selectedQues);
Log.e("mulitselect",username);
Log.e("mulitselect",userid);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.multiselect, container, false);
//Getting id of Linear Layout for answers
answersettinglayout=(LinearLayout)view.findViewById(R.id.answersetting);
//Getting id of text view for question
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//Getting id of textview for conditions
condition=(TextView)view.findViewById(R.id.conditionmulti);
//Getting id of textview for section id
sectionidtext=(TextView)view.findViewById(R.id.sectionidmultiselect);
//Getting id of text view for instructions display
instructions=(TextView)view.findViewById(R.id.instructionmultiselect);
//Create object of database
db=new DatabaseHandler(getActivity());
//Function call
retrieveQuestion();
getAnswer(container);
getcheckedCheckBoxes();
return view;
}
void retrieveQuestion()
{
//Open database
db.open();
Log.e("inside","retrieve question");
//Fetching value of question and section id
Cursor questioncursor=db.getQuestion(username,surveyName,selectedQues,question_no);
int length=questioncursor.getCount();
Log.e("length",""+length);
//Getting question and section id
if(questioncursor.moveToFirst())
{
//Getting column number
int indexquestion=questioncursor.getColumnIndex("question");
Log.e("index",""+indexquestion);
//Getting value of question and section id
question1= questioncursor.getString(indexquestion);
sectionids=questioncursor.getString(questioncursor.getColumnIndex("ques_id"));
//Setting question
ques.setText(question1);
Log.e("question",question1);
//Setting section id
sectionidtext.setText("Q."+sectionids);
}
//Closing cursor
questioncursor.close();
}
void getAnswer(ViewGroup container)
{
//Open database
db.open();
Log.e("inside","answer question");
//Fetching answers
Cursor answergettingcursor=db. getAnswer(username,surveyName,selectedQues,question_no);
//Declaring variable
int i=0;
//Getting answer value
while(answergettingcursor.moveToPosition(i))
{
//Getting column number
int indexanswer=answergettingcursor.getColumnIndex("answer");
//creating check boxes
answercheckbox[i] = new CheckBox(container.getContext());
//Setting id of check boxes
answercheckbox[i].setId(id);
//Adding check boxes in layout
answersettinglayout.addView(answercheckbox[i]);
//Setting answer value
answercheckbox[i].setText(answergettingcursor.getString(indexanswer));
//Setting text color
answercheckbox[i].setTextColor(Color.RED);
int rid=answercheckbox[i].getId();
Log.e("rid",""+rid);
//Incrementing value
id++;
i++;
}
//Closing cursor
answergettingcursor.close();
}
void getcheckedCheckBoxes()
{
Log.e("id",""+id);
Log.e("count",""+answersettinglayout.getChildCount());
//Fetching value of minimum and maximum characters
Cursor checkcondition=db.getmultiselecttabledata(username, surveyName, selectedQues, question_no);
//For Conditions
if(checkcondition.moveToFirst())
{
//Getting column number
int indexmin_answers=checkcondition.getColumnIndex("min_answers");
int indexmax_answers=checkcondition.getColumnIndex("max_answers");
Log.e("indexanswer",""+indexmin_answers);
Log.e("indexanswer1",""+indexmax_answers);
//Getting value of minimum and maximum characters and instructions
min_answers=checkcondition.getInt(indexmin_answers);
max_answers=checkcondition.getInt(indexmax_answers);
instructionset=checkcondition.getString(checkcondition.getColumnIndex("instructions"));
Log.e("texttableview",""+min_answers);
Log.e("texttableview",""+max_answers);
//Setting value of instructions
instructions.setText(instructionset);
//For answers
for(int k=0;k<answersettinglayout.getChildCount();k++)
{
//Whether check box checked or not
answercheckbox[k].setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//If check box checked
if(((CheckBox) v).isChecked())
{
//Incrementing value of count
count++;
Log.e("count",""+count);
//Getting value of checked check box
answertext=((CheckBox) v).getText().toString();
Log.e("checkbox",""+answertext);
//Checking min and max character conditions
if(count>=min_answers)
{
if(count>max_answers)
{
//Setting text
condition.setText("Selected answers exceeds maximum length");
//Setting text color
condition.setTextColor(Color.RED);
//Setting value of limit
limit="max";
}
else
{
//Setting text
condition.setText("");
//Setting value of limit
limit="proper";
}
}
else
{
//Setting text
condition.setText("Please select more answers");
//Setting text color
condition.setTextColor(Color.RED);
//Setting value of limit
limit="min";
}
//Inserting answers
db.insertAnswer(userid,username,surveyName,selectedQues,question_no,question1,answertext,rating,input_answer,limit,date,time,sectionids,tablename);
}
//if unchecked check box
else
{
//Decreasing count value
count--;
Log.e("count",""+count);
//Getting value of checked check box
answertext=((CheckBox) v).getText().toString();
Log.e("checkboxdelete",""+answertext);
//Deleting unchecked check box value
db.deleteQuesMultiselect(userid,username, surveyName, selectedQues, question_no,answertext);
//Checking min and max character conditions
if(count>=min_answers)
{
if(count>max_answers)
{
//Setting text
condition.setText("Selected answers exceeds maximum length");
//Setting text color
condition.setTextColor(Color.RED);
}
else
{
//Setting text
condition.setText("");
}
}
else
{
//Setting text
condition.setText("Please select more answers");
//Setting text color
condition.setTextColor(Color.RED);
}
}
}
});
}
//Closing cursor
checkcondition.close();
}
}
}

Error connecting to databasehandler

I have a error regarding database as shown below:
E/CursorWindow(386): Bad request for field slot 0,-1. numRows = 1, numColumns = 63
here's my piece of code:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_IMAGE = "image";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_IMAGE + " BLOB,"
+ KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE,contact.getImageId());
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Methods getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,KEY_IMAGE,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Methods contact = new Methods(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))),
cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE)),cursor.getString(cursor.getColumnIndex(KEY_NAME)), cursor.getString(cursor.getColumnIndex(KEY_PH_NO)));
// return contact
cursor.close();
return contact;
}
// Getting All Contacts
public List<Methods> getAllContacts() {
List<Methods> contactList = new ArrayList<Methods>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Methods contact = new Methods();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setImageId(cursor.getBlob(1));
contact.setName(cursor.getString(2));
contact.setPhoneNumber(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
/*// Updating single contact
public int updateContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}*/
// Deleting single contact
public void deleteContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
Log.v("deleteContact", "Deleted row is: "+String.valueOf(contact.getID()));
}
void deleteAll(Methods contact)
{
SQLiteDatabase db= this.getWritableDatabase();
db.delete(TABLE_CONTACTS, null, null);
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
It would help to have more information here (a stack trace perhaps?). However it seems you're not providing an "id" when adding a contact. Consider making this column auto incrementing instead.
Last, if this is an Android question, your primary key column should be auto incrementing and should be called "_id", else make sure that this is given as a column name in any cursor returned from a query. Also check that your database has a table called "android_metadata" too.

Datatype mismatch for blob type blackberry

I have an exception that Datatype mismatch in this line
byte[] _data = (byte[])row.getBlobBytes(1);
and in the table I have the type of column 2 is BLOB.
public static UrlRsc getContentUrl(String name) {
UrlRsc elementRsc = null;
try {
Statement statement = DB
.createStatement("SELECT * FROM table where"
+ " Name='"
+ name + "'");
statement.prepare();
Cursor cursor = statement.getCursor();
Row row;
while (cursor.next()) {
row = cursor.getRow();
byte[]_data;
_data = row.getBlobBytes(1);
}
statement.close();
cursor.close();
} catch (DatabaseException dbe) {
System.out.println(dbe.toString());
} catch (DataTypeException dte) {
System.out.println(dte.toString());
}
return elementRsc;
}
Can any one help me ?
Hi i am using following code for save image in my local database and i got success. i just posted my 3 methods
Note: When i am inserting image into data base i changed that image in byte array then only i can save into that table
1)Table creation 2) table insertion 3)image retrieving from table
ContactImage_table creation
public ContactImageTableCreation(){
try{
Statement stmt=DATABASE.createStatement("create table if not exists 'ContactImage_table'(ID 'TEXT',image 'blob',NodeId 'TEXT')");
stmt.prepare();
stmt.execute();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Insert data into ContactImage_table
public void ContactImageTableInsertion(){
try{
Statement st=DATABASE.createStatement("insert into ContactImage_table (ID,Image,NodeId)values(?,?,?)");
st.prepare();
st.bind(1, "101");
st.bind(2, BYTE_ARRY);
st.bind(3,"103");
st.execute();
st.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
Retrieving data from ContactImage_table
public ContactImageTableDataRetriving(){
try{
Statement st=DATABASE.createStatement("select * from ContactImage_table");
st.prepare();
Cursor c=st.getCursor();
Row r;
int i=0;
while(c.next()){
r=c.getRow();
i++;
// ContactImageObject is a wrapper class for data handling
contactImageObj=new ContactImageObject();
contactImageObj.setId(r.getString(0));
byte[] decoded=r.getBlobBytes(1);
EncodedImage fullImage = EncodedImage.createEncodedImage(decoded, 0, decoded.length);
Bitmap b=fullImage.getBitmap();
contactImageObj.setImage(b);
// System.out.println("Successfully retrived");
if(i==0){
// System.out.println("No Records");
}
}
st.close();
}catch (Exception e) {
// System.out.println(e.getMessage());
}
}
just cross check your code with this code snippet hope you will get resolve all the best

How to insert an array of String in SQLite database in blackberry

I have a Database Manager class which is creating the SQLite Database.Now from another class, i am creating the instance of that class. Now how can i insert an array of string in the Database?
My Database Manager class code is like below:
public class DatabaseManager
{
public Database sqliteDb = null;
public DatabaseManager()
{
try
{
URI myURI = URI.create("/SDCard/databases/itemdb.db");
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement statement = sqliteDb.createStatement("CREATE TABLE if not exists SelectedItem (Name TEXT, Quantity TEXT)");
statement.prepare();
statement.execute();
statement.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(sqliteDb!=null)
{
sqliteDb.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void insertValues(String tableName, Hashtable ht)
{
try
{
Logger.out("Grocery", "it is comin here");
URI myURI = null;
try
{
myURI = URI.create("/SDCard/databases/itemdb.db");
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (MalformedURIException e)
{
e.printStackTrace();
}
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement dbStatement = sqliteDb.createStatement("INSERT INTO SelectedItem(Name,Quantity) " + "VALUES (?,?)");
Enumeration itemName = ht.keys();
Enumeration itemQty = ht.elements();
while(itemName.hasMoreElements())
{
Logger.out("Grocery", "more items");
String strName = itemName.nextElement().toString();
String strQty = itemQty.nextElement().toString();
Logger.out("Grocery", "name:" + " " + strName);
Logger.out("Grocery", "QTY:" + " " + strQty);
dbStatement.bind(1, strName);
dbStatement.bind(2, strQty);
Logger.out("Grocery", "Binded:::::::::");
dbStatement.execute();
dbStatement.reset();
Logger.out("Grocery", "Executed:::::::::");
}
dbStatement.close();
}
catch (DatabaseException e)
{
e.printStackTrace();
}
}
public void closeDb()
{
try
{
sqliteDb.close();
}
catch (DatabaseIOException e)
{
e.printStackTrace();
}
}
}
Now i am taking the name and quantity as a hash table. And in my main class, when i am pressing the button i am inserting the values in the database like below:
dbManager = new DatabaseManager();
dbManager.insertValues("SelectedItem", htItem);
Try this as following when ever you want to use another class method as globle then just declare it as static . genaral query for multiple row insertion is
INSERT INTO 'tablename' SELECT 'data1' AS 'column1', 'data2' AS
'column2' UNION SELECT 'data3', 'data4' UNION SELECT 'data5', 'data6'
UNION SELECT 'data7', 'data8'
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class SampleDatabase extends UiApplication
{
LabelField test;
String names[];
int ages[];
MainScreen screen = new MainScreen();
public static void main(String[] args)
{
SampleDatabase theApp = new SampleDatabase();
theApp.enterEventDispatcher();
}
public SampleDatabase()
{
ButtonField btn=new ButtonField("Click");
names=new String[10];
ages=new int[10];
for(int i=0;i<10;i++)
{
names[i]="Govind"+i;
ages[i]=i;
}
btn.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
synchronized (UiApplication.getEventLock()) {
databaseOperations.DatabaseManager();
databaseOperations.InsertDatabaseManager(names,ages);
}
}
});
screen.add(btn);
pushScreen(screen);
}
}
This is another class named as "databaseOperations.java"
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;
public class databaseOperations {
public static void DatabaseManager()
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
Statement s = d.createStatement( "CREATE TABLE if not exists 'People' ( " +
"'Name' TEXT, " +
"'Age' INTEGER )");
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void InsertDatabaseManager(String[] names,int ages[])
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
String query="INSERT INTO 'People' SELECT '"+names[0]+"' AS 'Name', "+ages[0]+" AS 'Age'";
String query2="";
for(int i=1;i<names.length;i++)
{
query2=query2+" UNION SELECT '"+names[i]+"', "+ages[i];
}
System.out.println(query+query2);
Statement s = d.createStatement(query+query2);
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Resources