Copy and display data from one sqlite table to another at runtime - java

I am trying to make an android application that allows the user to create a custom workout list from an already existing list of workouts. I decided to create an sqlite database to accomplish this task. In my database handler class "DBHandles.java" I have created and populated "Table_Workouts" with all the available workouts in the application. Also in "DBHandles.java" I have created another empty table "Table_User_List" for the purpose of holding specific entries from the "Table_Workouts" table that the user selects. "Table_User_List" needs to be populated at runtime.
public class DBhandles extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Workouts.db";
public static final String TABLE_WORKOUTS = "Workouts";
public static final String TABLE_USER_LIST = "UserWorkouts";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_LINK = "link";
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_WORKOUTS_TABLE = "CREATE TABLE " +
TABLE_WORKOUTS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
String CREATE_USER_TABLE ="CREATE TABLE " +
TABLE_USER_LIST + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_DESCRIPTION + " TEXT,"
+ COLUMN_LINK + " TEXT" + ")";
db.execSQL(CREATE_WORKOUTS_TABLE);
db.execSQL(CREATE_USER_TABLE);
db.execSQL("INSERT INTO " + TABLE_WORKOUTS + "(name, description, link) VALUES ('Shoulder Press', 'Shoulder PRess description', 'https://www.youtube.com/watch?v=qEwKCR5JCog')");
public void addWorkout(Workout workout) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, workout.getWorkoutName());
values.put(COLUMN_DESCRIPTION, workout.getDescription());
values.put(COLUMN_LINK, workout.getLink());
db.insert(TABLE_USER_LIST, null, values);
} catch (Exception e){
Log.d(TAG, "Error while trying to add");
}
finally{
db.endTransaction();
}
//db.close();
}
public Workout findWorkout(String Workoutname) {
String query = "SELECT * FROM " + TABLE_WORKOUTS
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
workout.setID(Integer.parseInt(cursor.getString(0)));
workout.setWorkoutName(cursor.getString(1));
workout.setDescription((cursor.getString(2)));
workout.setLink(cursor.getString(3));
cursor.close();
} else {
workout = null;
}
db.close();
return workout;
}
public boolean deleteWorkout(String Workoutname) {
boolean result = false;
String query = " SELECT * FROM " + TABLE_USER_LIST
+ " WHERE " + COLUMN_NAME
+ " = \"" + Workoutname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Workout workout = new Workout();
if (cursor.moveToFirst()) {
workout.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_WORKOUTS, COLUMN_ID + " = ?",
new String[] { String.valueOf(workout.getID()) });
cursor.close();
result = true;
}
db.close();
return result;
}
public ArrayList getAllWorkoutNames (){
return genericGetSQL(TABLE_WORKOUTS, COLUMN_NAME);
}
public ArrayList genericGetSQL(String whichTable, String whichColumn){
ArrayList<String> wrkArray = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(whichTable, new String[]{whichColumn}, null,null, null, null,null);
String fieldToAdd = null;
if(cursor.moveToFirst()){
while(cursor.isAfterLast()==false){
fieldToAdd = cursor.getString(0);
wrkArray.add(fieldToAdd);
cursor.moveToNext();
}
cursor.close();
}
return wrkArray;
}
As you can see I am returning an Arraylist from the DBHandles.class to display the name column of the "Table_Workouts" table. This ArrayList is accessed in my "DisplayAllWorkouts.java" class. The "DiplayAllWorkouts.java" class generates a tablerow for each entry in the "Table_Workouts" table and displays the name column to the user.
public class DisplayAllWorkouts extends AppCompatActivity implements YourListFrag.OnFragmentInteractionListener {
DBhandles db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayworkoutlist);
yourListFrag = new YourListFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.LinLayDisplayYourList, yourListFrag, "ARG_PARAM1").
commit();
context = this;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText = {"NAME ", " ADD "};
for (String c : headerText) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setTextSize(18);
tv.setPadding(5, 5, 5, 5);
tv.setText(c);
rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);
db = yourListFrag.getDb();//new DBhandles(this, null, null, 1);
final ArrayList<String> arrNames = db.getAllWorkoutNames();
final ArrayList<String> arrDesc = db.getAllWorkoutDescription();
final ArrayList<String> arrLink = db.getAllWorkoutsLink();
for (int i = 0; i < arrNames.size(); i++) {
TableRow row = new TableRow(this);
final CheckBox AddBox = new CheckBox(this);
AddBox.setText("ADD");
final TextView nametv = new TextView(this);
//final TextView desctv = new TextView(this);
//final TextView linktv = new TextView(this);
nametv.setTextSize(30);
// desctv.setTextSize(30);
nametv.setText(arrNames.get(i));
//desctv.setText(arrDesc.get(i));
//linktv.setText(arrLink.get(i));
text = nametv.getText().toString();
row.addView(nametv);
row.addView(AddBox);
AddBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
// if(AddBox.isChecked()){
Workout wrk = (db.findWorkout(text));
db.addWorkout(wrk);
yourListFrag.refresh();
// yourListFrag.refresh();
// yourListFrag.refresh(text);
// }
// else{
// db.deleteWorkout(text);
//yourListFrag.delete(nametv.getText().toString());
// yourListFrag.refresh();
// }
}
});
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(DisplayAllWorkouts.this, DisplaySingleWorkout.class);
i.putExtra("itemName", nametv.getText());
i.putStringArrayListExtra("everydesc", arrDesc);
i.putStringArrayListExtra("everyname", arrNames);
i.putStringArrayListExtra("everylink",arrLink);
startActivity(i);
}
});
tableLayout.addView(row);
}
}
#Override
public void onFragmentInteraction(int position) {
}
}
My problem is as follows. I want to be able to click on a table row displayed in the "DisplayAllWorkouts.java" class and have the corresponding row in "Table_Workouts" table be copied to the "Table_User_List" table. Once the row is copied I want the name column of "Table_User_List" displayed in "YourListFrag.java" class and inflated in the "DisplayAllWorkouts.java" class.
public class YourListFrag extends Fragment {
private ArrayAdapter<String> arrayAdapter;
private ListView lstView;
public ArrayList<String> holdNamesFromDB;
final DBhandles db = new DBhandles(getContext(), null, null, 1);
public DBhandles getDb(){
return this.db;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_list, container, false);
lstView = (ListView)rootView.findViewById(R.id.lstView);
holdNamesFromDB = db.getAllUserWorkouts();
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, holdNamesFromDB);
lstView.setAdapter(arrayAdapter);
public void refresh(){//String text){
//arrayAdapter.add(text);
// db.getAllUserWorkouts();
// arrayAdapter.notifyDataSetChanged();
holdNamesFromDB = db.getAllUserWorkouts();
//arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, db.getAllUserWorkouts());
arrayAdapter.notifyDataSetChanged();
// arrayAdapter.notifyDataSetChanged();
//
}
I need the fragment to refresh its view everytime a new entry is added to the "Table_User_List" so the user can see every entry of the name column of "Table_User_List" in real time. I put logs in my program and the the flow seemed to successfully reach all the appropriate method calls without throwing an error or crashing. However, my program does not display the entries from Table_User_List in the "YourListFrag.java" class. I don't know if their is a problem copying the row from one sqlite table to the other, displaying and refershing the name column in the fragment or inflating the fragment into "DisplayAllWorkouts.java" class. I have been struggling with this problem for awhile now and I finally decided to reach out to the community that has always been there for me. I have referenced the following sqlite copy data from one table to another
and i can't tell if this approach actually works in my program because nothing is displayed in the fragment. Thank you for your time and effort. I apologize for the lines of code i commented out and posted. I have been trying everything i could think of.

