I have written an app where i have to insert its data into sqlite database and show it on one activity. But my code is showing "No record Found" even if i have inserted it.
I have tried using different options like moving cursor first to the first record and then using loop iterate over the record.
Inserting data into database
private void saveToDB() {
SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ChildMonitoringAppDBHelper.CHILD_NAME, name.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_AGE, age.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_DOB, dob.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_HEIGHT, height.getText().toString());
values.put(ChildMonitoringAppDBHelper.CHILD_WEIGHT, weight.getText().toString());
database.insert(ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null, values);
database.close();
}
Retrieving data from database
public ArrayList<Child> readFromDB()
{
ArrayList<Child> List = new ArrayList<>();
SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getReadableDatabase();
Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), cursor.getString(cursor.getColumnIndex("CHILD_AGE")), cursor.getString(cursor.getColumnIndex("CHILD_DOB")), cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
List.add(child);
cursor.moveToNext();
}
cursor.close();
return List;
}
It should display the record entered but it is making the toast "No Record found".
Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
if (cursor.moveToFirst())
{
do {
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), cursor.getString(cursor.getColumnIndex("CHILD_AGE")), cursor.getString(cursor.getColumnIndex("CHILD_DOB")), cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
List.add(child);
} while (cursor.moveToNext());
}
cursor.close();
return List;
Can you try this code and see it if it works for you?
public ArrayList<Child> readFromDB()
{
List list = new ArrayList<Child>();
Cursor cursor = database.rawQuery("select * from " +
ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
{
do
{
Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")),
cursor.getString(cursor.getColumnIndex("CHILD_AGE")),
cursor.getString(cursor.getColumnIndex("CHILD_DOB")),
cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")),
cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
list.add(child);
}
while (cursor.moveToNext());
}
cursor.close();
// return list of inserted values
return list;
}
Related
Main:
ColegiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ColegDataEditActivity.class);
intent.putExtra("Id", Integer.parseInt(Long.toString(id)));
Log.i("Id",id+"");
startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(MainActivity.this).toBundle());
}
});
DATABASE HELPER:
public Cursor getSpecificData(int id){
SQLiteDatabase db = this. getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM "+ TableName + " WHERE ID ="+id, null);
return data;
}
SECOND ACTIVITY:
Intent intent = getIntent();
int id =intent.getIntExtra("Id",0);
Cursor data = mDatabase.getSpecificData(id);
Hi! I am a beginner with SQL and I don't know what I did wrong. I have a database with multiple columns and I need to get some data from it so then I can put those values in some TextViews. The problem is that the data I need needs to be a single row with the specific id from an item from a ListView (yeah, I now about row id, I solved that problem). Any ideas why isn't it working?
Your Database Helper
public Cursor getSpecificData(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM "+ TableName + " WHERE ID = "+id;
Cursor res = db.rawQuery(query, null);
return res;
}
In Activity make a setViewsfunction
public void setViews() {
Cursor cursor = mDatabase.getSpecificData(id);
try {
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
textview1.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_1_NAME)));
textview2.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_2_NAME)));
//and so on
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I want to show data based on column values, is that possible?
My adapter
public Cursor getDisease() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_GEJALA, new String[]{
KEY_ID,
KEY_GEJALA,
KEY_PENYAKIT,
KEY_AREA,
KEY_KODE_PENYAKIT
},
null,
null,
null,
null,
KEY_GEJALA,
null);
}
My activity then
private void loadListView(View view) {
ListView listView = view.findViewById(R.id.list_view);
arrayList = new ArrayList<>();
Cursor c = sqliteHelper.getDisease();
if (c.moveToFirst()) {
do {
arrayList.add(c.getString(1));
} while (c.moveToNext());
}
adapter = new ListViewAdapter(getActivity(), arrayList, true);
listView.setAdapter(adapter);
}
I am expecting to show code based on category
I'm saving my ArrayList in SQLite. Save codes:
public void HistoryADD(ArrayList<String> full, String owner){
int size = full.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
cv.put(FULL, full.get(i));
cv.put(OWNER, owner);
db.insert(TABLE_NAME, null, cv);
}
System.out.println("added:" + full);
db.close();
}catch (Exception e){
System.out.println("Failed to add" + full);
}
}
And IT's working. I want to get this ArrayLists from SQLite. List Code:
public ArrayList<String> History_list(String owner) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> history_list = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " WHERE owner='"+owner+"'",
new String[] {});
cursor.close();
return history_list;
}
But list code not working. What's wrong in this codes?
Thanks.
You need do something like that:
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
//Here you have to add the item in your array list
}
} finally {
cursor.close();
}
public ArrayList<String> History_list(String owner) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> history_list = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * from " + TABLE_NAME + " WHERE owner"+"=?",new String[] {owner});
while (cursor.moveToNext()){
int owner_value= cursor.getColumnIndex(owner);
if (owner_value>0) history_list.add(cursor.getString(owner));
}
cursor.close();
return history_list;
}
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();
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
// providers data
// db.execSQL("insert into "
// + TABLE_PROVIDERS
// + " (_id, provider_id, parent_id, title, image, sh_n, enable, visible, image_bg, type, is_group, hide_in_search, limit_min, limit_max, off_on_line, invoice_search) "
// + "VALUES (1,600,101,'Источники оплаты','',1,1,0,'','',1,1,0,0,0,0)");
ContentValues cv = new ContentValues();
cv.put("_id", 1);
cv.put("provider_id", 600);
cv.put("parent_id", 101);
cv.put("title", "Bla");
cv.put("image", "bla");
cv.put("sh_n", 1);
cv.put("enable", 1);
cv.put("visible", 1);
cv.put("image_bg", "");
cv.put("type", "");
cv.put("is_group", 1);
cv.put("hide_in_search", 1);
cv.put("limit_min", 10);
cv.put("limit_max", 10000);
cv.put("off_on_line", 1);
cv.put("invoice_search", 1);
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
}
Now I'm doing as was suggested, inserting row by row:
import java.util.*;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
public class ProviderDataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
public ProviderDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public List<Provider> getProvidersByParentId(long parentId) {
List<Provider> providersList = new ArrayList<Provider>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_PROVIDERS, new String[] { "provider_id", "title", "image" }, " parent_id=" + parentId,
null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Provider provider = cursorToProvider(cursor);
providersList.add(provider);
cursor.moveToNext();
}
cursor.close();
System.out.println("getProvidersByParentId");
return providersList;
}
private Provider cursorToProvider(Cursor cursor) {
Provider provider = new Provider();
provider.setId(cursor.getInt(1));
provider.setTitle(cursor.getString(3));
provider.setImg(cursor.getString(4));
return provider;
}
}
It doesn't work. It seems like the row wasn`t inserted and the array returnd by getProvidersByParentId method is empty. Parent_id as argument is 101.
Your insert statement is wrong. In SQLite, you cant insert multiple records by separating them with comma, in fact you need to prepare separate insert commands for that. But if your SQLite version is 3.7.11 then its possible.
Read this.
You can do it with a for loop like this
// add a button click event like
String[] arr1 = new String[n];
String[] arr2 = new String[n];
String[] arr3 = new String[n];
addButton.setOnClickListener
(
new View.OnClickListener()
{
#Override public void onClick(View v) {
for(int i=1;1<4;i++){
try
{
// ask the database manager to add a row given the two strings
//db object of database manager class
db.addValues
(
arr1[i] ,
arr2[i] ,
arr3[i] ,
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
);
// function of insertion
public void addValues(String Col1, String Col2,
String col3)
{
ContentValues values = new ContentValues();
values.put(Columns1, Col1);
values.put(Columns2, Col2);
values.put(Columns3, Col3);
try{
db.insert(Course_Info_Table, null, values);
}
catch(Exception e)
{
}
}
use ContentValues to insert data into table like this.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_id", 1);
cv.put("provider_id", 600);
cv.put("parent_id", 0);
cv.put("title", "Источники оплаты");
cv.put("image", "");
cv.put("sh_n", 1);
cv.put("enable", 1);
cv.put("visible", 0);
cv.put("image_bg", "");
cv.put("type", "");
cv.put("is_group", 1);
cv.put("hide_in_search", 1);
cv.put("limit_min", 0);
cv.put("limit_max", 0);
cv.put("off_on_line", 0);
cv.put("invoice_search", 0);
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
db.close();
for multiple records call this methods multiple times.
public void insertMydata(int _id, int provider_id, int parent_id /*....add more parameters as you required */){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("_id", _id);
cv.put("provider_id", provider_id);
cv.put("parent_id", parent_id);
/*
......
.....
put more code here for other columns
......
*/
db.insertOrThrow(TABLE_PROVIDERS, null, cv);
db.close();
}