cursor is not retrieving data from sqlite database - java

I facing problem in sqlite database. Actually I have 3 .java files and a databse helper class in which my database is created, tables are created insertion etc. all CRUD functions and I am trying to call them from some other activity class but it is not calling and not retrieving data from table. Here are my files please can anyone tell me where i am making mistake.
MainActivity.java
package mad.project;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper m = new DatabaseHelper(this);
m.onCreate();
Button menubutton4 = (Button) findViewById(R.id.InsertRecipeButton);
menubutton4.setOnClickListener(new View.OnClickListener() {
public void onClick(View argo) {
Intent intent4 = new Intent(MainActivity.this, TryActivity.class);
startActivity(intent4);
}
});
}
}
When I click on the button we will reach TryActivity class which is as follows:
package mad.project;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class TryActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.insertrecipe);
final DatabaseHelper m = new DatabaseHelper(this);
final EditText RecipeBox = (EditText) findViewById(R.id.RecipeBox);
Button submit_button = (Button) findViewById(R.id.SubmitRecipe);
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String a=RecipeBox.getText().toString();
m.Insert_Recipe_Into_DB(a);
Intent intent23 = new Intent(TryActivity.this,RoughActivity.class);
startActivity(intent23);
}
});}}
In this class I have created an object 'm' of Databsehelper class which is used to call Insert_Recipe_Into_DB function of DatabaseHelper class. Uptill now no issue if I remove Intents statements from above. But if I call another activity class after calling insertion function it shows "forcesclose" error. the next activity class is as follows:
RoughActivity.java
package mad.project;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class RoughActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final DatabaseHelper m = new DatabaseHelper(this);
String [] rec ;
rec=m.get_recipe();
int rec_len = rec.length;
String [] todaymenu = new String[rec_len];
for(int i = 1;i<=rec_len;i++)
{
todaymenu[i]=rec[i-1];
}
this.setListAdapter(newArrayAdapter<String>(RoughActivity.this,
R.layout.todays_menu_view,R.id.Today,rec));
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
}
DatabaseHelper.java
package mad.project;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper{
static final String dbName="CookBookDatabase";
public DatabaseHelper(Context context)
{
super(context, dbName, null, 33);
// TODO Auto-generated constructor stub
}
static final String Try_Table= "Try_Table";
static final String Recipe= "Recipe";
public void onCreate() {
execSQL("CREATE TABLE "+Try_Table+" ( "+ Recipe + " VARCHAR ) " );
}
private void execSQL(String string) {
// TODO Auto-generated method stub
}
public void Insert_Recipe_Into_DB(String a)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(Recipe, a);
db.insert(Try_Table, Recipe, cv);
db.close();
}
String[] get_recipe()
{
String [] recipe = null;
SQLiteDatabase db=this.getReadableDatabase();
Cursor count =db.rawQuery("SELECT COUNT(*) FROM "+Try_Table, null);
count.moveToFirst();
if(count.getInt(0) == 0)
{
db.close();
return recipe;
}
if(count.getInt(0)!= 0 )
{
Cursor cur=db.rawQuery("SELECT * FROM "+Try_Table, null);
int br_count =cur.getCount();
if(br_count != 0)
{
int i=0, index;
recipe= new String[br_count];
cur.moveToFirst();
do {
index=cur.getColumnIndex(Recipe);
recipe[i++]=cur.getString(index);
}while(cur.moveToNext());
}
}
db.close();
return recipe;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
}
Please tell me where i am making mistake whether in DatabaseHelper class or RoughActivity class.

You need to open your database in the activity you retrieve or insert data into your SQLite database. Also make sure you close it when your finished.
final DatabaseHelper m = new DatabaseHelper(this);
m.open();
In your onDestroy or pause.
Call
m.close();
This may be the issue, because i dont see where you open your database in the code.
EDIT:
In your DatabaseHelper class. Create a method.
public void open(){
db.open();
}
public void close(){
db.close()
}
Then you will have the method to close and open the database in your activities where you need to insert and retrieve information.