Related

SUMming column values based on String ID and set result to a TextView

The question might seen repeated, but I've looked for a solution before posting it and I couldn't find a solution. I'm trying to perform a SUM of column values based on a string passed by the user, but I think I'm doing it wrong on my MainActivity.java or on my DatabaseAccess.java because my app crashs when the string is passed.
Here is my DatabaseAccess.java method:
public String SumMoneyValues (String id){
Cursor cursor = database.rawQuery("SELECT SUM(" + valueColumn + ") as Total FROM " + tableName + " where " + idColumn + " like ?", new String [] { "%" + id + "%" }, null);
String total = "";
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
total = String.valueOf(cursor.getDouble(cursor.getColumnIndex("Total")));
cursor.moveToNext();
}
cursor.close();
return total;
}
I'm using an external database with 5 TEXT columns and 1 DOUBLE column (valueColumn).
On my MainActivity, I've set a TextView and initialized it. Here is my database columns:
private static String idColumn = "tag_id";
private static String firstnameColumn = "first_name";
private static String lastnameColumn = "last_name";
private static String phoneColumn = "phone";
private static String addressColumn = "address";
private static String emailColumn = "email";
private static String valueColumn = "valor";
By the way, my search method is working fine:
public List<Contact> getTagDataById(String id) {
List<Contact> list = new ArrayList<>();
Cursor cursor = database.rawQuery("select * from " + tableName + " where " + idColumn + " like ?", new String[] { "%" + id + "%" });
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Contact contact = new Contact();
contact.setFirstName(cursor.getString(0));
contact.setLastName(cursor.getString(1));
contact.setPhone(cursor.getString(2));
contact.setEmail(cursor.getString(3));
contact.setTagId(cursor.getString(4));
contact.setValor(cursor.getString(5));
list.add(contact);
cursor.moveToNext();
}
cursor.close();
return list;
}
This is what I'm trying to implement on my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
initData();
initView();
initClick();
// Find the GUI components
this.databaseAccess = DatabaseAccess.getInstance(getApplicationContext());}
private String SumMoneyValues (String str) {
databaseAccess.open();
String soma = databaseAccess.SumMoneyValues(str);
databaseAccess.close();
return soma;
}
private void initView() {
swTotalSum = (TextView)findViewById(R.id.swTotalSum);
initListView();
}
...
String testeSoma = SumMoneyValues(epctag);
if (testeSoma != null){
swTotalSum.setText(testeSoma);
} else{
epcTTS.speak("Something went wrong!", TextToSpeech.QUEUE_FLUSH, null);
}
What is the code to call the SumMoneyValues method on my MainActivity? Sorry, newbie here.

