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();
Related
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.
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.
I am a newbie in android programming. This is what I have learned from tutorials but I am not able to understand why the app does not store data which i insert. This is my code but whenever I run the application it says data not inserted.
This is DataBaseHelper class
package com.dutt.rishabh.android.sqlite.contacts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Rishabh on 06-07-2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="contacts.db";
public static final String TABLE_NAME="student_contacts";
public static final String id="ID";
public static final String COL_1="NAME";
public static final String COL_2="PHONE NUMBER";
public static final int DATABASE_VERSION=1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query="create table "+TABLE_NAME+"("+id+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_1+" TEXT NOT NULL,"+COL_2+" TEXT NOT NULL"+")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("Drop table if exists "+TABLE_NAME);
onCreate(db);
}
public boolean addData(String name,String num ){
SQLiteDatabase myDb=this.getWritableDatabase();
ContentValues content=new ContentValues();
content.put("NAME",name);
content.put("PHONE NUMBER",num);
long result=myDb.insert(TABLE_NAME,null ,content);
if(result==-1){
return false;
}else{
return true;
}
}
public Cursor viewData(){
SQLiteDatabase myDb=this.getReadableDatabase();
Cursor cr= myDb.rawQuery("Select * from "+DatabaseHelper.TABLE_NAME,null);
return cr;
}
}
**This is MainActivity class**
package com.dutt.rishabh.android.sqlite.contacts;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button add, view;
EditText name, num;
Contact contact;
DatabaseHelper dbHelper= new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.add);
name = (EditText) findViewById(R.id.name);
num = (EditText) findViewById(R.id.num);
view = (Button) findViewById(R.id.view);
//contact = new Contact(name.getText().toString(), num.getText().toString());
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean m = dbHelper.addData(name.getText().toString(),num.getText().toString());
if (m) {
Toast.makeText(MainActivity.this, "Data Inserted!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "Data not Inserted!", Toast.LENGTH_SHORT).show();
}
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor res = dbHelper.viewData();
if (res.getCount() == 0) {
Toast.makeText(getApplicationContext(), "No Data Found", Toast.LENGTH_SHORT).show();
}
StringBuffer sb = new StringBuffer();
while (res.moveToNext()) {
sb.append("ID: " + res.getString(0) + "\n");
sb.append("NAME: " + res.getString(1) + "\n");
sb.append("PHONE NUMBER: " + res.getString(2) + "\n\n");
}
showData("Details",sb.toString());
}
});
}
public void showData(String title, String mess) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(mess);
builder.show();
}
}
I am trying to search and retrieve the result in list view from sqlite database. When I try to search, the app closed.
Logcat
04-20 11:50:56.550 2297-2297/com.example.asus.myapplication3.app
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.asus.myapplication3.app, PID: 2297
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase
com.example.asus.myapplication3.app.dbtry$DatabaseHelper.getReadableDatabase()'
on a null object reference
at com.example.asus.myapplication3.app.searchActivity$1.onClick(searchActivity.java:62)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Code
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.net.ContentHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class ListAdapter extends ArrayAdapter {
List list= new ArrayList();
static class layoutHandler
{
TextView nameText;
}
public ListAdapter(Context context, int resource)
{
super(context, resource);
}
#Override
public void add (Object object){
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
// retern each row of data
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
layoutHandler layouthandler;
if (row==null){
LayoutInflater layoutInflater =(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.result,parent,false);
// row=layoutInflater.inflate(R.layout.listrow,parent,false);
layouthandler=new layoutHandler();
layouthandler.nameText=(TextView)row.findViewById(R.id.nameText);
row.setTag(layouthandler);
}
else
{
layouthandler =(layoutHandler) row.getTag();
}
// return each abject from the list
dataProvider provider=(dataProvider)this.getItem(position);
//assaien each row of data
layouthandler.nameText.setText(provider.getName());
return row;
}
}
public class dataProvider {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public dataProvider(String name) {
this.name = name;
}
}
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class searchActivity extends Activity {
EditText rname;
TextView result;
Button search;
dbtry db;
ListView data;
ListAdapter listAdapter;
String search_name;
SQLiteDatabase sqLiteDatabase;
dbtry.DatabaseHelper dbhlper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
search = (Button) findViewById(R.id.search);
rname = (EditText) findViewById(R.id.rname);
data = (ListView) findViewById(R.id.data);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// setContentView(R.layout.result);
search_name = rname.getText().toString();
//db = new dbtry(getBaseContext());
sqLiteDatabase= dbhlper.getReadableDatabase();
Log.e("the app search ","dbhlper");
db.open();
Cursor d = db.returndata(search_name, sqLiteDatabase);
Log.e("the app search ","yah!");
listAdapter = new ListAdapter(getApplicationContext(), R.layout.listrow);
data.setAdapter(listAdapter);
data.setVisibility(View.GONE);
if (d.moveToFirst()) {
do {
String result_search;
result_search = d.getString(0);
//adding data to adapter
dataProvider provider = new dataProvider(result_search);
listAdapter.add(provider);
Log.e("the app search ","good");
} while (d.moveToNext());
}
// startActivity( new Intent(searchActivity.this, resultActivity.class));
}
}); }}
package com.example.asus.myapplication3.app;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.sql.SQLException;
public class dbtry {
public static int _id;
public static final String ecapp_col_name = "name";
public static final String ecapp_col_discrption = "discrption";
public static final String ecapp_col_ingredant = "ingredant";
// public static final String ecapp_image = "image";
public static final String ecapp_col_Optional_ingredant = "Optional_ingredant";
public static final String TABLE_NAME1 = "recipe";
public static final String TABLE_NAME2 = "ingredant";
public static final String DATABASE_NAME="ecapp";
public static final int DATABASE_VERSION=1;
public static final String DATABASE_create1 = "create"+ TABLE_NAME1+ "("+_id +"int not null auto_increment,"+ecapp_col_name+" text UNIQUE,"+ecapp_col_discrption +"text+ );";
public static final String DATABASE_create2 = "create "+TABLE_NAME2+ "("+ ecapp_col_ingredant+"text ,"+ecapp_col_Optional_ingredant+"text ,"+_id+ "number );";
DatabaseHelper dbh;
Context con;
SQLiteDatabase db2;
public dbtry(Context con)
{
this.con = con;
dbh = new DatabaseHelper(con);
}
public static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper (Context con)
{
super(con,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_create1);
db.execSQL(DATABASE_create2);
Log.d("db created ", "table2");
}
catch (Exception e) {
e.printStackTrace();
Log.e("db not created ", "bad");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS ecapp");
onCreate(db);
}
}
public dbtry open()
{
db2= dbh.getWritableDatabase();
return this;
}
public void close()
{
dbh.close();
}
public void insertData(String name, String ingredant, String discrption) {
ContentValues content = new ContentValues();
content.put(ecapp_col_name, name);
Log.e("db created ", "good");
content.put(ecapp_col_ingredant, ingredant);
Log.e("db created ", "good");
content.put(ecapp_col_discrption, discrption);
Log.e("db created ", "good");
db2.insert("ecapp", null, content);
Log.e("db created ", "good");
}
//retrieve
public Cursor returndata(String sname, SQLiteDatabase sqldb)
{
sqldb = dbh.getReadableDatabase();
String selection, selectionArg;
Cursor query;
String[] projection = {ecapp_col_name};
String[] where = {ecapp_col_name};
query = sqldb.query(TABLE_NAME1, projection,sname,null, null, null, null);
// query = sqldb.query( "select"+ecapp_col_name+ "form" +TABLE_NAME1+"where "+ecapp_col_name+"="+sname+;)
Log.e( "get all data:", "query");
return query;
}
}
In your project's searchActivity, inside search.setOnClickListener before initializing sqLiteDatabase= dbhlper.getReadableDatabase(); add these line db = new dbtry(searchActivity.this); to avoid NullPointerException.
Also comment this line sqLiteDatabase= dbhlper.getReadableDatabase(); since you are already using SQLiteDatabase db2; inside open() method here as
public dbtry open()
{
db2= dbh.getWritableDatabase();
return this;
}
So no need for dbHelper & sqliteDatabase inside searchActivity class, just call db.open(). In case you want to read from database create another method read() similar to your open() method inside dbtry class
public dbtry read()
{
db2= dbh.getReadableDatabase();
return this;
}
Usage: db.read(); call this inside your searchActivity only after intializing db.
Happy coding..!!
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.