Related

how do i make the note deleteable or can be changed

just like the title, i dont know how to make the note deleteable or able to change. after i press the save note button it will stay like that and cannot be change or deleted.
this is the mainactivity code i write
package com.example.test1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.CalendarView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private mySQLiteDBHandler dbHandler;
private EditText editText;
private CalendarView calendarView;
private String selectedDate;
private SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
calendarView = findViewById(R.id.calendarView);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
selectedDate = Integer.toString(year) + Integer.toString(month) + Integer.toString(dayOfMonth);
ReadDatabase(view);
}
});
try {
dbHandler = new mySQLiteDBHandler(this, "CalendarDatabase", null, 1);
sqLiteDatabase = dbHandler.getWritableDatabase();
sqLiteDatabase.execSQL("CREATE TABLE EventCalendar(Date TEXT, Event TEXT)");
}
catch (Exception e){
e.printStackTrace();
}
}
public void InsertDatabase (View view){
ContentValues contentValues = new ContentValues();
contentValues.put("Date",selectedDate);
contentValues.put("Event",editText.getText().toString());
sqLiteDatabase.insert("EventCalendar",null,contentValues);
}
public void ReadDatabase(View view){
String query = "Select Event from EventCalendar where Date =" +selectedDate;
try {
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
cursor.moveToFirst();
editText.setText(cursor.getString(0));
}
catch (Exception e){
e.printStackTrace();
editText.setText("");
}
}
}
it would be nice if i could just stick with 1 button instead of dedicated button to delete the note that has been saved.

Why does my Database not exist in the Main-Activity, when I return back to MainActivity?

