This is the code of my Connection Class, but the connection is not getting established. Whenever I print con I get null , Can anyone tell me where I went wrong? I included the jtds-1.3.1.jar in lib folder of app. I am unable to understand where I went wrong
package com.jazzitup.music;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
import net.sourceforge.jtds.jdbc.*;
public class ConnectionClass {
#SuppressLint("NewApi")
public static Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:sqlserver://jazzitup.database.windows.net:1433;database=jazzitup.db;user=xxxxxxxx;password=xxxxxx;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
System.out.println("CON:"+conn);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
}
It's preferable (or a must i think) to use web services to access your data base from the device and not using a direct connection . Not every lib for java works with andoid .
1.First of all make class that extend SQLiteOpenHelper
2.Create a contractor for that class and implement all the function that needed .
On the method
onCreate((SQLiteDatabasedb)
Just create String called query
and create the table you want , and execSql it , for example :
String query="create table if not exists table(text text,name text2,_id text)";
db.execSQL(query);
Then for create new row in the sql lite use :
public void add_new_row(String text,String text2,String _id){
try{
ContentValues cn=new ContentValues();
cn.put("text",per_name);
cn.put("text2",per_age);
cn.put("_id",per_age);
SQLiteDatabase db;
db=getWritableDatabase();
db.insert("table",null,cn);}
catch(Exception e){
Log.i("AddSql_lite","Print :"+e.to );
}
And for read Row from sqllite you just use :
public String getRow_by_id(String _id){
string text = "";
try{
db=getWritableDatabase();
query="select * from table where _id = '"+_id+"'";
Cursor cr=db.rawQuery(query, null);
if(cr.moveToFirst()){
do{
text = cr.getString(0);
String text2 = cr.getString(1);
String _id = cr.getString(2);
}while(cr.moveToNext());
}
}catch(Exception e){
}
return text;
}
And for reading all the rows in the table one after another :
public int get_all_Rows(){
string int counter = 0;
try{
db=getWritableDatabase();
query="select * from table";
Cursor cr=db.rawQuery(query, null);
if(cr.moveToFirst()){
do{
text = cr.getString(0);
String text2 = cr.getString(1);
String _id = cr.getString(2);
counter++;
}while(cr.moveToNext());
}
}catch(Exception e){
}
return counter;
}
Hope its will help you to understand how Sqllite work and how build it correctly :)
And for make it run so just :
SQLiteDataBase Sqllite_ref = new SQLiteDataBase(context, "VerName",
null, 1);
Sqllite_ref.add_new_row("hey","hey4","1");
Sqllite_ref.add_new_row("hey2","hey5","2");
Sqllite_ref.add_new_row("hey3","hey6","3");
Sqllite_ref.getRow_by_id("2");>>> will return "hey2"
Sqllite_ref.get_all_Rows()>>> will return 3 [number of items you have
in the sqllite]
Related
I have created a Sugar ORM database successfully in my app, I can update, delete and also get all data from a row, but I want a single column data matched with another data...
I mean, I have a registration database with fields: username, password, first_name, last_name, email fields.
After login a user with right username and password, I want THAT User's First_Name in a Textview sent to the Next Activity...
How can I do this? Over last two days I have tried but failed, please help me...
Thanks in advance...
public static List<String> getResultWithRawQuery(String rawQuery, Context mContext) {
List<String> stringList = new ArrayList<>();
if (mContext != null) {
long startTime = System.currentTimeMillis();
SugarDb sugarDb = new SugarDb(mContext);
SQLiteDatabase database = sugarDb.getDB();
try {
Cursor cursor = database.rawQuery(rawQuery, null);
try {
if (cursor.moveToFirst()) {
do {
stringList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
Timber.d(cursor.getString(0), "hi");
} finally {
try {
cursor.close();
} catch (Exception ignore) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("total time query" + totalTime);
}
return stringList;
}
Another example that returns a List of values in the column. Use as such:
String rawQuery = ("SELECT feed_key FROM team_feed_key WHERE team_id = " + mTeam_id + " ORDER BY feed_key DESC");
Did you try to run a raw query like this?
List<Note> notes = Note.findWithQuery(Note.class, "Select * from Note where name = ?", "satya");
from: http://satyan.github.io/sugar/query.html
you can add function to SugarRecord.java forever
public static String Scaler(String Query) {
String Result = "";
SugarDb db = getSugarContext().getSugarDb();
SQLiteDatabase sqLiteDatabase = db.getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
or
public static String Scaler(String Query) {
String Result = "";
SQLiteDatabase sqLiteDatabase = SugarContext.getSugarContext().getSugarDb().getDB();
SQLiteStatement sqLiteStatament = sqLiteDatabase
.compileStatement(Query);
try {
Result = sqLiteStatament.simpleQueryForString();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqLiteStatament.close();
}
return Result;
}
Scaler("Select First_Name from Note where name ='ali' limit 1");
I had the same problem.
I hope this helps someone:
String firstName = Select.from(User.class).where("EMAIL = "+ user.getEmail()).first().getFirstName();
Hi this must work you can not edit the libraries but you can extend them so check this out:
public class DBUtils extends SugarRecord {
public static <T> List<Object> findByColumn(Context context, String tableName,T ColumnObjectType, String columnName) {
Cursor cursor = new SugarDb(context).getDB().query(tableName, new String[]{columnName}, null, null,
null, null, null, null);
List<Object> objects = new ArrayList<>();
while (cursor.moveToNext()){
if (ColumnObjectType.equals(long.class) || ColumnObjectType.equals(Long.class)) {
objects.add(cursor.getLong(0));
}else if(ColumnObjectType.equals(float.class) || ColumnObjectType.equals(Float.class)){
objects.add(cursor.getFloat(0));
}else if(ColumnObjectType.equals(double.class) || ColumnObjectType.equals(Double.class)){
objects.add(cursor.getDouble(0));
}else if(ColumnObjectType.equals(int.class) || ColumnObjectType.equals(Integer.class)){
objects.add(cursor.getInt(0));
}else if(ColumnObjectType.equals(short.class) || ColumnObjectType.equals(Short.class)){
objects.add(cursor.getShort(0));
}else if(ColumnObjectType.equals(String.class)){
objects.add(cursor.getString(0));
}else{
Log.e("SteveMoretz","Implement other types yourself if you needed!");
}
}
if (objects.isEmpty()) return null;
return objects;
}
}
The usage is simple use DBUtils.findByColumn(...);
Any where you like and from now on you can use only this class instead of SugarRecord and add your own other functions as well.
hint:
ColumnObjectType as the name Suggest tells the type of column like you send Integer.class
I am storing data into SQLiteDatabase which is stored into SD Card, now i have to send all SQLite data to server.
Note: I have created same fields to server database as well (simillar to SQLite DB) for an eg: PersonName
Below code i used to check, am i able to store data to server (for testing purpose - i accepted data by user into edittext) and then sent to server, and i was successful in that.
String url = "http://localhost/ChurchData.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sPersonName", editPersonName.getText().toString()));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// prepare save data
if(strStatusID.equals("0"))
{
Toast.makeText(getApplicationContext(), "Already Exist !", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Data Uploaded Successfully!", Toast.LENGTH_SHORT).show();
}
return true;
}
private String getHttpPost(String url,
List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
So may i know, How can i send SQLite database records to server ? My database class looks like this:
public class myDBClasss extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "ChurchDB";
// Table Name
private static final String TABLE_MEMBER = "DataTable";
public myDBClasss(Context context) {
// to store data into SD Card
super(context, Environment.getExternalStorageDirectory()
+ File.separator + "ChurchData"
+ File.separator + DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// Create Table Name
db.execSQL("CREATE TABLE " + TABLE_MEMBER +
"(PersonName VARCHAR(100)," +
" PersonEmail VARCHAR(100)," +
" PersonTelephone VARCHAR(100)," +
" Newsletter VARCHAR(100));"); // checkbox
Log.d("CREATE TABLE","Create Table Successfully - classs");
}
// Insert Data
public long insertData(String strPersonName, String strPersonEmail, String strPersonTelephone, String strNewsletter) {
// TODO Auto-generated method stub
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("PersonName", strPersonName);
Val.put("PersonEmail", strPersonEmail);
Val.put("PersonTelephone", strPersonTelephone);
Val.put("Newsletter", strNewsletter); // checkbox
long rows = db.insert(TABLE_MEMBER, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
// Update Data
public long updateData(String strPersonName, String strPersonEmail, String strPersonTelephone, String strNewsletter){
// TODO Auto-generated method stub
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("PersonName", strPersonName);
Val.put("PersonEmail", strPersonEmail);
Val.put("PersonTelephone", strPersonTelephone);
Val.put("Newsletter", strNewsletter); // checkbox
long rows = db.update(TABLE_MEMBER, Val, "PersonName=?",
new String[] { String.valueOf(strPersonName) });
db.close();
return rows; // return rows updated.
} catch (Exception e) {
return -1;
}
}
// Fetch data
public String[] selectData(String strPersonName) {
// TODO Auto-generated method stub
try {
String arrData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_MEMBER, new String[] { "*" },
"PersonName=?",
new String[] { String.valueOf(strPersonName) }, null, null, null, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
arrData = new String[cursor.getColumnCount()];
arrData[0] = cursor.getString(0);
arrData[1] = cursor.getString(1);
arrData[2] = cursor.getString(2);
arrData[3] = cursor.getString(3); // checkbox
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
// Check for data(s) using PersonName field
public boolean exists(String strImageName) {
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.rawQuery("select 1 from DataTable where PersonName= ?",
new String[] { strImageName });
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
// Re Create on method onCreate
onCreate(db);
}
}
I think easy way is that you convert all your sqlite data into xml or json and then only one http request is required to send all your data to online server. At online server you can easily parse your data as you already know the structure of your xml or json whatever you used.
let say you have 2 fields in your database. ID , Name. you have 10 records. you convert all your records into json .
let say you query your database for all records and now cursor object will hold all your sqlite data.
add getAllData() method to retrieve all your database data.
public Cursor getAllData() {
String selectQuery = "Select * from "+TABLE_MEMBER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
now do,
Cursor cursor = getAllData(); //cursor hold all your data
JSONObject jobj ;
JSONArray arr = new JSONArray();
cursor.moveToFIrst();
while(cursor.moveToNext()) {
jobj = new JSONObject();
jboj.put("Id", cursor.getInt("Id"));
jboj.put("Name", cursor.getString("Name"));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
String st = jboj.toString();
now simply make an http call with string parameter and send to server.and parse at server by converting this string into jsonobject.
now according to your code, do
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("allData", st));
String resultServer = getHttpPost(url,params);
I have some snippet of code just for your idea.If it help you it my pleasure.
protected void startSync(Context aContext) {
try {
AccountManager am = AccountManager.get(getBaseContext());
Account[] ac = am.getAccountsByType(Constants.ACCOUNT_TYPE);
if (ac.length > 0) {
Toast.makeText(SuperHomeActivity.this,
"Synchronization Started", Toast.LENGTH_SHORT).show();
List<PeriodicSync> aList = ContentResolver.getPeriodicSyncs(
ac[0], Constants.AUTHORITY);
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, false);
if (aList != null && aList.size() > 0) {
while (aList != null && !aList.isEmpty()) {
ContentResolver.removePeriodicSync(ac[0],
Constants.AUTHORITY, aList.get(0).extras);
aList.remove(0);
}
}
// mention only in seconds -> 120 minutes 60 seconds
ContentResolver.addPeriodicSync(ac[0], Constants.AUTHORITY,
bundle, 5 * 60); //15
ContentResolver.requestSync(ac[0], Constants.AUTHORITY, bundle);
}
} catch (Exception ex) {
Log.e("SyncAccountTriggerError", ex.getMessage());
}
}
And you can call it by
startSync(getApplicationContext());
For any more clarification you can ping me.
you can use Http Post method or Get method or if you directly wants to update your server DB then use Put method. You can send data by http request with NameValue pair and just get that data from server and update your DB. That's it.
This is my problem: I have an SQLite DB set up to store some values. In this case, its pretty simple. Two columns (_id, name). I know data is getting stored in the database and I know the cursor I am using to pass that information is also populating. However, when I try to add a cursor value to an ArrayList, I get an error. This is the code for my problem method:
public void sqltest(LDatabase LConnector){
cursor = LConnector.getAllRecords(); //gets the cursor from my db
try{
cursor.moveToFirst();}
catch (Exception e){
log.i("Failed", "Couldn't moveToFirst"); //I get a successful moveToFirst
}
while(cursor.moveToNext()){
try{
getWork.add(cursor.getString(cursor.getColumnIndex("name")));
} catch (Exception h){
Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));
}
}
I set up that last log to tell me the value of the cursor at that position. The values entered for the DB always print out so I know the cursor is being populated. Anyone have any idea what I am doing wrong here?
EDIT: LogCat shows these two lines after this is called when an activity starts:
04-12 23:26:26.606: I/MOVED(9478): MOVED TO FIRST
04-12 23:26:26.606: I/FAILED(9478): test1
There are no more verbose errors that describe it better, that is why I am so confused. It just doesn't get stored to the AssetList at all.
This is the code for the getAllRecords() mehod:
public Cursor getAllLifts() throws SQLiteException
{
open();
return database.rawQuery("SELECT * FROM contacts"+";", null);
}
Additionally, here is the create code + the code used for inserting:
Create:
String createQuery = "CREATE TABLE contacts" +
"(_id auto_increment integer primary key," +
"name text);";
db.execSQL(createQuery); // execute the query
Insert:
open(); // open the database
try{
//add more later to get data to insert from usr, just for testing
database.execSQL("INSERT INTO contacts(name) VALUES('test1')");
database.execSQL("INSERT INTO contacts(name) VALUES('test2')");}
catch (Exception insert){
Log.i("INSERT", "INSERT FAILED");
}
close(); // close the database
EDIT: rest of the activity w/ imports
package com.jydev.llogger2;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.database.Cursor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Create extends Activity implements OnClickListener {
Button buttonNext; //continue button
Button buttonBack; //back button
EditText nameEditText; //editText w/ workout name
EditText commentEditText; //editText w/ comments
Intent info; //intent used to pass extras
String wName = null;
String wComments = null;
ArrayList<String> getWork;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
commentEditText = (EditText)findViewById(R.id.commentEditText);
buttonBack = (Button)findViewById(R.id.create_back);
buttonNext = (Button)findViewById(R.id.create_continue);
nameEditText = (EditText)findViewById(R.id.nameEditText);
LtDatabase LConnector = new LDatabase(this);
LConnector.insert();
sqltest(LConnector);
}
There are several wrong things. First moveToFirst() returns a boolean so you will never get an exception thrown. Second the while statement will skip one row since you call moveToNext(), thus the first row is skipped. Finally, you get an exception because you did not initialize getwork.
public void sqltest(LDatabase LConnector)
{
cursor = LConnector.getAllRecords(); //gets the cursor from my db
if (cursor.moveToFirst())
{
do
{
try{
getWork.add(cursor.getString(cursor.getColumnIndex("name")));
} catch (Exception h){
Log.i("FAILED", cursor.getString(cursor.getColumnIndex("name")));
}
while (cursor.moveToNext());
}
}
}
In your declaration of getWork
ArrayList<String> getWork = new ArrayList<String>();
for my queries i'm using the following
public ArrayList<T> findAllBy(String selection) {
final SQLiteDatabase db = HELPER.getReadableDatabase();
final ArrayList<T> result = new ArrayList<T>();
final Cursor cursor = db.query(TABLE_NAME, SELECTED_COLS, WHERE, null, null, null, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
T model = CREATEOBJECT(cursor);
result.add(model);
cursor.moveToNext();
}
return result;
} finally {
cursor.close();
db.close();
}
}
Where:
HELPER is a instance extendes from SQLiteOpenHelper
TABLE_NAME is a string with the name of the table
SELECTED_COLS is a String[] array with the columns names i want get
WHERE is a string like "COL_NAME = 'value'" or null
CREATEOBJECT is a method for create Object of type T want in my ArrayList<T>
Example CREATEOBJECT
public T CREATEOBJECT(Cursor cursor) {
new T(
cursor.getInt(0), cursor.getString(1)
);
}
public class T {
private long id;
private String name;
T(int id, String name) {
this.id = id;
this.name = name;
}
//...
}
I am trying to develop a quiz app for physics, but I keep getting the error
02-23 16:02:06.006: E/Database(9348): on sqlite3_open_v2("data/data/com.mcq.srm/databases/q.db", &handle, 1, NULL) failed
Code Snippet below
public class QuestionPane extends Activity {
int counter =00;
RadioButton radioButton;
TextView Question;
TextView tvScore;
Button Next;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionpane);
int resdb=0;
try {
SQLiteDatabase checkDB = null;
String DB_FULL_PATH = "data/data/com.mcq.srm/databases/q.db";
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
//Toast.makeText(this,"db "+checkDB, Toast.LENGTH_LONG).show();
resdb=0;
Log.v("msg","Database created");
} catch (Exception e){
resdb=1;
}
Log.v("msg", "check res-->"+resdb);
try{
db = openOrCreateDatabase("q.db" , SQLiteDatabase.CREATE_IF_NECESSARY , null );
if(resdb==1)
{
Log.v("msg","creating tables");
CreateTable();
InsertData();
displayres();
}
}
catch(Exception e){
}
}
public void CreateTable(){
String Createtab;
Createtab =" CREATE TABLE tbl_Question ("+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, Questions TEXT, option_1 TEXT,option_2 TEXT, option_3 Text, option_4 TEXT, correct_answer TEXT);";
try{
db.execSQL(Createtab);
}
catch(Exception e){
}
}
public void InsertData(){
ContentValues values = new ContentValues();
values.put("question", "Two beams of red and violet colours are made to pass separately through a prism of A = 60°. In the minimum deviation position, the angle of refraction inside the prism will be");
//... value.put statements removed
db.insert("tbl_Question", null, values);
//.. values.put statements removed
values.put("correct_answer","35 grams");
db.insert("tbl_Question", null, values);
}
public void displayres() {
int qno=1;
String sql1="select * from question;";
Cursor c1=db.rawQuery(sql1,null);
Log.v("answer","asd");
String que,opt1,opt2,opt3,opt4;
startManagingCursor(c1);
c1.moveToFirst();
que=c1.getString(c1.getColumnIndex("Question1"));
Log.v("answer",que);
}
}
There are lot of mistakes in your I'll suggest you go through this example, it's best to start with that example in android.You need to create separate class for Database generally know as Database Adapter and one more that is Database Helper by Android Devs. So to get complete idea go through that example.
I am new to android . I have an application working with SQLite DB.
I need to push values from database to an arraylist of type object.
The code i used is given here.
private ArrayList<objectname> objectList = new ArrayList<objectname>();
//function used to get values from database
public ArrayList<objectname> getResults() {
MyDb db = new MyDb(this); //my database helper file
db.open();
Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
if (c.moveToFirst())
{
do {
String date = c.getString(c.getColumnIndex("date"));
try
{
ob = new objectname();
ob.setDate(c.getString(c.getColumnIndex("date")));// setDate function is written in Class file
objectList.add(ob);
}
catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
} while (c.moveToNext());
}
db.close();
return objectList;
}
This is not working correctly. Not shown any errors but i didn't get values in to the arraylist objectList
Please help me..Thanks in advance..
try this:
private ArrayList<objectname> objectList = getResults();
private ArrayList<objectname> getResults() {
MyDb db = new MyDb(this); //my database helper file
db.open();
ArrayList<objectname> resultList = new ArrayList<objectname>();
Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
while (c.moveToNext())
{
String date = c.getString(c.getColumnIndex("date"));
try
{
ob = new objectname();
ob.setDate(date);// setDate function is written in Class file
resultList.add(ob);
}
catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
}
c.close();
db.close();
return resultList;
}
I had a similar issue with retrieving values from the db using cursors and displaying on screen.. The below solution works for me..
Cursor cur = db.getAllValues();
int index = c.getColumnIndex("date");
cur.moveToFirst();
while (cur.isAfterLast() == false) {
System.out.println(cur.getString(index)); // For debug purposes
String date = cur.getString(index);
try {
ob = new objectname();
ob.setDate(date);
resultList.add(ob);
} catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
cur.moveToNext();
}
cur.close();
Probably your query is drawing a blank and moveToFirst is returning false.
What about logging the value of c.getCount() before your if statement?