I've got two activities. One is updating value in database from edittext and in the second activity i want put this value from database into textview. At the first time when i update value everything goes well but at the second time textview cant be updated and i see in the Textview value "0". When i gave breakpoints i see that my cursor didnt want to take value second time. Any suggestion what should i do ? It's problem with lifecycle of activity or what? There is my code. Any example or suggestion will be very helpful for me.
public class DzienPierwszy extends AppCompatActivity {
Button button;
OpenHelper1 mDb;
TextView pp1,pp2,pp3,s1,s2,s3,p1,p2,p3,pn,sr,pt,nd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.dzien_treningu);
p1 = (TextView) findViewById(R.id.p1);
p2 = (TextView) findViewById(R.id.p2);
p3 = (TextView) findViewById(R.id.p3);
s1 = (TextView) findViewById(R.id.s1);
s2 = (TextView) findViewById(R.id.s2);
s3 = (TextView) findViewById(R.id.s3);
pp1 = (TextView) findViewById(R.id.pp1);
pp2 = (TextView) findViewById(R.id.pp2);
pp3 = (TextView) findViewById(R.id.pp3);
pn = (TextView) findViewById(R.id.pn);
sr = (TextView) findViewById(R.id.sr);
pt = (TextView) findViewById(R.id.pt);
nd = (TextView) findViewById(R.id.nd);
Intent i = getIntent();
final String product = i.getStringExtra("cwiczenie ");
int lol1=0;
mDb = new OpenHelper1(this);
mDb.open();
// fetch data about 1 row in database table
Cursor test = mDb.fetchOneCwiczenie(product);
mDb.close();
if( test != null && test.moveToFirst() ){
//get value from column
lol1 = test.getInt(test.getColumnIndex("score"));
test.close();
}
p1.setText(String.valueOf(Math.round(lol1*0.55)));
p2.setText(String.valueOf(Math.round(lol1*0.79)));
p3.setText(String.valueOf(Math.round(lol1*0.67)));
s1.setText(String.valueOf(Math.round(lol1*0.67)));
s2.setText(String.valueOf(Math.round(lol1*0.91)));
s3.setText(String.valueOf(Math.round(lol1*0.79)));
pp1.setText(String.valueOf(Math.round(lol1*0.79)));
pp2.setText(String.valueOf(Math.round(lol1*1.03)));
pp3.setText(String.valueOf(Math.round(lol1*0.91)));
}
public void open(View view) {
Intent intent = new Intent(getApplicationContext(),TestActivity.class);
startActivity(intent);
}
}
public class OpenHelper1{
private static final String TAG = "TreningDbAdapter";
public DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final ContentResolver resolver =null;
private final Context mCtx;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "menadzerCwiczen1";
public static final String TABLE_CWICZENIA = "cwiczenia";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KIND = "kind";
public static final String KEY_URL = "url";
public static final String KEY_SCORE = "score";
public static final String KEY_SERIES = "series";
static final String PROVIDER_NAME = "com.example.jacek.gympartner.SQLite";
static final String URL = "content://" + PROVIDER_NAME + "/cwiczenia";
static final Uri CONTENT_URI = Uri.parse(URL);
private static HashMap<String, String> CWICZENIA_PROJECTION_MAP;
static final int CWICZENIA = 1;
static final int CWICZENIE_ID = 2;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenie", CWICZENIA);
uriMatcher.addURI(PROVIDER_NAME, "cwiczenia/#", CWICZENIE_ID);
}
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + TABLE_CWICZENIA + " (" +
KEY_ID + " integer PRIMARY KEY autoincrement," +
KEY_NAME + " TEXT," +
KEY_KIND + " TEXT," +
KEY_URL + " TEXT," +
KEY_SCORE + " TEXT," +
KEY_SERIES + " integer" +
");";
/*
#Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
mDb = dbHelper.getWritableDatabase();
return (mDb == null)? false:true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki','Klatka piersiowa','https://www.youtube.com/watch?v=bwnidT3CB_Q',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Pompki na poręczach','Triceps','https://www.youtube.com/watch?v=Cufsu3IHhCo',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Odwrotne wiosłowanie','Plecy','https://www.youtube.com/watch?v=8qCn76yKhro',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Spięcia brzucha leżąc','Górna część mięśni brzucha','https://www.youtube.com/watch?v=VVcm4LdmIwM',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Unoszenie kolan','Dolna część mięśni brzucha','https://www.youtube.com/watch?v=Htx9Z8ZkiCg',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Skręty tułowia','Mięśnie skośne brzucha','https://www.youtube.com/watch?v=i7smKA3mgBU',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Przysiady','Uda','https://www.youtube.com/watch?v=NEduXlZ8zSk&t',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Wspięcia na palce','Mięśnie łydek','https://www.youtube.com/watch?v=Wri0VppFWCY',0,3)");
db.execSQL("INSERT INTO "+TABLE_CWICZENIA+"("+KEY_NAME+","+KEY_KIND+","+KEY_URL+","+KEY_SCORE+","+KEY_SCORE+") VALUES('Podciąganie na drążku','Mięśnie łydek','https://www.youtube.com/watch?v=7hM1iriAxx8',0,3)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CWICZENIA);
onCreate(db);
}
}
public OpenHelper1(Context ctx) {
this.mCtx = ctx;
}
public OpenHelper1 open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public OpenHelper1 read() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getReadableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCwiczenie(String name,
String kind,
String url,
int score,
int series) {
mDbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_KIND, kind);
initialValues.put(KEY_URL, url);
initialValues.put(KEY_SCORE, score);
initialValues.put(KEY_SERIES, series);
return mDb.insert(TABLE_CWICZENIA, null, initialValues);
}
public void deleteCwiczenie(String name) {
mDb.execSQL("DELETE FROM " + TABLE_CWICZENIA + " WHERE " + KEY_NAME + "=\"" + name + "\";" );
}
public void updateScore1(Uri uri,String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public void updateScore(String name, int wynik) {
String str = "UPDATE "+TABLE_CWICZENIA+" SET "+KEY_SCORE+" = "+wynik+" WHERE "+KEY_NAME+" = '"+name+"'";
mDb.execSQL(str);
}
public boolean deleteAllCwiczenia() {
int doneDelete = 0;
doneDelete = mDb.delete(TABLE_CWICZENIA, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCwiczeniaByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllcwiczenia() {
Cursor mCursor = mDb.query(TABLE_CWICZENIA, new String[] {KEY_ID,
KEY_NAME, KEY_KIND, KEY_URL, KEY_SCORE, KEY_SERIES},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchOneCwiczenie(String name) {
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if(c != null) {
c.moveToFirst();
}
return c;
}
public Cursor fetchOneCwiczenie1(Uri uri,String name) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_CWICZENIA);
String query = "SELECT * FROM " + TABLE_CWICZENIA + " WHERE name='"+name+"'";
Cursor c = mDb.rawQuery(query,null);
if (c != null) {
// c.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI);
}
return c;
}
public void insertSomeCwiczenia() {
createCwiczenie("Pompki","Klatka piersiowa","https://www.youtube.com/watch?v=bwnidT3CB_Q",20,3);
createCwiczenie("Pompki na poręczach","Triceps","https://www.youtube.com/watch?v=Cufsu3IHhCo",0,3);
createCwiczenie("Odwrotne wiosłowanie","Plecy","https://www.youtube.com/watch?v=8qCn76yKhro",0,3);
createCwiczenie("Spięcia brzucha leżąc","Górna część mięśni brzucha","https://www.youtube.com/watch?v=VVcm4LdmIwM",0,3);
createCwiczenie("Unoszenie kolan","Dolna część mięśni brzucha","https://www.youtube.com/watch?v=Htx9Z8ZkiCg",0,3);
createCwiczenie("Skręty tułowia","Mięśnie skośne brzucha","https://www.youtube.com/watch?v=i7smKA3mgBU",0,3);
createCwiczenie("Przysiady","Uda","https://www.youtube.com/watch?v=NEduXlZ8zSk&t",0,3);
createCwiczenie("Wspięcia na palce","Mięśnie łydek","https://www.youtube.com/watch?v=Wri0VppFWCY",0,3);
createCwiczenie("Podciąganie na drążku","Mięśnie łydek","https://www.youtube.com/watch?v=7hM1iriAxx8",0,3);
}
}
public class TestActivity extends AppCompatActivity {
TextView textView;
EditText editText;
Button button,button1;
OpenHelper1 mDb;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.test_layout);
textView = (TextView) findViewById(R.id.polecenie);
editText = (EditText) findViewById(R.id.wartosc);
button = (Button) findViewById(R.id.treningactivity);
button1 = (Button) findViewById(R.id.zapisz);
//button2 = (Button) findViewById(R.id.button);
mDb = new OpenHelper1(this);
Intent i = getIntent();
// getting attached intent data
final String product = i.getStringExtra("cwiczenie ");
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int wynik = Integer.parseInt(editText.getText().toString());
mDb.open();
mDb.updateScore(product,wynik);
mDb.close();
}
});
/*
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDb.open();
Cursor t = mDb.fetchOneCwiczenie(product);
int c = t.getInt(t.getColumnIndex("score"));
String k = Integer.toString(c);
textView1.setText(k);
mDb.close();
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext().getApplicationContext(), DzienPierwszy.class);
i.putExtra("cwiczenie ", product);
startActivity(i);
}
});
}
}
There are more than couple of things that you need to do -
In your content provider, you need to attach a notification Uri before the Cursor is being returned to client (in this case your Activity). The code would look something like this (Here the Authority URI need to be changed as per your provider) -
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(),ContactsContract.AUTHORITY_URI);
}
return c;
Every time there is a update in data, the following line needs to be called -
getContext().getContentResolver().notifyChange(ContactsContract.AUTHORITY_URI, null,
syncToNetwork);
Basically what point 1 & 2 does is that it notifies the underlying data layer that there is currently a client with an active cursor and needs to be notified if there is a change in the underlying data. If you are using any of the inbuilt data providers in Android like ContactsProvider/SmsProvider to read contacts/SMS data, point 1 &2 would have been taken care.
ContactsProvider
And on your activity code you need to do something like
cursor.registerContentObserver(mChangeObserver). If you instead use a Cursor adapter which wraps around your cursor, then this would have been taken care. Have a look at the Cursor Adapter source code -
CursorAdapter Sample
Related
I apologize for conversation.
I am using Google Translator.
I am writing an application that displays text messages with specific numbers.
The numbers stored in the application's user.
*** My problem is that my app does not work on Android 4.4 and above.
Basically what I Should do ? thanks.
My step-by-step program :
Incoming sms:
public class IncomingSms extends BroadcastReceiver {
SmsManager smsManager = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentmessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentmessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentmessage.getDisplayMessageBody();
Log.i("payam", "senderNum=" + senderNum + " | msg=" + message);
DBAdapter db = new DBAdapter(context);
db.open();
List<sh_number> blocknumbers = db.getAllNUMBERItem();
db.close();
for (sh_number thisblocknumber : blocknumbers) {
if (senderNum.equals(thisblocknumber.getnumber())) {
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}
/*if(senderNum.equals("5554")){
Toast.makeText(context, "پیام دریافتی بلاک شد. ", Toast.LENGTH_LONG).show();
sh_msg thisMsg = new sh_msg();
thisMsg.setText(message);
thisMsg.setnumber(senderNum);
db.open();
db.insertSH_MSG(thisMsg);
db.close();
abortBroadcast();
}else {
Toast.makeText(context, "senderNum="+senderNum+" | msg="+message,Toast.LENGTH_LONG).show();
}*/
}
}
}
}
NumberListAdapter :
public class NumberListAdapter extends ArrayAdapter<sh_number> {
List<sh_number> AllNumbers;
Context c;
public NumberListAdapter(Context c, List<sh_number> numbrs){
super(c, android.R.id.content, numbrs);
AllNumbers = numbrs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_number, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getname());
txt = (TextView)convertView.findViewById(R.id.Itm_number);
txt.setText(AllNumbers.get(position).getnumber());
return convertView;
}
MassageListAdapter :
public class MsgListAdapter extends ArrayAdapter<sh_msg> {
List<sh_msg> AllNumbers;
Context c;
public MsgListAdapter(Context c, List<sh_msg> msgs){
super(c, android.R.id.content, msgs);
AllNumbers = msgs;
this.c = c;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater v1 = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertView == null) convertView = v1.inflate(R.layout.item_msg, null);
TextView txt = (TextView)convertView.findViewById(R.id.Itm_name);
txt.setText(AllNumbers.get(position).getnumber());
txt = (TextView)convertView.findViewById(R.id.Itm_msg);
txt.setText(AllNumbers.get(position).getText());
txt = (TextView)convertView.findViewById(R.id.Itm_date);
txt.setText(AllNumbers.get(position).getDate());
return convertView;
}
Database :
public class DBAdapter {
public static final String DATABASE_NAME = "smsblkrdb";
static final int DATABASE_VERSION = 1;
static final String CREATE_MSGTABLE = "CREATE TABLE msgsTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" numberid integer(128),\n" +
"\"text\" text(128),\n" +
" date text(128)\n" +
");";
public static final String DATABASE_MSGTABLE = "msgsTable";
public static final String KEY_ID = "id";
public static final String KEY_NUMBERID = "numberid";
public static final String KEY_TEXT = "text";
public static final String KEY_DATE = "date";
static final String CREATE_NUMBERSTABLE = "CREATE TABLE numbersTable (\n" +
" id integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
" name text(128),\n" +
" number text(128)\n" +
");";
public static final String DATABASE_NUMBERSTABLE = "numbersTable";
public static final String KEY_NAME = "name";
public static final String KEY_NUMBER = "number";
public static final String TAG = "EsfanduneLrn";
DatabaseHelper DBHelper;
final Context context;
SQLiteDatabase db;
String yek_Msgnam[] = {
KEY_ID, KEY_NUMBERID, KEY_TEXT, KEY_DATE
};
String yek_Numbernam[] = {
KEY_ID, KEY_NAME, KEY_NUMBER
};
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_MSGTABLE);
db.execSQL(CREATE_NUMBERSTABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_MSGTABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NUMBERSTABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close() {
DBHelper.close();
}
//---insert a contact into the database---
public long insertSH_MSG(sh_msg thisMsg) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisMsg.getId()));
initialValues.put(KEY_NUMBERID, thisMsg.getnumber());
initialValues.put(KEY_TEXT, thisMsg.getText());
initialValues.put(KEY_DATE, thisMsg.getDate());
return db.insert(DATABASE_MSGTABLE, null, initialValues);
}
public long insertSH_NUMBER(sh_number thisNumbr) {
ContentValues initialValues = new ContentValues();
// initialValues.put(KEY_ID, Integer.valueOf(thisNumbr.getId()));
initialValues.put(KEY_NUMBER, thisNumbr.getnumber());
initialValues.put(KEY_NAME, thisNumbr.getname());
return db.insert(DATABASE_NUMBERSTABLE, null, initialValues);
}
//---retrieves all the contacts---
public List<sh_msg> getAllMSGItem() {
Cursor cursor = db.query(DATABASE_MSGTABLE, yek_Msgnam, null, null, null, null, null);
List<sh_msg> nams = cursorToList_SHMSG(cursor);
cursor.close();
return nams;
}
private List<sh_msg> cursorToList_SHMSG(Cursor cursor) {
List<sh_msg> nams = new ArrayList<sh_msg>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_msg nam = new sh_msg();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setDate(cursor.getString(cursor.getColumnIndex(KEY_DATE)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBERID)));
nam.setText(cursor.getString(cursor.getColumnIndex(KEY_TEXT)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public List<sh_number> getAllNUMBERItem() {
Cursor cursor = db.query(DATABASE_NUMBERSTABLE, yek_Numbernam, null, null, null, null, null);
List<sh_number> nams = cursorToList_SHNUMBER(cursor);
cursor.close();
return nams;
}
private List<sh_number> cursorToList_SHNUMBER(Cursor cursor) {
List<sh_number> nams = new ArrayList<sh_number>();
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
sh_number nam = new sh_number();
nam.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
nam.setname(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
nam.setnumber(cursor.getString(cursor.getColumnIndex(KEY_NUMBER)));
// nam.set(cursor.getString(cursor.getColumnIndex(KEY_)));
nams.add(nam);
}
;
}
cursor.close();
return nams;
}
public void removeNumber(int numberId) {
db.delete(DATABASE_NUMBERSTABLE, KEY_ID +" == "+numberId,null);
}
I'm beginner and I'm trying to to load contact from database by clicking a button in a fragment, and then save outgoing call also in database?
ContactsFragemt.java
public class ContactsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>
{
SimpleCursorAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.contact, container, false);
final Button Button = (Button) view.findViewById(R.id.load_button);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(getActivity());
//*************************** method for population main contacts listView *********************************//
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String image_uri = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
int position = 0;
int exist = 0;
boolean imageComp, nameComp;
String[] contactsData = sqlDataBaseHelper.getContacts(position);
while (exist == 0 && (contactsData[0] != (null) || contactsData[1] != (null) || contactsData[2] != (null))) // we are checking that if it is reached at the end or not
{
if (contactsData[1] != null) {
if (contactsData[1].equals(phNumber)) // will make update if we got matched with phone number and if any of ther other parameter is changed
{
if (contactsData[2] == null) {
// pic is null saved in data base and
if (image_uri != null) {
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
// then update new pic here
}
} else // but if their is pic
if (!contactsData[2].equals(image_uri)) { // and he/she update pic with a brand new picture then
sqlDataBaseHelper.updateTable1(null, null, null, null, contactsData[2], image_uri);
}
if (contactsData[0] == null) {
// name is null saved in data base and
if (contactName != null) {
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
// then update new name here
}
} else // if name was saved previously in based
if (!contactsData[0].equals(contactName)) { //but the guy changed his name so
sqlDataBaseHelper.updateTable1(contactsData[0], contactName, null, null, null, null);
}
exist = 1;
}
}
position++;
contactsData = sqlDataBaseHelper.getContacts(position);
}
if (exist == 0) // means if number is not in the list then make update
{
long id = sqlDataBaseHelper.insertData1(contactName, phNumber, image_uri);
if (id < 0) {
Toast.makeText(getActivity(), "Data1 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Data1 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
}
String[] fromFieldNames = sqlDataBaseHelper.fromFieldName1();
int[] toViewIDs = sqlDataBaseHelper.toIds1();
adapter = new SimpleCursorAdapter(getActivity(),
R.layout.list_items_view,
null,
fromFieldNames,
toViewIDs,0);
ListView mainList = (ListView) view.findViewById(R.id.main_list_view);
mainList.setAdapter(adapter);
getLoaderManager().initLoader(0, null, ContactsFragment.this);
}
});
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Uri uri = ContentProvider.CONTENT_URI;
return new CursorLoader(getActivity(), uri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader loader) {
adapter.swapCursor(null);
}
}
SimpleCursorAdapter.java
public class SimpleCursorAdapter extends android.widget.SimpleCursorAdapter {
Context mcontext;
String[] values;
Cursor cursor;
int[] to;
public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.values = from;
this.to = to;
this.cursor = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(list_items_view, parent, false);
final ImageButton call = (ImageButton) view.findViewById(R.id.call);
ImageButton sms = (ImageButton) view.findViewById(R.id.sms);
final TextView contact_no = (TextView) view.findViewById(R.id.contact_no);
final TextView contactName = (TextView) view.findViewById(R.id.contact_name);
ImageView contactImage = (ImageView) view.findViewById(R.id.contact_image);
final SQLDataBaseAdapter sqlDataBaseHelper = new SQLDataBaseAdapter(mcontext);
//********************************** method for calling from app****************************/
call.setOnClickListener(new View.OnClickListener() { //when phone button is clicked
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(String.valueOf("tel:" + contact_no.getText().toString())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//*/
if (ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mcontext.startActivity(callIntent);//*/
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) { // for 12 hours format
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
Cursor c = mcontext.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
if (c.moveToNext() == true) {
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/outgoing_call.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
c.close();
}
});
//********************************** method for sending message from app****************************//
sms.setOnClickListener(new View.OnClickListener() { //when sms button is clicked
#Override
public void onClick(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + contact_no.getText().toString()));
smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(smsIntent);
Calendar rightNow = Calendar.getInstance();
int hourOfDay = rightNow.get(Calendar.HOUR_OF_DAY);
String AM_PM;
if (hourOfDay > 12) {
hourOfDay = hourOfDay - 12;
AM_PM = "PM";
} else {
AM_PM = "AM";
}
String time = Integer.toString(hourOfDay)
+ " : " + Integer.toString(rightNow.get(Calendar.MINUTE))
+ " " + AM_PM;
String date = Integer.toString(rightNow.get(Calendar.DAY_OF_MONTH))
+ "/" + Integer.toString(rightNow.get(Calendar.MONTH) + 1)
+ "/" + Integer.toString(rightNow.get(Calendar.YEAR));
String name = contactName.getText().toString();
String duration = "000 000 000";
String pic = Uri.parse("android.resource://com.example.asim.simpleviewpager/drawable/message_sent.png").toString();
long id = sqlDataBaseHelper.insertData2(name, duration, pic, time, date);
if (id < 0) {
Toast.makeText(mcontext, "Data2 Insertion is unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mcontext, "Data2 Insertion is successful", Toast.LENGTH_SHORT).show();
}
}
});
//************************** Reading contact from SQLDataBase for each item*************************************//
String[] contactsData = sqlDataBaseHelper.getContacts(position);
if (contactsData[0] != (null)) {
contactName.setText(contactsData[0]);
contact_no.setText(contactsData[1]);
if (contactsData[2] == (null)) {
contactImage.setImageResource(R.drawable.w4j8n);
} else {
contactImage.setImageURI(Uri.parse(contactsData[2]));
}
}//*/
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
}
}
ContentProvider.java
public class ContentProvider extends android.content.ContentProvider {
public static final String PROVIDER_NAME = "com.example.asim.simpleviewpager"; //.contentprovider
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/ContactsDataBase");
private static final int CONTENTPROVIDERS = 1;
private static final UriMatcher uriMatcher ;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "ContactsDataBase", CONTENTPROVIDERS);
}
SQLDataBaseAdapter sqlDataBaseAdapter;
#Override
public boolean onCreate() {
sqlDataBaseAdapter = new SQLDataBaseAdapter(getContext());
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if (uriMatcher.match(uri) == CONTENTPROVIDERS) {
return sqlDataBaseAdapter.getAllContacts();
} else {
return null;
}
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
SQLDataBaseAdapter.java
public class SQLDataBaseAdapter {
SQLDataBaseHelper sqlDataBaseHelper;
public SQLDataBaseAdapter(Context context){
sqlDataBaseHelper = new SQLDataBaseHelper(context);
}
public long insertData1(String contactName, String contactNo, String pic){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.NO, contactNo);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE1_NAME,null,contentValues);
return id;
}
public long insertData2(String contactName, String duration, String time, String date, String pic ){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, contactName);
contentValues.put(SQLDataBaseHelper.DURATION, duration);
contentValues.put(SQLDataBaseHelper.TIME, time);
contentValues.put(SQLDataBaseHelper.DATE, date);
contentValues.put(SQLDataBaseHelper.PICTURE, pic);
long id = db.insert(SQLDataBaseHelper.TABLE2_NAME,null,contentValues);
return id;
}
public String[] getContacts(int position) {
String[] contactsData = new String[3];
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
String[] columns = {SQLDataBaseHelper.UID, SQLDataBaseHelper.NAME, SQLDataBaseHelper.PICTURE, SQLDataBaseHelper.NO};
Cursor cursor = db.query(SQLDataBaseHelper.TABLE1_NAME, columns, null, null, null, null, null);
cursor.moveToPosition(position);
int pos = cursor.getPosition();
int cnt = cursor.getCount();
int checkElement = cnt-pos;
if (checkElement > 0)
{
cursor.moveToPosition(position);
int nameColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NAME);
String name = cursor.getString(nameColumnIndex);
int noColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.NO);
String contactNo = cursor.getString(noColumnIndex);
int picColumnIndex = cursor.getColumnIndex(SQLDataBaseHelper.PICTURE);
String picture = cursor.getString(picColumnIndex);
contactsData[0] = name;
contactsData[1] = contactNo;
contactsData[2] = picture;
} else
{
contactsData[0] = null;
contactsData[1] = null;
contactsData[2] = null;
}
cursor.close();
db.close();
return contactsData;
}
public void updateTable1 (String oldName, String newName, String oldPhoneNo, String NewPhoneNumber, String oldPic, String newPic) {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
if (oldName != newName) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NAME, newName);
String[] whereArgs = {oldName};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NAME+" =? ",whereArgs);
}
if(oldPhoneNo!=NewPhoneNumber){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.NO, NewPhoneNumber);
String[] whereArgs = {oldPhoneNo};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.NO+" =? ",whereArgs);
}
if(oldPic!=newPic){
ContentValues contentValues = new ContentValues();
contentValues.put(SQLDataBaseHelper.PICTURE, NewPhoneNumber);
String[] whereArgs = {oldPic};
db.update(SQLDataBaseHelper.TABLE1_NAME,contentValues,SQLDataBaseHelper.PICTURE+" =? ",whereArgs);
}
}
public void deleteRowTable1()
{
}
public void updateTable2 ()
{
}
public void deleteRowTable2()
{
}
/////////////////////////////////////////////////////////////////////
public Cursor getAllContacts(){
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return db.query(SQLDataBaseHelper.TABLE1_NAME, new String[] {
SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE},
null, null, null, null,
SQLDataBaseHelper.NAME + " asc ");
}
public SQLDataBaseAdapter open() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
return this;
}
public Cursor getAllRows1() {
SQLiteDatabase db = sqlDataBaseHelper.getWritableDatabase();
Cursor cursor = db.query(true, SQLDataBaseHelper.TABLE1_NAME, SQLDataBaseHelper.ALL_KEYS1, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public String[] fromFieldName1(){///
String[] fields = new String[] {SQLDataBaseHelper.UID,SQLDataBaseHelper.NAME, SQLDataBaseHelper.NO, SQLDataBaseHelper.PICTURE};
return fields;
}
public int[] toIds1(){
int[] toViewIds = new int[]{R.id.contact_name,R.id.contact_no,R.id.contact_image};
return toViewIds;
}
static class SQLDataBaseHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "ContactsDataBase";
private static final String TABLE1_NAME = "CALLS_TABLE1";
private static final String TABLE2_NAME = "LOGS_TABLE";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String NO = "ContactNo";
private static final String DURATION = "Duration";
private static final String PICTURE = "Picture";
private static final String DATE = "Date";
private static final String TIME = "Time";
private static final String[] ALL_KEYS1 = new String[] {UID,NAME, NO, PICTURE};
private static final String CREATE_TABLE1 = "CREATE TABLE "+TABLE1_NAME+" (" +UID+
" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+NO+" VARCHAR(255), "
+PICTURE+" VARCHAR(255));";
private static final String CREATE_TABLE2 = "CREATE TABLE "+TABLE2_NAME+" ("
+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+DURATION+" VARCHAR(255), "
+PICTURE+" VARCHAR(255), " +DATE+ " VARCHAR(255), "+TIME+ " VARCHAR(255));";
private static final String DROP_TABLE1 = "DROP TABLE IF EXIST"+ TABLE1_NAME ;
private static final String DROP_TABLE2 = "DROP TABLE IF EXIST"+ TABLE2_NAME ;
private Context context;
public SQLDataBaseHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE1);
Toast.makeText(context,"onCreate1 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
try {
db.execSQL(CREATE_TABLE2);
Toast.makeText(context,"onCreate2 called" , Toast.LENGTH_SHORT).show();
} catch (SQLException e) {
Toast.makeText(context,""+e , Toast.LENGTH_SHORT).show();
Log.e("exception in onCreate", "here is exception " + e);
} //*/
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE1);
Toast.makeText(context,"onUpgrade1 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
try {
db.execSQL(DROP_TABLE2);
Toast.makeText(context,"onUpgrade2 called" , Toast.LENGTH_SHORT).show();
onCreate(db);
}catch (SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_SHORT).show();
}
}
}
}
and these are the errors
01-30 04:03:23.804 2702-2702/com.example.asim.simpleviewpager E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: Resource ID #0x88a6fd
at android.content.res.Resources.getValue(Resources.java:1049)
at android.content.res.Resources.getDrawable(Resources.java:664)
at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:323)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:175)
at android.support.v7.widget.TintManager.getDrawable(TintManager.java:168)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:51)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:72)
at android.support.v4.widget.SimpleCursorAdapter.setViewImage(SimpleCursorAdapter.java:195)
at android.support.v4.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:143)
In SimpleCursorAdapter.java, you have a method bindView() which overrides the same method from its parent class, but you don't put any code in that method. Deleting the method should fix the error. But if you plan to override how binding works in that method, you may want to put some code in there starting with something like
super.bindView(view, context, cursor);
i created a SQL Database and was able to safe data from three EditText Views and display it in a single TextView.
Then i thought it would be way better to display the data in a custom ListView, so i followed the developer guide and tried to display the data by a simpleCursorAdapter. But it did not work...i do not get any errors or anything, the data is just not shown...I guess there must be some missing connection between the Cursor, the Adapter or the DB...
i know that this kind of question is asked quite frequently, but i am unable to find my mistake, any help would be greatly appreciated:
MyDBHandlerFaecher.java:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
//Delete the line in which the COLUMN_NAME is equal to the input
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
FaecherActivity.java
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(), et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
//delete fach from database
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = new String[]{"_faechername", "_faecherraum", "_faecherfarbe"};
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = getContentResolver().query(Uri.parse(MyDBHandlerFaecher.TABLE_FAECHER),null, null, null, null);
SimpleCursorAdapter fachadapter = new SimpleCursorAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
}
}
i found code that works for me: i found out that the cursor in my DBHandler class was not empty, but it was empty in my FaecherActivity...so i created a custom SimpleCursorAdapter, and modified my code this way:
FaecherActivity:
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(),
et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = dbHandlerFaecher.databaseToStringArray();
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = dbHandlerFaecher.getWritableDatabase().rawQuery(" SELECT * FROM " + MyDBHandlerFaecher.TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist2");
}
else {
Log.d("Event", "Records do not exist2");
}
SimpleCursorAdapter fachadapter = new FaecherRowAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
MyDBHandlerFaecher:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
public String[] databaseToStringArray() {
String[] fromColumns = new String[]{COLUMN_NAME, COLUMN_RAUM, COLUMN_COLOR};
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty or not
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist");
}
else {
Log.d("Event", "Records do not exist");
}
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
cursor.moveToNext();
}
db.close();
return fromColumns;
}
}
FaecherRowAdapter:
public class FaecherRowAdapter extends SimpleCursorAdapter {
private int layout;
private Context context;
public FaecherRowAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
this.context = context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.faecher_row, parent, false);
bindView(v, context, c);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
int fachNameColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_NAME);
int fachRaumColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_RAUM);
int fachFarbeColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_COLOR);
String fachName = c.getString(fachNameColumn);
String fachRaum = c.getString(fachRaumColumn);
String fachFarbe = c.getString(fachFarbeColumn);
//set the name of the entry
TextView facheintrag = (TextView) v.findViewById(R.id.facheintrag);
if (facheintrag != null){
facheintrag.setText(fachName);
}
TextView raumeintrag = (TextView) v.findViewById(R.id.raumeintrag);
if (raumeintrag != null){
raumeintrag.setText(fachRaum);
}
TextView farbeintrag = (TextView) v.findViewById(R.id.farbeintrag);
if (farbeintrag != null){
farbeintrag.setText(fachFarbe);
}
}
}
Im trying to update a users current credits, but I don't want to replace the value, just add on a selected amount from the spinner and add it on to the the users current credits? Thank you.
My database code?
package com.example.parkangel;
public class UDbHelper extends SQLiteOpenHelper
{
public static final String KEY_ROWID = "_id";
public static final String KEY_PFNAME = "payeeFname";
public static final String KEY_PSNAME = "payeeSname";
public static final String KEY_CARD = "card";
public static final String KEY_CREDITS = "credits";
private static final String DATABASE_NAME = "UserData.db";
private static final String DATABASE_TABLE = "UserTable";
private static final int DATABASE_VERSION = 1;
//private UDbHelper dbHelper;
//private final Context ourContext;
private static UDbHelper instance;
private SQLiteDatabase ourDatabase;
public UDbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static UDbHelper getInstance(Context context)
{
if (instance == null)
{
instance = new UDbHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_PFNAME + " TEXT NOT NULL, " + KEY_PSNAME + "
TEXT NOT NULL, " +
KEY_CARD + " INTEGER NOT NULL, " + KEY_CREDITS + "
INTEGER NOT NULL);");
ContentValues values = new ContentValues();
values.put(KEY_PFNAME, "Tutku");
values.put(KEY_PSNAME, "Erbil");
values.put(KEY_CARD, "12345677");
values.put(KEY_CREDITS, 5);
db.insert(DATABASE_TABLE, null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public synchronized UDbHelper open() throws SQLException
{
System.out.println ("running open");
if(ourDatabase == null || !ourDatabase.isOpen())
ourDatabase = getWritableDatabase();
return this;
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[] {KEY_ROWID, KEY_PFNAME, KEY_PSNAME,
KEY_CARD, KEY_CREDITS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = " ";
int iRow = c.getColumnIndexOrThrow(KEY_ROWID);
int iPFname = c.getColumnIndexOrThrow(KEY_PFNAME);
int iPSname = c.getColumnIndexOrThrow(KEY_PSNAME);
int iCard = c.getColumnIndexOrThrow(KEY_CARD);
int iCredits = c.getColumnIndexOrThrow(KEY_CREDITS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +
c.getString(iPFname) + " " +
c.getString(iPSname) + " " + c.getString(iCard) + " " +
c.getString(iCredits) + "\n";
}
return result;
}
public void upDateUser(String money) {
// TODO Auto-generated method stub
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, money);
ourDatabase.update(DATABASE_TABLE, cvUpdate, null, null);
}
}
Class that needs to perform the actoin:
package com.example.parkangel;
public class Balance extends Activity implements OnClickListener{
Button add;
TextView display;
Spinner spinner3;
Integer[] money = new Integer[] {1, 2, 5, 10};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.balance_layout);
TextView tv = (TextView) findViewById(R.id.firstn);
UDbHelper db = new UDbHelper(this);
db.open();
String data = db.getData();
//db.addUser();
db.close();
tv.setText(data);
ArrayAdapter<Integer> adapter3 = new ArrayAdapter<Integer>(Balance.this,
android.R.layout.simple_spinner_item, money);
spinner3 = (Spinner) findViewById (R.id.moneytoadd);
spinner3.setAdapter(adapter3);
add = (Button) findViewById(R.id.topup);
add.setOnClickListener(this);
//add = (Button) findViewById(R.id.topup);
}
public void onClick(View arg0)
{
switch (arg0.getId()){
case R.id.topup:
boolean work = true;
try{
String money = spinner3.getContext().toString();
UDbHelper ud = new UDbHelper(this);
ud.open();
ud.upDateUser(money);
ud.close();
}catch (Exception e){
work = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Unable To TopUp!");
TextView dg = new TextView(this);
dg.setText(error);
d.setContentView(dg);
d.show();
}finally{
if(work){
Dialog d = new Dialog(this);
d.setTitle("You Have ToppedUp!");
TextView dg = new TextView(this);
dg.setText("TopUp Successful");
d.setContentView(dg);
d.show();
}
}
break;
}
}
public void updateActivity(View view){
Intent book = new Intent(Balance.this, BookTicket.class);
startActivity(book);
}
public void addBalance(View view){
Intent addB = new Intent(Balance.this, Balance.class);
startActivity(addB);
}
public void doUpdate(View view){
Intent upd = new Intent(Balance.this, UpdateTicket.class);
startActivity(upd);
}
}
First of all you should have an ID that will let you find the user you are interested in. That do a select to get the current value that is stored in database. Parse the value to integer and add "new" money. And finally, update the value in database.
public void upDateUser(String ID, String money) {
String query = "Select money from TABLE_NAME where ID = " + ID;
SQLiteDatabase db = this.getWriteableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int oldMoney = 0;
if (cursor.moveToFirst()) {
oldMoney = Integer.parseInt(cursor.getString(0)); //Cause we get only from money column
}
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_CREDITS, oldMoney + money);
String filter = "UID" + "=" + ID;
db.update(DATABASE_TABLE, cvUpdate, filter, null);
}
Of course you have to check if cursor returns exactly one row and do some other checks.
I'm trying to add site details to a database and then after I insert a row, output the result to a TextView. The record is being inserted into the database because it's being shown in a TextView, however I can only insert one record and I'm not sure why. I'm been using the tutorial here and modifying it to meet my needs.
Here is my DBAdapter:
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String username,
String password, int port) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
initialValues.put(KEY_PORT, port);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, String port) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
// newValues.put(KEY_PASSWORD, password);
// newValues.put(KEY_PORT, port);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
I'm querying the database here:
public class FTPConnector extends Activity {
DBAdapter myDb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.ftp);
status = (TextView) findViewById(R.id.status);
editAddress = (EditText) findViewById(R.id.editAddress);
editUser = (EditText) findViewById(R.id.editUsername);
editPassword = (EditText) findViewById(R.id.editPassword);
addsiteBtn = (Button) findViewById(R.id.addsiteBtn);
addsiteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
siteManager();
}
});
openDb();
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
//Where the insertRecord() happens
public void siteManager() {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.site_manager, null);
final EditText tmpname = (EditText) view
.findViewById(R.id.dialogsitename);
final EditText tmpaddress = (EditText) view
.findViewById(R.id.dialogaddress);
final EditText tmpuser = (EditText) view
.findViewById(R.id.dialogusername);
final EditText tmppass = (EditText) view
.findViewById(R.id.dialogpassword);
final EditText tmpport = (EditText) view.findViewById(R.id.dialogport);
final TextView tmpsites = (TextView) view.findViewById(R.id.textView6);
final CheckBox tmppassive = (CheckBox) view
.findViewById(R.id.dialogpassive);
final Button tmpclose = (Button) view.findViewById(R.id.closeBtn);
final Button tmptestBtn = (Button) view.findViewById(R.id.testBtn);
final Button tmpsavetsite = (Button) view.findViewById(R.id.saveSite);
customDialog.setView(tmpclose);
customDialog.setView(tmptestBtn);
customDialog.setView(tmpname);
customDialog.setView(tmpaddress);
customDialog.setView(tmpuser);
customDialog.setView(tmppass);
customDialog.setView(tmpport);
customDialog.setView(tmppassive);
customDialog.setView(tmpsavetsite);
customDialog.setView(tmpsites);
tmpclose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
tmptestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
_passive = false;
if (tmppassive.isChecked()) {
_passive = true;
}
boolean status = ftpConnect(_address, _user, _pass, _port);
if (status == true) {
Toast.makeText(FTPConnector.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(FTPConnector.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
tmpsavetsite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tmpsites.setText("");
String msg = "!";
_name = tmpname.getText().toString();
_address = tmpaddress.getText().toString();
_user = tmpuser.getText().toString();
_pass = tmppass.getText().toString();
_port = Integer.parseInt(tmpport.getText().toString());
long newId = myDb.insertRow(_name, _address, _user, _pass, 21);
Cursor c = myDb.getAllRows();
if (c.moveToFirst()) {
int id = c.getInt(0);
String _name = c.getString(1);
String _address = c.getString(2);
String _user = c.getString(3);
String _pass = c.getString(4);
int _port = c.getInt(5);
msg += "id=" + id + "\n";
msg += ", name=" + _name + "\n";
msg += ", address=" + _address + "\n";
msg += ", username=" + _user + "\n";
msg += ", password=" + _pass + "\n";
msg += ", port=" + _port + "\n";
while (c.moveToNext());
}
c.close();
// displayText(msg);
tmpsites.setText(msg);
}
});
customDialog.setView(view);
customDialog.show();
}
Why can't I add more than one record?
In here :
while (c.moveToNext()); //<<<
currently you are not using any loop like do-while for iterating through cursor(you forget to add do block with while). get all data from cursor as using for loop:
//more to the first row
c.moveToFirst();
//iterate over rows
for (int i = 0; i < c.getCount(); i++) {
// get all data here from current row..
//move to the next row
c.moveToNext();
}
//close the cursor
c.close();
and using do-while you can get all values from current row as:
c.moveToFirst(); //more to the first row
do {
// get all data here from current row..
} while (c.moveToNext());