in the Mainclass Im creating a variable called mDatabase. In the Mainclass there is a button called Database. When I click on it, it opens a new Activity. Then it starts the onCreate-Method of the second class databasegrocery.
When the program executes the command:
mAdapter=new GroceryAdapter(this, activity.getAllItems());
(...) it returns back to Main-Activity to call the method getAllItems().
When im returning to this method, mDatabase is null (mDatabase was already declared and initialized, when the app started with the MainActivity), why?
As Im totally new to android programing its possible that Im trying something stupid,
so I appreciate your help.
(I read something about activity-lifecycles and I saw that the MainActivity is in Stop-Status, when the second Activity is active. So the data from MainActivity is not destroyed, right?)
If you need more information, tell me!
Thank you.
package com.example.grocerylist;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class MainActivity extends AppCompatActivity{
public SQLiteDatabase mDatabase;
private EditText mEditTextName;
private EditText mEditTextName2;
private EditText mEditTextName3;
private EditText mEditTextName4;
private EditText mEditTextName5;
private EditText mEditTextName6;
private EditText mEditTextName7;
private EditText mEditTextName8;
private EditText mEditTextName9;
Button buttonIncrease;
Button buttonDecrease;
Button buttonAdd;
Button buttonDatabase;
public databasegrocery database;
Intent IntentDatabase;
private TextView mTextViewAmount;
private int mAmount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GroceryDBHelper dbHelper = new GroceryDBHelper(this);
mDatabase = dbHelper.getWritableDatabase();
mEditTextName = findViewById(R.id.edittext_name);
mTextViewAmount = findViewById(R.id.textview_amount);
mEditTextName2=findViewById(R.id.edittext_name2);
mEditTextName3=findViewById(R.id.edittext_name3);
mEditTextName4=findViewById(R.id.edittext_name4);
mEditTextName5=findViewById(R.id.edittext_name5);
mEditTextName6=findViewById(R.id.edittext_name6);
mEditTextName7=findViewById(R.id.edittext_name7);
mEditTextName8=findViewById(R.id.edittext_name8);
mEditTextName9=findViewById(R.id.edittext_name9);
IntentDatabase=new Intent(MainActivity.this,databasegrocery.class);
buttonIncrease = findViewById(R.id.button_increase);
buttonDecrease = findViewById(R.id.button_decrease);
buttonAdd = findViewById(R.id.button_add);
buttonDatabase=findViewById(R.id.buttonDatabase);
buttonDatabase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(IntentDatabase);
}
});
buttonIncrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increase();
}
});
buttonDecrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
decrease();
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItem();
}
});
}
private void increase() {
mAmount++;
mTextViewAmount.setText(String.valueOf(mAmount));
}
private void decrease() {
if (mAmount > 0) {
mAmount--;
mTextViewAmount.setText(String.valueOf(mAmount));
}
}
private void addItem() {
if (mEditTextName.getText().toString().trim().length() == 0 || mAmount == 0) {
return;
}
String name = mEditTextName.getText().toString();
String mkcal1 = mEditTextName2.getText().toString();
String mkcal2=mEditTextName3.getText().toString();
String mFett=mEditTextName4.getText().toString();
String mDavongesaettigtefettsaueren=mEditTextName5.getText().toString();
String mKohlenhydrate=mEditTextName6.getText().toString();
String mZucker=mEditTextName7.getText().toString();
String mEiweiss=mEditTextName8.getText().toString();
String mSalz=mEditTextName9.getText().toString();
//___________________________________________________________________
ContentValues cv = new ContentValues();
cv.put(GroceryContract.GroceryEntry.COLUMN_NAME, name);
cv.put(GroceryContract.GroceryEntry.COLUMN_AMOUNT, mAmount);
//----------------------------------------------------------------------------------------
cv.put(GroceryContract.GroceryEntry.COLUMN_KCAL1, mkcal1);
cv.put(GroceryContract.GroceryEntry.COLUMN_KCAL2, mkcal2);
cv.put(GroceryContract.GroceryEntry.COLUMN_FETT, mFett);
cv.put(GroceryContract.GroceryEntry.COLUMN_DAVONGESAETTIGTEFETTSAEUREN, mDavongesaettigtefettsaueren);
cv.put(GroceryContract.GroceryEntry.COLUMN_Kohlenhydrate, mKohlenhydrate);
cv.put(GroceryContract.GroceryEntry.COLUMN_Zucker, mZucker);
cv.put(GroceryContract.GroceryEntry.COLUMN_EIWEIS, mEiweiss);
cv.put(GroceryContract.GroceryEntry.COLUMN_SALZ, mSalz);
//------------------------------------------------------------------------------------------
mDatabase.insert(GroceryContract.GroceryEntry.TABLE_NAME, null, cv);
databasegrocery.mAdapter.swapCursor(getAllItems());
mEditTextName.getText().clear();
mEditTextName2.getText().clear();
mEditTextName3.getText().clear();
mEditTextName4.getText().clear();
mEditTextName5.getText().clear();
mEditTextName6.getText().clear();
mEditTextName7.getText().clear();
mEditTextName8.getText().clear();
mEditTextName9.getText().clear();
}
public Cursor getAllItems() {
return mDatabase.query(GroceryContract.GroceryEntry.TABLE_NAME, null, null, null, null, null, GroceryContract.GroceryEntry.COLUMN_TIMESTAMP + " ASC");
}
}
package com.example.grocerylist;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class databasegrocery extends AppCompatActivity {
public static GroceryAdapter mAdapter;
public MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databasegrocery);
activity=new MainActivity();
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new GroceryAdapter(this, activity.getAllItems());
recyclerView.setAdapter(mAdapter);
}
}

data in the row is not deleted from table