Unable to insert data into database within fragment

I'm using fragment to create tabs, and I'm trying to insert information from the fragment to my database.
So I've 3 RadioGroup and I'm adding to the database the 'Checked' radio button that the user has marked, and I'm not able to add into the database the data because the following error:
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
There are DatabaseHandler functions (which works) that I use such as
db.checkSetting() - Check if the database table is empty, if empty return false, if not return true.
db.updateSetting() - Update the data inside the table.
db.addSetting() - Create new table with new data.
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
//table name
private static final String TABLE_DETAILS = "details";
private static final String TABLE_FOOD = "food";
private static final String TABLE_OLDDETAILS = "oldDetails";
private static final String TABLE_SETTING = "setting";
//Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_HEIGHT = "height";
private static final String KEY_WEIGHT = "weight";
private static final String KEY_CALORIES = "calories";
private static final String KEY_DATE = "date";
private static final String KEY_LEVEL = "level";
private static final String KEY_DURATION = "duration";
private static final String KEY_DAYS = "days";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DETAILS_TABLE = "CREATE TABLE " + TABLE_DETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_FOOD_TABLE = "CREATE TABLE " + TABLE_FOOD + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_CALORIES + " INTEGER " + ")";
String CREATE_OLDDETAILS_TABLE = "CREATE TABLE " + TABLE_OLDDETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_SETTING_TABLE = "CREATE TABLE " + TABLE_SETTING + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_LEVEL + " INTEGER," + KEY_DURATION + " INTEGER," + KEY_DAYS + " INTEGER " + ")";
db.execSQL(CREATE_OLDDETAILS_TABLE);
db.execSQL(CREATE_DETAILS_TABLE);
db.execSQL(CREATE_FOOD_TABLE);
db.execSQL(CREATE_SETTING_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_OLDDETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOOD);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTING);
// Create tables again
onCreate(db);
}
public boolean addSetting(int level, int duration, int days) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, 1);
values.put(KEY_LEVEL, level);
values.put(KEY_DURATION, duration);
values.put(KEY_DAYS, days);
// Inserting Row
long result = db.insert(TABLE_SETTING, null, values);
if(result == -1){
return false;
}
else{
return true;
}
}
public boolean checkSetting(){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
Cursor cursor = db.rawQuery(selectQuery, null);
Boolean rowExists;
if (cursor.moveToFirst())
{
// DO SOMETHING WITH CURSOR
rowExists = true;
} else
{
// I AM EMPTY
rowExists = false;
}
return rowExists;
}
public setting getSetting() {
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
setting set = new setting(cursor.getInt(1), cursor.getInt(2), cursor.getInt(3));
return set;
}
public int updateSetting(setting set) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LEVEL, set.getLevel());
values.put(KEY_DURATION, set.getDuration());
values.put(KEY_DAYS, set.getDays());
Log.d("UPDATE: ", "updated all");
// updating row
return db.update(TABLE_SETTING, values, KEY_ID + " = ?", new String[] { String.valueOf(1) });
}
Fragment:
public class PageFragment extends Fragment {
DatabaseHandler db = new DatabaseHandler(getActivity()); //DATABASE
private int group1;
private int group2;
private int group3;
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_training, container, false);
ViewStub stub = (ViewStub) view.findViewById(R.id.stub);
if(mPage == 1) { // mPage represents the ID of the tab/page/fragment that in use.
stub.setLayoutResource(R.layout.fragment_trainingone); // Sets resource for each fragment
View inflated = stub.inflate();
return inflated;
}
else{
stub.setLayoutResource(R.layout.fragment_trainingtwo);
View inflated = stub.inflate();
RadioGroup rg1 = (RadioGroup) inflated.findViewById(R.id.group1);
RadioGroup rg2 = (RadioGroup) inflated.findViewById(R.id.group2);
RadioGroup rg3 = (RadioGroup) inflated.findViewById(R.id.group3);
Button update = (Button) inflated.findViewById(R.id.update);
rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
group1 = 1;
break;
case R.id.radio2:
group1 = 2;
break;
case R.id.radio3:
group1 = 3;
break;
}
}
});
rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio11:
group2 = 1;
break;
case R.id.radio22:
group2 = 2;
break;
case R.id.radio33:
group2 = 3;
break;
}
}
});
rg3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio111:
group3 = 1;
break;
case R.id.radio222:
group3 = 2;
break;
case R.id.radio333:
group3 = 3;
break;
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
setting set = new setting(group1, group2, group3);
if (db.checkSetting()) {
db.updateSetting(set);
} else {
db.addSetting(group1, group2, group3);
}
}
});
return inflated;
}
}
}
How can I insert data into database within fragment and avoiding NullPointerException?
You're calling
DatabaseHandler db = new DatabaseHandler(getActivity());
before the Activity is even attached to the Fragment. Initialise it in the onCreate(), or onAttach() method, so getActivity() doesn't return null.
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
According to Exception You Have to open database before querying from it follow the below linked post
public void openDataBase() throws SQLException
{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
SQLite database status on app uninstall

How do I delete by ID in SQLite?

I am quite new Android Development and figured I should start by trying to create a simple ToDo List App using SQLite. I have all of the basic functionality in place: adding, updating, and deleting tasks. However, I am adding, updating, and deleting by the title of the task, rather than by the ID. This creates problems with duplicate tasks (e.g. tasks of the same name are deleted simultaneously). After much internet search, I still cannot find a way to do this. I would appreciate any help offered!
Here's my code:
public class TaskDbHelper extends SQLiteOpenHelper {
public TaskDbHelper(Context context) {
super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " +
TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL, " +
TaskContract.TaskEntry.COL_TASK_DATE + " DATE);";
sqLiteDatabase.execSQL(createTable);
}
}
Activity where tasks are shown
public class ShowTaskActivity extends AppCompatActivity {
private TaskDbHelper mHelper;
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
mHelper = new TaskDbHelper(this);
mTaskListView = (ListView) findViewById(R.id.list_todo);
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase sqLiteDatabase = mHelper.getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(
TaskContract.TaskEntry.TABLE, // Name of the table to be queried
new String[]{ // Which columns are returned
TaskContract.TaskEntry._ID,
TaskContract.TaskEntry.COL_TASK_TITLE,
TaskContract.TaskEntry.COL_TASK_DATE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int index = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(index));
}
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
task, // What view to use for the items
R.id.task_title, // Where to put the string of data
taskList); // Where to get the data
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
cursor.close();
sqLiteDatabase.close();
}
// TODO: Change to delete by ID, not name
public void deleteTask(View view) {
View parent = (View) view.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
String task = taskTextView.getText().toString();
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
TaskContract.TaskEntry.COL_TASK_TITLE + " = ?", // Boolean check
new String[]{task}); // What to delete
sqLiteDatabase.close();
updateUI();
}
}
Task adding Code
public void addTask(String task, String date) {
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
contentValues.put(TaskContract.TaskEntry.COL_TASK_DATE, date);
sqLiteDatabase.insertWithOnConflict(
TaskContract.TaskEntry.TABLE,
null,
contentValues,
SQLiteDatabase.CONFLICT_REPLACE);
sqLiteDatabase.close();
}
String rowId; //Set your row id here
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
TaskContract.TaskEntry.TABLE, // Where to delete
KEY_ID+" = ?",
new String[]{rowId}); // What to delete
sqLiteDatabase.close();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",new String[]{Long.toString(id)} );
db.close();
You can try this method to delete By id
public void deleteData(String tableName, Integer id) {
try {
if (mWritableDB != null) {
mWritableDB.execSQL("delete from " + tableName + " Where id = " + id);
}
} catch (Exception _exception) {
_exception.printStackTrace();
}
}

