I have this code where I'll get all the available rows with same DueDateTime
public List<DatabaseSource> getListSched() {
text = sharedPreference.getValue2(context);
String shareFact = text.toString();
List<DatabaseSource> schedList= new ArrayList<DatabaseSource>();
// Select All Query
String selectQuery = "SELECT * FROM schedTBL WHERE DueDateTime like " + shareFact;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
DatabaseSource sched= new DatabaseSource();
sched.setId(Integer.parseInt(cursor.getString(0)));
sched.setSubject(cursor.getString(1));
sched.setDescription(cursor.getString(2));
sched.setDueDateTime(cursor.getString(3));
// Adding sched to list
contactList.add(sched);
} while (cursor.moveToNext());
}
// return schedlist
return schedList;
}
Am I doing it right??, it seems I cannot use the sharedpreferences in it, I have SharedPreferencesUID Class, I store this code below to get the value wherever I want to
public String getValue2(Context context) {
SharedPreferences settings;
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
text = settings.getString("dateselected", null);
return text;
}
The only solution I could do is to MIGRATE getListSched to the activity where needs it (for specific activity only) then just call the DatabaseSched Class (which has the SQLiteOpenHelper) so I could use the sharedPreference.
Related
I'm writing an app that will allow users to read short stories that are stored in an SQLite database.
So far so good.
But now I want to add features that involve writing to the database (saving the Y location of a ScrollView so the user can pick up where they left off, bookmarking stories, etc).
Should I add these values to the books table, or should I create a separate table user_settings with columns like id (int), story_id (int), y_position (int), bookmarked (boolean)?
Note: I'm also thinking ahead to the possibility of storing stories on a non-local database in the future.
My other question is: do I need to move the database somewhere to be able to write to it? I'm using SQLiteAssetHelper and the database is currently at /assets/databases/database.db. I'm hearing some talk of a /data/data/mypackage folder but I can't see it in my project.
My database setup is currently as follows:
authors
id
name
name_alphanumeric
books
id
title
author_id
collection
body
If it's useful, here's my DatabaseHelper so far:
public class DatabaseHelper extends SQLiteAssetHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database9.db";
private static final String BOOKS = "books";
private static final String AUTHORS = "authors";
public DatabaseHelper (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// setForcedUpgrade();
}
// Getting all books
public ArrayList<Author> getAllAuthors() {
ArrayList<Author> authorList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT id, name FROM " + AUTHORS + " ORDER BY name_alphabetic";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
// create new author object
Author author = new Author();
// set ID and name of author object
author.setID(Integer.parseInt(cursor.getString(0)));
author.setName(cursor.getString(1));
// pass author object to authorList array
authorList.add(author);
} while (cursor.moveToNext());
}
// return author list
return authorList;
}
// Getting all stories
public List<Book> getAllStories(int authorID) {
List<Book> storyList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT id, title FROM " + BOOKS + " WHERE author_id = " + authorID;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Book book = new Book();
book.setStoryID(Integer.parseInt(cursor.getString(0)));
book.setTitle(cursor.getString(1));
storyList.add(book);
} while (cursor.moveToNext());
}
// return contact list
return storyList;
}
// Get all collections
public List<Book> getAllCollections(int authorID) {
List<Book> collectionsList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT DISTINCT collection FROM " + BOOKS + " WHERE author_id = " + authorID;
Log.i("stories", selectQuery);
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Book book = new Book();
book.setCollection(cursor.getString(0));
// Log.i("stories", cursor.getString(0));
collectionsList.add(book);
} while (cursor.moveToNext());
}
return collectionsList;
// not sure how to log collectionsList here
}
// Get story
public String getStoryBody(int storyID) {
// Log.i("stories", Integer.toString(storyID));
String storyBody = "";
// String storyBody();
// Select all query
String selectQuery = "SELECT body FROM " + BOOKS + " WHERE id = " + storyID;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
storyBody = cursor.getString(0);
} while (cursor.moveToNext());
}
return storyBody;
}
public int setScrollPosition(int scrollY, int storyID) {
String insertQuery = "UPDATE " + BOOKS + " SET scroll_position = " + scrollY + " WHERE id = " + storyID;
Log.i("insert", insertQuery);
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(insertQuery);
return 0;
}
public int getScrollPosition(int storyID) {
int scrollPosition = 0;
String selectQuery = "SELECT scroll_position FROM " + BOOKS + " WHERE id = " + storyID;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
scrollPosition = cursor.getInt(0);
} while (cursor.moveToNext());
}
return scrollPosition;
}
}
But now I want to add features that involve writing to the database
(saving the Y location of a ScrollView so the user can pick up where
they left off, bookmarking stories, etc).
Should I add these values to the books table, or should I create a
separate table user_settings with columns like id (int), story_id
(int), y_position (int), bookmarked (boolean)?
I think you have made it clear that they are USER values, so it is very likely that a separate user table would be the better more manageable solution.
My other question is: do I need to move the database somewhere to be
able to write to it? I'm using SQLiteAssetHelper and the database is
currently at /assets/databases/database.db. I'm hearing some talk of a
/data/data/mypackage folder but I can't see it in my project.
In all likeliehood the database has been copied from the assets folder into data/data/yourpackage/databases/dbfilename by SQLiteAssetHelper (as I understand that's primarily what it's for. However I've never used it.) Such folders have limited access (normally only the Application (rooted device an exception)) so that could well be why you can't see it.
As such there is likely nothing required in the way of permissions for writing to/updating the database.
I have 3 activities - login activity, main page activity, profile activity. The login activity will call main page activity and main page activity will call profile activity. How can I pass the data from login activity to profile activity? Is it must pass the data from login activity to main page activity first then pass to profile activity from main page activity? Or is there any other way to pass the data? Thanks!
You can do that... or you could store the data in a persistent storage and read back whenever required.
Learn about SharedPreferences here - Saving Key-Value Sets | SharedPreferences
Saving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Retrieving data looks like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Learn about SQLite Database here - Saving Data in SQL Databases | SQLite Database
Saving data looks like:
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);
// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
Retrieving data looks like:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
List itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedEntry._ID));
itemIds.add(itemId);
}
cursor.close();
There are two methods to pass values between Activities in Android:
1. Using intent:
Example:
In the Login Activity, put the following code inside the OnClickListiner:
Intent intent = new Intent(getApplicationContext(), mainActivity.class);
intent.putExtra("username", usernameVariable);
intent.putExtra("password", passwordVariable);
startActivity(intent);
Then, on the mainActivity, to receive the values use the following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent intent = getIntent();
String u = intent.getStringExtra("username");
String p = intent.getStringExtra("password");
// note: the arguments should match the same as its in the loginActivity
}
2. Using Static Variables:
Example:
On the LoginActivity, create two static attributes. Like the following:
Public Class LoginActivity{
public static String username;
public static String password;
protected void onCreate(Bundle savedInstanceState) {
...
}
}
Then, in the mainActivity class use the following code to get these values:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
String u=LoginActivity.username;
String p=LoginActivity.password;
}
Hope it solved your problem...
There is one more way that you can use create a singleton class and store the value and use it.
public final class ProfileDataModel {
private static ProfileDataModel instance;
private String userName;
private String address;
private ProfileDataModel() {
}
/**
* Get Instance for Profile
* #return
*/
public static ProfileDataModel getInstance() {
if (instance == null){
instance = new ProfileDataModel();
}
return instance;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
// Use cases
//Set the data
ProfileDataModel.getInstance().setAddress("Data from login response");
ProfileDataModel.getInstance().setUserName("As per request/response");
//Get the data
String address = ProfileDataModel.getInstance().getAddress();
String userName = ProfileDataModel.getInstance().getUserName();
how to Display the particular field details in editext by giving id here i write code in database handler but i dont know what to do in MainActivity
i have fields when i gave id and click show button the details in database for that particular id want to be load in edittext
My database Handler class
Try this.
set editText as number only
android:inputType="number|numberDecimal"
public void show()
{
bshow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(uid.getText().toString().equals(""))
return;
int id = Integer.parseInt(uid.getText().toString());
Cursor res=myDB.getData(id);//i got an error Here and i dont know what to do
String NAME = res.getString(res.getColumnIndex("NAME"));
String SURNAME = res.getString(res.getColumnIndex("SURNAME"));
String MARKS = res.getString(res.getColumnIndex("MARKS"));
editname.setText(NAME);
editsurname.setText(SURNAME);
editmark.setText(MARKS);
}
});
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from student_details where id="+id+"", null );
if(res != null && res.moveToFirst()) {
return res;
}
return res;
}
In your activity initialize your Db class.
Now you can get value like below code ; -
Cursor mCur = myDb.getData(some integer value);
Now you can fetch value from cursor by ;-
mCur .getString(mCur .getColumnIndex("column name");
I am creating an android application which has 3 EditTexts.
Now when I close the app and return it, the value in EditText are gone and I have to return the values last entered.
How can I return those values entered by the user in EditText (On the press of a button) so that the user don't have to enter the whole text again and again on closing and responding of the app?
Providing the answer with the code will help a lot! Thanks.
Put this class in your project
public class SaveData {
private static final String EDIT1 = "edit1";
private static final String EDIT2 = "edit2";
private static final String EDIT3 = "edit3";
SharedPreferences pref;
Editor editor;
Context mContext;
// Shared pref mode
int PRIVATE_MODE = 0;
public SaveData(Context context) {
this.mContext = context;
// Sharedpref file name
final String PREF_NAME = mContext.getString(R.string.app_name) + "_pref";
pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getEditText1() {
return pref.getString(EDIT1, "");
}
public void setEditText1(String text) {
editor.putString(EDIT1, text);
editor.commit();
}
public String getEditText2() {
return pref.getString(EDIT2, "");
}
public void setEditText2(String text){
editor.putString(EDIT2, text);
editor.commit();
}
public String getEditText3() {
return pref.getString(EDIT3, "");
}
public void setEditText3(String text) {
editor.putString(EDIT3, text);
editor.commit();
}
}
Now in onCreate put this
SaveData saveData = new SaveData(this);
mEditText1.setText(saveData.getEditText1());
mEditText2.setText(saveData.getEditText2());
mEditText3.setText(saveData.getEditText3());
And in onPause
SaveData saveData = new SaveData(this);
saveData.setEditText1(mEditText1.getText()+"");
saveData.setEditText2(mEditText2.getText()+"");
saveData.setEditText3(mEditText3.getText()+"");
There are several ways to store data of this type, I would personally use a database table, especially if you are ready have a database as part of your application. If not consider writing and array of strings to file and reading it.
If you are looking at the Database option the do something like
// on create
String createTable = "CREATE TABLE texts (id INT NOT NULL,words TEXT)";
SQLiteDatabase db = MyDatabaseHelper.getDB(); // <- use the method you use to get a db.
db.exec(createTable);
db.close();
// on start up of your edit text activity
// create array of edit texts which you have initialized via their ids, it must be a member variable
EditText[] editTexts = new EditText[]{editText1,editText2,editText3};
SQLiteDatabase db;
String sql= "SELECT * from texts";
Cursor c = db.rawQuery(sql,null);
if(null !=c && c.moveToFirst())
{
for(int i = 0; i<c.getCount(); i++)
{
// get data from db
String text = c.getString(1);
int id = c.getInt(0);
editTexts[id].setText(text);
}
}
// to be called at the end of the activity or when then edit texts change
private void saveToDb(){
SQLiteDataBase db; // got from your sqlite helper method
for(int i =0; i<editTexts.length; i++)
{
// check for insert
String check = "SELECT * FROM texts WHERE id ="+i;
String ins;
Cursor c = db.rawQuery(check,null);
if(null != c && c.moveToFirst()){
// update
ins= "UPDATE texts SET words = '"+editTexts[i].getText().toString+"' WHERE id = "+i+";";
}else{
// insert
ins = "INSERT into texts (id,words) VALUES("+i+",'"+editTexts[i].getText().toString+"');";
}
db.exec(ins);
db.close();
}
}
I have written this without testing it as a guide line, I have used this pattern many times before and it works well
I'm writing an app that manipulates with database consists of 3 tables. I created this database from json file using models (Worker model, specialty model) with getters and setters. Now I want to get specific info from this database. I'v already made it but my code is pretty silly. What I need is to change the architecture of my app but I don't know how exactly it should looks like.
This is the examples of my methods, and they are pretty week
This is how I add info into database. I like it, I think it's correct:
public void addWorker(Worker worker){
List<Specialty> specialty;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//fixind names
String f_name = fixName(worker.getF_name());
String l_name = fixName(worker.getL_name());
String birthday = fixDate(worker.getBirthday());
values.put(KEY_F_NAME, f_name);
values.put(KEY_L_NAME, l_name);
values.put(KEY_BIRTHDAY, birthday);
values.put(KEY_AVATR_URL, worker.getAvart_url());
specialty = worker.getSpecialty();
long worker_id = db.insert(TABLE_WORKERS,null,values);
//add unique specialty
for (Specialty spec: specialty){
createRelations(worker_id, spec.getSpecialty_id());
if (getCount(spec.getSpecialty_id()) == 0){
addSpecialty(spec);
}
}
}
And this is how I take info from database:
public String[] getFullInfo(String worker_name){
String selectQuery = "HUGE QUERY HERE "where workers.f_name =?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {worker_name});
String[] details = new String[5];
c.moveToFirst();
while (c.isAfterLast() == false){
details[0] = c.getString(c.getColumnIndex(KEY_F_NAME));
details[1] = c.getString(c.getColumnIndex(KEY_L_NAME));
details[2] = c.getString(c.getColumnIndex(KEY_BIRTHDAY));
details[3] = c.getString(c.getColumnIndex("age"));
details[4] = c.getString(c.getColumnIndex(KEY_SPEC_NAME));
c.moveToNext();
}
return details;
}
This is my another query and it has different return type:
public List<Map<String ,String>> getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
//making list of workers
List<Map<String ,String>> data = new ArrayList<Map<String,String>>();
c.moveToFirst();
while (c.isAfterLast() == false){
Map<String,String> datum = new HashMap<String,String>(2);
datum.put(KEY_F_NAME, c.getString(c.getColumnIndex(KEY_F_NAME)));
datum.put(KEY_L_NAME, c.getString(c.getColumnIndex(KEY_L_NAME)));
datum.put(KEY_BIRTHDAY, c.getString(c.getColumnIndex(KEY_BIRTHDAY)));
data.add(datum);
c.moveToNext();
}
return data;
}
and the third one, which also have different return type:
public List<String> getAllSpecs_Names(){
List<String> spec_names = new ArrayList<String>();
String selectQuery = "select * from " + TABLE_SPECIALTY;
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()){
do{
spec_names.add(c.getString(c.getColumnIndex(KEY_SPEC_NAME)));
}while (c.moveToNext());
}
return spec_names;
}
I know, that this is all wrong.
Please tell me how I should make all my queries.
It will be good if you give me the link to check how the app should look like
instead of returning a List or Map, you should better return a own CursorWrapper
so you could could look like this:
public WorkerCursor getWorkerListBySpec(String spec_name){
String selectQuery = "HUGE QUERY HERE
"where specialty.spec_name=?";
Log.e(LOG_TAG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, new String [] {spec_name});
return new WorkerCursor(cursor);
}
public static class WorkerCursor extends CursorWrapper {
/**
* Creates a cursor wrapper.
*
* #param cursor The underlying cursor to wrap.
*/
public WorkerCursor(Cursor cursor) {
super(cursor);
}
public Worker getWorker() {
return getWorkerAtCursor();
}
public Worker getWorker(int position) {
if (moveToPosition(position)) {
return getWorkerCursor();
} else {
return null;
}
}
private Worker getWorkerAtCursor() {
if (isBeforeFirst() || isAfterLast()) {
return null;
}
worker worker = new Worker();
worker.name = c.getString(c.getColumnIndex(KEY_F_NAME));
....
return worker;
}
}
and the same for your List, just with a other CursorWrapper
and don't forget to close the CursorWrapper, when it's no more needed, like in onDestroy of Activity and so