when I click delete it doesn't delete or edit the row I created
so my MainActivity is
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.Table_Name;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col1;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col2;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
FloatingActionButton fab;
DatabaseHelper mydb;
ListView listView;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb =new DatabaseHelper(this);
fab= (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(this);
ListView listView = (ListView)findViewById(R.id.list);
registerForContextMenu(listView);
}
#Override
public void onResume() {
super.onResume();
ArrayList<String> theList =new ArrayList<>();
Cursor data= mydb.getAllData();
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(null);
if (data.getCount()==0){
Toast.makeText(MainActivity.this,"data not inserted",Toast.LENGTH_LONG).show();
}
else
{
while(data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.edit:
// int count= mydb.updaterow(getString(col2),EditText.)
return true;
case R.id.delete:
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onClick(View v) {
Intent intent= new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
My DataBasehelper class
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by BHUSHAN on 24-08-2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String Database_Name = "Memo.db";
public static final String Table_Name = "Memo";
public static final String col1 = "ID";
public static final String col2 = "data";
//DatabaseHelper mydb;
public DatabaseHelper(Context context) {
super(context, Database_Name, null, 1);
//mydb=new DatabaseHelper(context);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Name + "(ID integer primary key autoincrement, data text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + Table_Name);
onCreate(db);
}
public boolean insertData(String data, String Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, Data);
long result = db.insert(Table_Name, null, contentValues);
if (result==-1)
return false;
else
return true;
}
public ArrayList<String> getList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.query(Table_Name,new String[]{col1},new String(col2),null,null,null,null);
while (cursor.moveToNext()){
int index= cursor.getColumnIndex(col1);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + Table_Name, null);
return res;
}
public int deleterow(String col1) {
String whereClause = "ID = ?";
String[] whereArgs = {String.valueOf(col1)};
SQLiteDatabase db = this.getWritableDatabase();
int count = db.delete(Table_Name, whereClause, whereArgs);
db.close();
return count;
}
/* public int updaterow(String oldname, String newdata){
SQLiteDatabase db= mydb.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(DatabaseHelper.col2,newdata);
String[] whereargs={oldname};
int count = db.update(Table_Name,cv, DatabaseHelper.col2+"=?" , whereargs);
return count;
}*/
}
my Main2Activity class where I edit and insert data
package com.frolicfreak.bhushan.memo;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
DatabaseHelper db;
EditText Data;
FloatingActionButton add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
db = new DatabaseHelper(this);
Data = (EditText)findViewById(R.id.edit);
add =(FloatingActionButton)findViewById(R.id.add);
AddData();
}
public void AddData(){
add.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
db.insertData(Data.getText().toString(),
Data.getText().toString() );
if (isInserted==true)
Toast.makeText(Main2Activity.this,"data
inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Main2Activity.this,"data not
inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
please help me I'm new to programming so I'm trying to learn here
thankyou in advance
and I actually need help with editing and saving the data too I wrote the code but I saved it in the comments
Your delete function is working fine according to the code. Check the return is greater than 0 or not.
But you won't be able to see the changes in the ListView because you have to populate the list again.
Set an CursorAdapter since you're using a database to link to the listview and use CursorAdapter.notifyDataSetChanged()
Or create a method that will recreate the listview when a delete occurs.
ArrayList<String> COUNTRIES = new ArrayList<>();
public void refreshView() {
MyDatabase database = new MyDatabase(ViewList.this);
Cursor cursor = database.fetchAllData();
COUNTRIES.clear();
while (cursor.moveToNext()) {
String temp = cursor.getString(cursor.getColumnIndex(database.COL1));
COUNTRIES.add(temp);
}
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRIES);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(arrayAdapter);
}
When deleting, you are calling this
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
You are not passing the id of selected item, but you are passing menu item's string fetched by getString(...) method, which is weird. There are so much unused code in your class.
I advice you to work on BaseAdapter and ListView.
It's not a good programming pattern to call onResume() method. You should extract it to different method and call it in onResume().
Anyway, in this case notifyDataSetChanged() is a solution what you are looking for.

Retrieve data into EditText from SQL Lite Database

I am currently working on a small application which allows a persons details to be stored in a database and then retrieved into an EditText field. Currently i am able to store a persons name into the database. But i am having trouble retrieving this data.
Any help anyone can give would be greatly appreciated!
Thanks!
DatabaseHelper.java:
package my.example.com.mymedicare;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "user.db", null, 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Users (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , FullName VARCHAR, Email VARCHAR, Number INTEGER, Age INTEGER, Nurse VARCHAR)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Users");
// Create tables again
onCreate(db);
}
}
SQLHelper.java:
package my.example.com.mymedicare;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class SQLHelper {
Context mContext;
DatabaseHelper dbHelper;
public SQLHelper(Context mContext) {
dbHelper = new DatabaseHelper(mContext);
this.mContext = mContext;
}
public boolean insert(String FullName, int i){
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("FullName", FullName);
db.close();
return true;
}
}
Register.java:
package my.example.com.mymedicare;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
};
public void btnCreate(View view) {
SQLHelper sqlHelper = new SQLHelper(this);
EditText addName = (EditText) findViewById(R.id.nameText);
sqlHelper.insert(addName.getText().toString(), 0);
Toast.makeText(this, "Your Account Details Have Been Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Register.this, MainMenu.class));
}}
Modify.java:
package my.example.com.mymedicare;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class Modify extends AppCompatActivity {
static SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify);
EditText getName=(EditText)findViewById(R.id.nameText);
}
}
Follow this step.
put this method in SQLHelper.java file.
public ArrayList<String> fetch_Edittext() {
ArrayList<String> arr_ = new ArrayList<String>();
String selectQuery = "Select * FROM " + TABLE_SCANITEMS + " ORDER BY id";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
arr_.add(cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return arr_;
}
put this class in your modify java class
private class GetEdittext extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// dialog start
Log.e("Currency", "3");
}
#Override
protected Void doInBackground(Void... arg0) {
ArrayList<String> arr_ = new ArrayList<String>();
arr_ = db.fetch_Edittext();
return null;
}
#Override
protected void onPostExecute(Void resul) {
super.onPostExecute(resul);
// dialog dismiss
//hear set your edit text
}
}
then call this class at on create method like.
new GetEdittext().execute();

