I want to save name in the SQLite Database and later in another activity I want to retrieve that name as a String Value. But I am not being able to get data from the database. Help me please. My code is given below,
Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public void onCreate(SQLiteDatabase db) {String createTable =
"CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT, " + COL2 +" TEXT)";
db.execSQL(createTable);}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
MainActivity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
AddData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
}
}
HomeActivity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
}
}
Here, in this home activity i want to get the username as a string but I don't know how to do that. Help me please...
To retrieve data, you run a query that extracts the data into a Cursor. The Cursor will consist of 0-n rows and will have as many columns as defined in the query. You then move through the rows and use the appropriate Cursor get????? methods to get the actual data.
As an example you could add the following method to your DatabaseHelper :-
public String getName(long id) {
String rv = "not found";
SqliteDatabase db = this.getWritableDatabase();
String whereclause = "ID=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COL2));
}
return rv;
}
The above can then be used by String name = mDatabaseHelper.getName(1);.
Note that this assumes that a row with an ID of 1 exists.
Your Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 +" INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT)"; // You have written ID inplace of COL1
public DatabaseHelper(Context context)
{
super(context,DB_NAME,null,1);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(createTable);
}
public boolean insertData(String name) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL2,name);
long result1 = sqLiteDatabase.insert(TABLE_NAME,null,contentValues1);
return result1 != -1;
}
public Cursor viewData()
{
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor ;
String query = "Select * from " +TABLE_NAME;
cursor= sqLiteDatabase.rawQuery(query, null);
return cursor;
}
Your Main Activity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
mDatabaseHelper.insertData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
}
Your Home Activity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
ArrayList<String> listItem;
ArrayAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.listView);
listItem = new ArrayList<>();
viewData1();
}
private void viewData1() {
Cursor cursor = mDatabaseHelper.viewData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
Log.i("message","Data got");
listItem.add(cursor.getString(1)); // Adding data received to a Listview
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
listView.setAdapter(adapter);
}
}
}
check it out this library
it is very easy to implement
https://github.com/wisdomrider/SqliteClosedHelper
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
Thanks in advance for helping me out. This is my first time working on SQLite Database as well as creating an app.
Problem: When I click save"ImageButton" on the AddEntry.xml for some reason its not displaying on my listview which is located in my Fragment Home.xml. I found fragments to be a tad difficult since you have to change the code around in order for it to work. so please excuse if my code is all over the place.
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener
{
EditText DescriptionET,CalorieET;
ImageButton Savebtn, Cancelbtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry,
container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
descriptionET.setText("");
EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
calorieET.setText("");
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER =
"section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private View v;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home,
container, false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain)getActivity()).loadSelection(1);
}
});
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView)
getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
listview = (ListView) getActivity().findViewById(R.id.listViewDB);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber -
FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new
SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
closeDataBase();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
// Constants & Data
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[]
{KEY_ROWID, KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public CalorieDatabase 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 description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
// 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 description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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);
}
}
}
Thanks again for helping me out. I've been stressing for the last couple of days trying to figure it out.
I'm very new at android programming and this is my first question on stack overflow ever. I am having trouble understanding where i have gone wrong in my code implementation. I'm trying to store data in a database and then extract it into an arraylist.
This is the class where i add data into the database in the button onclicklistener:
public class KarmaDescription extends AppCompatActivity {
Button button;
TasksDBHandler dbHandler;
int tId = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_karma_desc2min);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Overview");
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyTasksGS myTask = new MyTasksGS(tId, "New Task Title", 2);
dbHandler.addTask(myTask);
Toast.makeText(KarmaDescription.this, "Task Added", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
This is the class which manages the database:
public class TasksDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "tasks.db";
public static final String TABLE_TASKS = "tasks";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TASKNAME = "taskname";
public static final String COLUMN_DAYSLEFT = "daysleft";
public TasksDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TASKS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_TASKNAME + " TEXT," +
COLUMN_DAYSLEFT + " INTEGER" +
")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
onCreate(db);
}
//Add a new row to the database
public void addTask(MyTasksGS myTask) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, myTask.getId());
values.put(COLUMN_TASKNAME, myTask.getTitle());
values.put(COLUMN_DAYSLEFT, myTask.getDaysRemaining());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_TASKS, null, values);
db.close();
}
//Delete row from the database
public void deleteTask(String taskID) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_TASKS + " WHERE " + COLUMN_ID + "=\"" + taskID + "\";");
}
//To put data into an arraylist
public List<MyTasksGS> getDataFromDB()
{
int id, daysRemaining;
String title;
List<MyTasksGS> tasksList = new ArrayList<MyTasksGS>();
String query = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
while (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
title = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TASKNAME));
daysRemaining = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_DAYSLEFT));
MyTasksGS myTask = new MyTasksGS(id, title, daysRemaining);
tasksList.add(myTask);
}
return tasksList;
}
}
I'm trying to copy the arraylist data which is returned from the above class(using getDataFromDB function) into myTaskList here and im getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.prateek.karma.TasksDBHandler.getDataFromDB()' on a null object reference
public class MyTasksFragment extends Fragment {
Button taskComplete;
RecyclerView RVMyTasks;
static MyTasksAdapter mtAdapter;
List<MyTasksGS> myTaskList = new ArrayList<>();
TasksDBHandler dbHandler;
public MyTasksFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_tasks, container, false);
taskComplete = (Button) view.findViewById(R.id.taskComplete);
RVMyTasks = (RecyclerView) view.findViewById(R.id.RVMyTasks);
mtAdapter = new MyTasksAdapter(myTaskList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
RVMyTasks.setLayoutManager(mLayoutManager);
RVMyTasks.setItemAnimator(new DefaultItemAnimator());
RVMyTasks.setAdapter(mtAdapter);
myTaskList = dbHandler.getDataFromDB();
mtAdapter.notifyDataSetChanged();
return view;
}
}
And this is the MyTasksGS class:
public class MyTasksGS {
String title;
int daysRemaining;
int id;
public MyTasksGS() {
}
public MyTasksGS(int id, String title, int daysRemaining) {
this.title = title;
this.daysRemaining = daysRemaining;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getDaysRemaining() {
return daysRemaining;
}
public void setDaysRemaining(int daysRemaining) {
this.daysRemaining = daysRemaining;
}
}
I may have made a very silly mistake somewhere but im not able to find it. Any help is appreciated
You need to instantiate the dbHandler, you are trying to use it without a valid instance. It causes the NullPointerException.
In your on onCreateView
before myTaskList = dbHandler.getDataFromDB();
add : dbHandler = new TasksDBHandler(getActivity());
use your class property DATABASE_NAME and DATABASE_VERSION instead of pass in constructor.
Change your TaskDBHandler constructor like this
public TasksDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
I want to save the Score from a Quiz in a SQLite Database and change an image in another activity if the Score is 5. There is no error shown, but even if I score 5 the image won't change... How can I log the content of my database to check if the score was added or how can I find the mistake?
DB Helper:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "CE";
public static final String SCORE_TABLE = "score";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public static final String COLUMN_MARKERID = "MARKERID";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase= db;
String create_query = "CREATE TABLE IF NOT EXITS " + SCORE_TABLE + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SCORE + " INTEGER, "
+ COLUMN_MARKERID + " TEXT) ";
db.execSQL(create_query);
}
public void addScore (DbHelper dbh, Integer score, String markerID) {
dbase = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_SCORE, score);
cv.put(COLUMN_MARKERID, markerID);
dbase.insert(SCORE_TABLE, null, cv);
}
public Cursor getScore(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
return cursor;
}
Write the Score into the Database after completing the Quiz:
public class ResultActivity extends Activity {
String markerID;
int score;
TextView t=(TextView)findViewById(R.id.textResult);
Button saveButton = (Button) findViewById(R.id.saveButton);
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
markerID = b.getString("markerID");
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DbHelper dbh = new DbHelper(context);
dbh.addScore(dbh,score,markerID);
Intent intent = new Intent(ResultActivity.this, Discover.class);
intent.putExtra("MarkerID", markerID);
startActivity(intent);
}
});
}
Discover class -> Check if score is 5 and change image if:
DbHelper dbh = new DbHelper(context);
Cursor cursor = dbh.getScore(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(0))== 5 && InfoUeberschrift.toString().equals(cursor.getString(1))){
ImageDone.setImageResource(R.drawable.markerdone);
}
}
while(cursor.moveToNext());
}
cursor.close();
}
The SQLiteDatabase insert function returns a long value, so if an error has occurred it returns -1.
'the row ID of the newly inserted row, or -1 if an error occurred'
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This can be used to see if the insert is happening correctly.
Or you can wrap in try and catch and print message like so
try {
//code
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught", ex.getMessage());
return -1;
}
}
When I have issues using Java and SQLite i normally do it directly with the SQLite desktop version using Shell, as I find it easier to test out table design.
Hope this helps