How to get data from database on click of an event?

I am generating an events dynamically. These events data I am storing in sqlite database. Now I want to retrieve data of the clicked event. I tried to retrieve data but always getting 0th id data.
Generating events function :
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
This is my attempt to get data:
db = new EventTableHelper(getApplication());
eventData = new EventData();
if(editMode)//true
{
eventData = events.get(id);
Toast.makeText(getApplicationContext(),String.valueOf(id),Toast.LENGTH_LONG).show();
title.setText(eventData.getTitle());
eventTitle = title.getText().toString();
db.updateEvent(eventData);
Toast.makeText(getApplicationContext(),"Edit mode",Toast.LENGTH_LONG).show();
Log.i("Log","save mode");
}
I have EventTableHelper in that i have created functions to get event,update and delete events.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE,KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I want to show data and update data if changes made.
Whats going wrong?

Android: How to display string on textview from console

I'm trying to display string on the textview. I'm succesfully able to print it on the console from database, but I'm not able to figure out how to print all the strings on different different textviews. Here is my code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText search;
Button insert;
TextView txt1, txt2, txt3, txt4, txt5;
DatabaseHandler db;
List<History> history;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
search = (EditText) findViewById(R.id.search_word);
insert = (Button) findViewById(R.id.insert);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
txt3 = (TextView) findViewById(R.id.txt3);
txt4 = (TextView) findViewById(R.id.txt4);
txt5 = (TextView) findViewById(R.id.txt5);
insert.setOnClickListener(this);
history = db.getAllHistory();
}
public void onClick(View v) {
db.addHistory(new History(search.getText().toString(), null));
Toast.makeText(getApplicationContext(),
"Inserted: " + search.getText().toString(), Toast.LENGTH_LONG)
.show();
}
#Override
protected void onStart() {
super.onStart();
List<History> history = db.getAllHistory();
for (History cn : history) {
String log = "Search Strings: " + cn.getName();
Log.d("Search Strings: ", log);
}
}
}
This is my activity in which I'm bringing my all database value on onStart() function. Now here I have to set all the data coming from database on the textview. Here is my DabaseHandler class in which I'm taking out each row.
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "historyManager";
private static final String TABLE_HISTORY = "histories";
private static final String KEY_NAME = "history";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_HISTORY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
void addHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
db.insert(TABLE_HISTORY, null, values);
db.close();
}
History getHistory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HISTORY, new String[] { KEY_NAME },
"=?", new String[] { String.valueOf(id) }, null, null, null,
null);
if (cursor != null)
cursor.moveToFirst();
History history = new History(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return history;
}
public List<History> getAllHistory() {
List<History> historyList = new ArrayList<History>();
String selectQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
History contact = new History();
contact.setName(cursor.getString(0));
historyList.add(contact);
} while (cursor.moveToNext());
}
return historyList;
}
public int updateHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
return db.update(TABLE_HISTORY, values, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
}
public void deleteHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HISTORY, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
db.close();
}
public int getHistoryCount() {
String countQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Please help in getting data printed on the textview. On the Log.d I can see all my data coming, one after another. But I'm not able to print all the data.
It's answer for "Thank You for that. Can you tell me how to set the data which I have printed in MainActivity on onStart() method (Log.d("")). If you can give me the code for that, that will be much easier for me."
try this:
List<String> listNames = new ArrayList<String>();//global variable
List<History> history = db.getAllHistory();
for (History cn : history) {
listNames.add(cn.getName());
}
or, if have in History field date try is, after easy will sort:
Map<String, Date> historyMap = new HashMap<String, Date>();
List<History> history = db.getAllHistory();
for (History cn : history) {
historyMap.put(cn.getName, cn.getDate);
}
You need make ListView in which will show your data from DB.Because you have many items datas getting from db.
I suggest to the next version:
In xml file you creat:
<ListView
android:id="#+id/list_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...>
You need create Adapter for your list with next xml resource:
<TextView
android:id="#+id/text_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
In java code:
in onCreate:
ListView list = (ListView) findViewById(R.id.list);
OurAdapter adapter = new OurAdapter(..., List<String> yourListWithName);
list.setAdapter(adapter);
if you want a more detailed description of the code tell me.
For add last item in top you need next, create spec. internal class :
class Holder implements Comparable<Holder> {
String key;
Double value;
public int compareTo(Holder another) {
return another.value.compareTo(value);
}
}
and use him how:
List<this.Holder> listSortforLastInTop = new ArrayList<this.Holder>();
and
for(...){
Holder holder = new Holder();
holder.key=...;
older.value=..;
listSortforLastInTop.add(holder);
}

Categories

Resources