show data from database to listView Android

I am trying to show all my data from my database into the listview
Code to create database:
DataHander.java
package com.example.testingforstack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandler {
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String TABLE_NAME = "mytable";
public static final String DATA_BASE_NAME = "mydatabase";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_CREATE = "create table mytable (name text not null, email text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
}
public static class DataBaseHelper extends SQLiteOpenHelper{
public DataBaseHelper(Context ctx) {
super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
try{
db.execSQL(TABLE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getReadableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String name, String email){
ContentValues content = new ContentValues();
content.put(NAME, name);
content.put(EMAIL, email);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null);
}
}
mainActivity.java
package com.example.testingforstack;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save, load;
EditText name, email;
DataHandler handler;
String getName, getEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button) findViewById(R.id.save);
load = (Button) findViewById(R.id.load);
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName = name.getText().toString();
String getEmail = email.getText().toString();
handler = new DataHandler(getBaseContext());
handler.open();
long id = handler.insertData(getName, getEmail);
insertSuccess();
//Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getName = "";
getEmail = "";
handler = new DataHandler(getBaseContext());
handler.open();
Cursor C = handler.returnData();
if(C.moveToFirst()){
do{
getName = C.getString(0);
getEmail = C.getString(1);
}while(C.moveToNext());
}
handler.close();
loadSuccess();
//Toast.makeText(getBaseContext(), "Name: "+getName+", Email: "+getEmail, Toast.LENGTH_LONG).show();
}
});
}
public void insertSuccess()
{
AlertDialog.Builder insertData = new AlertDialog.Builder(this);
insertData.setTitle("Info");
insertData.setMessage("Data Inserted");
insertData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
insertData.show();
}
public void loadSuccess()
{
AlertDialog.Builder loadData = new AlertDialog.Builder(this);
loadData.setTitle("Info");
loadData.setMessage("Name: "+getName+" & your email: "+getEmail);
loadData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
loadData.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I have two button save and load. I have successfully implemented the save button to save the user name and email. However, I don't really know to load the data into the listview. How to do that?
In listview you can use different types of adapters. For database, most appropriate is to use cursorAdapter where you tell which cursor to use. You can also manually walk through elements in DB and save them in some other object in array and then you can have arrayAddapter in which you pass your array of object. In each case you must set binder or override method onCreateView where you tell which parameter go in which child.
You can look this http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html example for more information.

Categories

Resources