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();
}
}
}
Related
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;
}
I am creating an android app that has basically 6 inputs (2 from spinners and the rest textviews) and am using an SQLite Database. I have got as far as when the user clicks on a "start button" the data is saved successfully to the database and also displays on the same activity.
The problem that i am asking help for is.. i want to display the saved data, not on the same activity(screen) in which the data is being saved but on a different activity. So, for instance everything is working in terms of storing and displaying the data on screen 1, but how do i retrieve the data again on screen 2?
Here is the code that i have to save the data (DataBaseHelper):
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,LINETYPE TEXT,PACKAGETYPE TEXT,QUANTITY TEXT,DURATION TEXT,STARTTIME TEXT,ENDTIME TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String linetype, String packagetype, String quantity, String duration, String starttime, String endtime) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,linetype);
contentValues.put(COL_3,packagetype);
contentValues.put(COL_4,quantity);
contentValues.put(COL_5,duration);
contentValues.put(COL_6,starttime);
contentValues.put(COL_7,endtime);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
And some code from the activity:
//INSERT DATA TO DATABASE
boolean isInserted = myDb.insertData(
spinnerSelection,
spinnerSelection2,
q,
d,
formattedtime,
endtimecalc);
if(isInserted == true)
Toast.makeText(screen2.this, "Data Inserted Successfully", Toast.LENGTH_LONG).show();
else
Toast.makeText(screen2.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
//show messages
showMessage("Error", "Nothing Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("ID: " + res.getString(0)+"\n");
buffer.append("LineType: " + res.getString(1)+"\n");
buffer.append("PackageType: " + res.getString(2)+"\n");
buffer.append("Quantity: " + res.getString(3)+"\n");
buffer.append("Duration: " + res.getString(4)+"\n");
buffer.append("StartTime: " + res.getString(5)+"\n");
buffer.append("EndTime: " + res.getString(6)+"\n\n");
}
//SHOW ALL DATA
showMessage("Data", buffer.toString());
}
});
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
So, i now need to display the same information which is being stored from this activity into a new one.
Anyone any thoughts?
ERROR STACK TRACE:
10-05 15:54:58.072 5958-5958/com.example.t_fdonnelly.pharmatest E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.t_fdonnelly.pharmatest, PID: 5958
android.database.CursorIndexOutOfBoundsException: Index 13 requested, with a size of 13
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.t_fdonnelly.tracker.screen2$4.onClick(screen2.java:196)
at android.view.View.performClick(View.java:5653)
at android.view.View$PerformClick.run(View.java:22509)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6144)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
UPDATED CODE:
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
//show messages
showMessage("Error", "Nothing Found");
return;
}
StringBuffer buffer = new StringBuffer();
String getid = res.getString(0);
String getlt = res.getString(1);
String getpt = res.getString(2);
String getqty = res.getString(3);
String getdur = res.getString(4);
String getst = res.getString(5);
String getet = res.getString(6);
if ( res != null && res.moveToFirst()) {
do {
buffer.append(getid);
buffer.append(getlt);
buffer.append(getpt);
buffer.append(getqty);
buffer.append(getdur);
buffer.append(getst);
buffer.append(getet);
} while (res.moveToNext());
}
Intent TransferData = new Intent(getBaseContext(), screen4.class);
TransferData.putExtra("ID", getid);
TransferData.putExtra("LineType", getlt);
TransferData.putExtra("PackageType", getpt);
TransferData.putExtra("Quantity", getqty);
TransferData.putExtra("Duration", getdur);
TransferData.putExtra("Starttime",getst);
TransferData.putExtra("endtime", getet);
startActivity(TransferData);
}
});
}
When you starting new activity via Intent you can put your strings as extras
String id = res.getString(0);
String lineType = res.getString(1);
//rest of cursor logic
sb.append("ID: ").append(id).append("\n");
sb.append("LineType: ").append(lineType).append("\n");
//rest of StringBuffer logic
Intent newActivity = new Intent(this, NewActivity.class);
newActivity.putExtra("ID", id);
newActivity.putExtra("LineType", lineType);
startActivity(newActivity);
In new activity call getIntent() method and retrieve them from it
String id = getIntent().getStringExtra("ID");
First of all
get a unique key for your data in database table like...
public long insertData(String linetype, String packagetype, String quantity, String duration, String starttime, String endtime) {
......
long result = db.insert(TABLE_NAME,null,contentValues);
return result;
}
in calling activity.
long yourUniqueId = myDb.insertData(
spinnerSelection,
spinnerSelection2,
q,
d,
formattedtime,
endtimecalc);
Second
Pass this yourUniqueId with intent as putLong...etc. and get it in Second activity. and fetch the record of corresponding id. and show it.
add new method in database class as. and then call it in second activity with the previous unique_id.
public Cursor getAllData(long uid) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where ID = "+uid,null);
return res;
}
Hi I have a search list in which I want to click on any item. By clicking a particular position, item on that position should open. I have done the following :
public List<DBSearch> searchByName(String name){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from biography where name like '%" + name + "%'", null);
List<DBSearch> dbsearch = new ArrayList<>();
while (cursor.moveToNext()){
DBSearch sea = new DBSearch();
sea.setId(cursor.getLong(0));
sea.setName(cursor.getString(1));
sea.setImage(cursor.getBlob(2));
sea.setComment(cursor.getString(3));
dbsearch.add(sea);
}
cursor.close();
db.close();
return dbsearch;
}
and this is my activity :
private void search(String name) {
persons = (ArrayList<DBSearch>) databaseAdapter.searchByName(name);
SearchAdapter personListAdapter = new SearchAdapter(persons, this);
personListView.setAdapter(personListAdapter);
personListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Intent i = new Intent(getBaseContext(),AWDetailsActivity.class);
String my_id = persons.get(position).getId("id").toString();
i.putExtra("id", my_id);
startActivity(i);
}
}
);
}
Thank you very much.
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();
}
}
I want to add SQLite database value to ListView if record exists, but I'm only getting text from EditText.
Here's what I'm doing
Code from databaseHelper Class
public String ifExistIn(String stationName) {
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
try {
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null));
return stationName;
}
}
Code from activity class
public View.OnClickListener searchStation = new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
String searchString= searchText.getText().toString();
dbHelper.ifExistIn(searchString);
list.add(searchString);
arrayAdapter= new ArrayAdapter<String>(SearchAndReview.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
};
Probably a few mistakes here but from what I can see you can try this:
public String ifExistIn(String stationName) {
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null);
c.moveToFirst();
return c.getString(c.getColumnIndex("stationName"));
}
You have to get the result of the Cursor and interpret it then return it AS String stationName.
And this:
public View.OnClickListener searchStation = new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
String searchString= searchText.getText().toString();
String usethis = dbHelper.ifExistIn(searchString);
list.add(usethis);
arrayAdapter= new ArrayAdapter<String>(SearchAndReview.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
};
You're getting searchString and putting it into your list and not doing anything with the result of your query. You need to assign the result of your query somewhere then use it. Or actually just directly use it in the insert like:
list.add(dbHelper.ifExistsIn(searchString);
Change your method like this:
public String ifExistIn(String stationName){
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
try{
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null))
return c.getString(c.getColumnIndex("columnName"));
}
}
You need to extract data from cursor object. Now you are returning a same value which you are passing.