I have an application in which I'm trying to add user info inside a table created using SQLlite. The problem is when I press the add button the application crashes. bellow I include all the code and logcat.
MainActivity.java
package com.example.asus.sqlliteproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DataBaseHelper myDB;
EditText Name,LastName,Grades;
Button AddData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DataBaseHelper(this);
Name = (EditText)findViewById(R.id.name);
LastName = (EditText)findViewById(R.id.lastName);
Grades = (EditText)findViewById(R.id.Grades);
AddData = (Button)findViewById(R.id.addDataButton);
addData();
}
public void addData () {
AddData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean inserted = myDB.insertData(Name.getText().toString(),
LastName.getText().toString(),
Grades.getText().toString());
if (inserted){
Toast.makeText(MainActivity.this,"Text Inserted!", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this,"Unsuccessful!", Toast.LENGTH_SHORT).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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DataBaseHelper.java
package com.example.asus.sqlliteproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Asus on 29.4.2016.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DataBaseName = "student.db";
public static final String DataTableName = "studentTable.db";
public static final String ColID = "ID";
public static final String ColName = "Name";
public static final String ColLastName = "LastName";
public static final String ColGrades = "Grade";
public DataBaseHelper(Context context) {
super(context, DataBaseName, null, 1);
//SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table" + DataTableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT)," +
"Name TEXT, LastName TEXT, Grade INTEGER");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists" + DataTableName);
onCreate(db);
}
public boolean insertData (String name, String LastName, String Grades) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ColName,name);
contentValues.put(ColLastName,LastName);
contentValues.put(ColGrades,Grades);
long result = db.insert(DataTableName, null, contentValues);
if (result == -1) {
return false;
}else
return true;
}
}
logcat error (separated into two imgs) and activity_main view
You missed white space here "create table" should be "create table "
Don't forget about white spaces.
try this:
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DataBaseName = "student.db";
public static final String DataTableName = "studentTable";
public static final String ColID = "ID";
public static final String ColName = "Name";
public static final String ColLastName = "LastName";
public static final String ColGrades = "Grade";
public DataBaseHelper(Context context) {
super(context, DataBaseName, null, 1);
//SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + DataTableName + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"Name TEXT, LastName TEXT, Grade INTEGER);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists" + DataTableName);
onCreate(db);
}
public boolean insertData (String name, String LastName, String Grades) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ColName,name);
contentValues.put(ColLastName,LastName);
contentValues.put(ColGrades,Grades);
long result = db.insert(DataTableName, null, contentValues);
if (result == -1) {
return false;
}else
return true;
}
}
Once I was getting similar error. I simply replaced 'ID' by '_id' and it worked like a charm.
Related
I am trying to implement a search function into a custom list view. I using a menu for the search feature. When I type into the search bar, my project crashes with this error.
2019-11-19 18:50:05.762 17072-17072/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.example.medicationmanagementsystem, PID: 17072
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object
reference
at com.example.medicationmanagementsystem.ViewListContents$1.onQueryTextChange(ViewListContents.java:72)
I think it is getting null for the array and is therefore unable to show any details. Any help would be grateful.
ViewListContents.java
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.MenuItemCompat;
import com.example.medicationmanagementsystem.DAO.DatabaseHelper;
import java.util.ArrayList;
public class ViewListContents extends AppCompatActivity {
DatabaseHelper myDB;
ArrayList<Prescription> prescriptionList;
ListView listView;
Prescription prescription;
ArrayList<String> listItem;
ArrayAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcontents_layout);
myDB = new DatabaseHelper(this);
prescriptionList = new ArrayList<Prescription>();
Cursor data = myDB.getListContents();
int numRows = data.getCount();
if(numRows == 0){
Toast.makeText(ViewListContents.this, "There is nothing in this database", Toast.LENGTH_LONG).show();
}
else {
while(data.moveToNext()){
prescription = new Prescription(data.getString(1), data.getString(2), data.getString(3),
data.getString(4), data.getString(5), data.getString(6), data.getString(7),
data.getString(8), data.getString(9));
prescriptionList.add(prescription);
}
EightColumn_ListAdapter adapter = new EightColumn_ListAdapter(this,R.layout.prescription_view,prescriptionList);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
}
}
//END
//This code is based on SQLite Database to ListView- Part 4:Search Items- Android Studio Tutorial, KOD Dev, https://www.youtube.com/watch?v=QY-O49a_Ags
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<String> listViews = new ArrayList<>();
for (String prescription : listItem){
if (prescription.toLowerCase().contains(newText.toLowerCase())){
listViews.add(prescription);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ViewListContents.this,R.layout.prescription_view,listViews);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
}
DatabaseHelper.java
package com.example.medicationmanagementsystem.DAO;
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;
public class DatabaseHelper extends SQLiteOpenHelper {
//Create Database
public static final String DATABASE_NAME = "ManagementSystem.db";
//Create patient table
public static final String TABLE_PATIENT = "patient_table";
public static final String COL_PATIENT_PATIENTID = "PATIENTID";
public static final String COL_PATIENT_FNAME = "FNAME";
public static final String COL_PATIENT_SNAME = "SNAME";
public static final String COL_PATIENT_PPS = "PPS";
public static final String COL_PATIENT_DOB = "DOB";
public static final String COL_PATIENT_ADDRESS = "ADDRESS";
public static final String COL_PATIENT_TYPE = "PATIENTTYPE";
public static final String COL_PATIENT_MEDCOND = "PATIENTMEDCON";
public static final String COL_PATIENT_CARINGID = "CARINGID";
//Create prescription table
public static final String TABLE_PRESCRIPTION = "prescription_table";
public static final String COL_PRESCRIPTION_ID = "PRESCRIPTIONID";
public static final String COL_PRESCRIPTION__PATIENTID = COL_PATIENT_PATIENTID;
public static final String COL_PRESCRIPTION__DATE = "DATE";
public static final String COL_PRESCRIPTION__DRUGNAME = "DRUGNAME";
public static final String COL_PRESCRIPTION__CONCENTRATION = "CONCENTRATION";
public static final String COL_PRESCRIPTION__DOSAGE = "DOSAGE";
public static final String COL_PRESCRIPTION__PREPARATION = "PREPARATION";
public static final String COL_PRESCRIPTION__STARTDATE = "STARTDATE";
public static final String COL_PRESCRIPTION__ENDDATE = "ENDDATE";
public static final String COL_PRESCRIPTION__DOCTORID = "DOCTORID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate (SQLiteDatabase db) {
String patienttable = "CREATE TABLE " + TABLE_PATIENT + "(PATIENTID INTEGER PRIMARY KEY AUTOINCREMENT, FNAME TEXT, SNAME TEXT, PPS TEXT, DOB TEXT, ADDRESS TEXT, PATIENTTYPE TEXT, PATIENTMEDCON TEXT, CARINGID INTEGER)";
String prescriptiontable = "CREATE TABLE " + TABLE_PRESCRIPTION + "(PRESCRIPTIONID INTEGER PRIMARY KEY AUTOINCREMENT, PATIENTID INTEGER, DATE TEXT, DRUGNAME TEXT, CONCENTRATION TEXT, DOSAGE TEXT, PREPARATION TEXT, STARTDATE TEXT, ENDDATE TEXT, DOCTORID INTEGER)";
db.execSQL(patienttable);
db.execSQL(prescriptiontable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PATIENT);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_PRESCRIPTION);
onCreate(db);
}
//insert patient data
public boolean insertPatientData(String fname, String sname, String pps, String dob, String address, String patienttype, String patientmedcon, String caringid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL_PATIENT_FNAME, fname);
contentValues1.put(COL_PATIENT_SNAME, sname);
contentValues1.put(COL_PATIENT_PPS, pps);
contentValues1.put(COL_PATIENT_DOB, dob);
contentValues1.put(COL_PATIENT_ADDRESS, address);
contentValues1.put(COL_PATIENT_TYPE, patienttype);
contentValues1.put(COL_PATIENT_MEDCOND,patientmedcon);
contentValues1.put(COL_PATIENT_CARINGID, caringid);
long result= db.insert(TABLE_PATIENT,null, contentValues1);
if (result == 1)
return false;
else
return true;
}
//insert prescription data
public boolean insertData(String patientid, String date, String drugname, String concentration,String dosage, String preparation, String startdate, String enddate, String doctorid) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put(COL_PRESCRIPTION__PATIENTID, patientid);
contentValues2.put(COL_PRESCRIPTION__DATE, date);
contentValues2.put(COL_PRESCRIPTION__DRUGNAME, drugname);
contentValues2.put(COL_PRESCRIPTION__CONCENTRATION, concentration);
contentValues2.put(COL_PRESCRIPTION__DOSAGE, dosage);
contentValues2.put(COL_PRESCRIPTION__PREPARATION, preparation);
contentValues2.put(COL_PRESCRIPTION__STARTDATE, startdate);
contentValues2.put(COL_PRESCRIPTION__ENDDATE, enddate);
contentValues2.put(COL_PRESCRIPTION__DOCTORID, doctorid);
long result= db.insert(TABLE_PRESCRIPTION,null, contentValues2);
if (result == 1)
return false;
else
return true;
//END
}
//Coding with mitch tutorial
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_PRESCRIPTION, null);
return data;
}
////This code is based on SQLite Database to ListView- Part 4:Search Items- Android Studio Tutorial, KOD Dev, https://www.youtube.com/watch?v=QY-O49a_Ags
public Cursor searchPrescriptions(String text) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * from " + TABLE_PRESCRIPTION + "WHERE " + COL_PRESCRIPTION__PATIENTID + " Like '%" + text +"%'";
Cursor data = db.rawQuery(query, null);
return data;
}
}
Eight_Column_ListAdapter.java
package com.example.medicationmanagementsystem;
//The code below is based on Adding multiple columns to your ListView, CodingWithMitch, https://www.youtube.com/watch?v=8K-6gdTlGEA, https://www.youtube.com/watch?v=hHQqFGpod14, https://www.youtube.com/watch?v=jpt3Md9aDIQ
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class EightColumn_ListAdapter extends ArrayAdapter<Prescription> {
private LayoutInflater mInflater;
private ArrayList<Prescription> prescriptions;
private int mViewResourceId;
public EightColumn_ListAdapter(Context context, int textViewResourceId, ArrayList<Prescription> prescriptions) {
super(context, textViewResourceId, prescriptions);
this.prescriptions = prescriptions;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents) {
convertView = mInflater.inflate(mViewResourceId, null);
Prescription prescription = prescriptions.get(position);
if (prescription != null) {
TextView patientID = (TextView) convertView.findViewById(R.id.textpatientID);
TextView date = (TextView) convertView.findViewById(R.id.textdate);
TextView drugname = (TextView) convertView.findViewById(R.id.textdrugname);
TextView concentration = (TextView) convertView.findViewById(R.id.textcontentration);
TextView dosage = (TextView) convertView.findViewById(R.id.textdosage);
TextView prep = (TextView) convertView.findViewById(R.id.textprep);
TextView startdate = (TextView) convertView.findViewById(R.id.textstartdate);
TextView enddate = (TextView) convertView.findViewById(R.id.textenddate);
TextView doctorID = (TextView) convertView.findViewById(R.id.textdoctorid);
if(patientID != null) {
patientID.setText((prescription.getPatientID()));
}
if(date != null) {
date.setText((prescription.getPresdate()));
}
if(drugname != null) {
drugname.setText((prescription.getDrugname()));
}
if(concentration != null) {
concentration.setText((prescription.getConcentration()));
}
if(dosage != null) {
dosage.setText((prescription.getDosage()));
}
if(prep != null) {
prep.setText((prescription.getPreparation()));
}
if(startdate != null) {
startdate.setText((prescription.getStartdate()));
}
if(enddate != null) {
enddate.setText((prescription.getEnddate()));
}
if(doctorID != null) {
patientID.setText((prescription.getDoctorID()));
}
}
return convertView;
}
}
You are trying to read the elements of your list called listItem . That list is null because you never set it to anything else.
Change this:
ArrayList<String> listItem;
to this:
ArrayList<String> listItem = new ArrayList<String>();
... or you can put it in your onCreate() method, just as you did with prescriptionList :
prescriptionList = new ArrayList<Prescription>();
listItem = new ArrayList<String>();
Also, don't name your list listItem because it is not an item... it is a list!
I want all edit text content that I have saved in SQL to be displayed on the edit bills activity when I click on the list item, but I am only able to retrieve the name and display it again in the intent. Rather than saving another data it should update the record with the new data if I save the existing record another time in the editbills_activity. Here is my DBAdapter.java
package com.example.dhruv.bills;
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;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "name VARCHAR not null, amount VARCHAR, duedate date );";
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
//return db.insert(DATABASE_TABLE, null, initialValues);
// Will return NULL POINTER EXCEPTION as db isn't set
// Replaces commented out line
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public void deleteName(int id, String name){
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "DELETE FROM " + DATABASE_TABLE + " WHERE "
+ KEY_ROWID + " = '" + id + "'" +
" AND " + KEY_NAME + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
/* public Cursor getRecord()
{String query1 ="SELECT * FROM" + KEY_TITLE;
Cursor mCursor = db.rawQuery(query1,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}*/
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
/* public boolean updateRecord(long rowId, String name, String amount, String duedate)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
// Will return NULL POINTER EXCEPTION as db isn't set
//return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// Replaces commented out line
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}*/
}
Here is my Bills.java (MainActivity)
Problem: Bills.java has the list view that shows the intent whenever the item in list view is clicked, but it does not put the amount and date or update the record. Instead it saves another record.
Solution: I want to retrieve it and display all (name ,amount,duedate) and instead of saving another record it should update it.
package com.example.dhruv.bill;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class bills extends AppCompatActivity {
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="assignments";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mrecycleview =(ListView) findViewById(R.id.mRecycleView);
dbAdapter = new DBAdapter(this);
// mlistview();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab1);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Editbills.class);
startActivity(i);
}
});
mlistview();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void mlistview(){
Log.d(TAG,"mlistview:Display data in listview");
Cursor mCursor = dbAdapter.getAllRecords();
ArrayList<String> listData = new ArrayList<>();
while (mCursor.moveToNext()){
listData.add(mCursor.getString(1));
}
ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = dbAdapter.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(bills.this, Editbills.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
}
}
});
}
}
here is my editbills.java code
package com.example.dhruv.bill;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag= "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private int selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.editText);
editText2=(EditText)findViewById(R.id.editText2);
editText3 =(EditText)findViewById(R.id.editText3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
editText.setText(selectedName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_Delete) {
db.deleteName(selectedID,selectedName);
editText.setText("");
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
Intent p = new Intent(getApplicationContext(),bills.class);
startActivity(p);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Instead of
DBHelper.getWritableDatabase().insert(DATABASE_TABLE, null, initialValues);
in insertRecord function of DBHelper, it should be
DBHelper.getWritableDatabase().update("markers", valores, where, whereArgs);
No matter how many times I've reviewed my code I keep getting a LogCat error of
Process: com.zito.zitolab4, PID: 2357
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zito.zitolab4/com.zito.zitolab4.ZitoLab4Data}: android.database.sqlite.SQLiteException: no such column: title (code 1): , while compiling: SELECT id, title, genre, releaseYear FROM movies
Based on the LogCat I figured it would be in the Data.Java Class but I've looked everywhere and I'm just not setting it.I would appreciate any advice.
Thanks
Data.Java
package com.zito.zitolab4;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class ZitoLab4Data extends ActionBarActivity {
TextView idView;
EditText titleBox, genreBox, yearBox;
Button addMovieButton;
TableLayout movieTable;
private ZitoDataController sqlCon;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zito_lab4_data);
sqlCon = new ZitoDataController(this);
titleBox = (EditText) findViewById(R.id.movieTitle);
genreBox = (EditText) findViewById(R.id.movieGenre);
yearBox = (EditText) findViewById(R.id.releaseYear);
addMovieButton = (Button) findViewById(R.id.addMovieButton);
movieTable = (TableLayout) findViewById(R.id.movieTable);
BuildTable();
addMovieButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new MyAsync().execute();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_zito_lab4_data, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void BuildTable() {
sqlCon.open();
Cursor dbCursor = sqlCon.readEntry();
int movies = dbCursor.getCount();
int fields = dbCursor.getColumnCount();
// 1 row for each person in the database table
for (int i = 0; i < movies; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
// create a TextView for each field in the record
for (int j = 0; j < fields; j++) {
TextView TableDataTextView = new TextView(this);
TableDataTextView.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
TableDataTextView.setTextSize(16);
TableDataTextView.setPadding(0, 5, 0, 5);
TableDataTextView.setText(dbCursor.getString(j));
row.addView(TableDataTextView);
}
dbCursor.moveToNext();
movieTable.addView(row);
}
sqlCon.close();
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
movieTable.removeAllViews();
progressDialog = new ProgressDialog(ZitoLab4Data.this);
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String title = titleBox.getText().toString();
String genre = genreBox.getText().toString();
int year = Integer.parseInt(yearBox.getText().toString());
sqlCon.open();
sqlCon.insertData(title, genre, year);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
BuildTable();
progressDialog.dismiss();
titleBox.setText("");
genreBox.setText("");
yearBox.setText("");
titleBox.requestFocus();
}
}
}
DataModel.Java
package com.zito.zitolab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ZitoDataModel extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ZitoLab4DB.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_MOVIES = "movies";
public static final String MOVIE_ID = "id";
public static final String MOVIE_TITLE = "title";
public static final String MOVIE_GENRE = "genre";
public static final String MOVIE_YEAR = "releaseYear";
public ZitoDataModel(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_MOVIES + "(" + MOVIE_ID + " INTEGER PRIMARY KEY," +
MOVIE_TITLE + " TEXT," + MOVIE_GENRE + " STRING, " + MOVIE_YEAR + " INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIES);
onCreate(db);
}
public void addMovie(String title, String genre, int year) {
ContentValues values = new ContentValues();
values.put(MOVIE_TITLE, title);
values.put(MOVIE_GENRE, genre);
values.put(MOVIE_YEAR, year);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_MOVIES, null, values);
db.close();
}
public Cursor readEntry(){
SQLiteDatabase db = this.getWritableDatabase();
String[] allColumns = new String[]{ZitoDataModel.MOVIE_ID, ZitoDataModel.MOVIE_TITLE,
ZitoDataModel.MOVIE_GENRE, ZitoDataModel.MOVIE_YEAR};
Cursor dbCursor = db.query(ZitoDataModel.TABLE_MOVIES, allColumns,
null, null, null, null, null);
if (dbCursor !=null) {
dbCursor.moveToFirst();
}
return dbCursor;
}
}
DataController.Java
package com.zito.zitolab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class ZitoDataController {
private ZitoDataModel dataModel;
private Context movieContext;
private SQLiteDatabase database;
public ZitoDataController(Context context) {
movieContext = context;
}
public ZitoDataController open() throws SQLException {
dataModel = new ZitoDataModel(movieContext);
database = dataModel.getWritableDatabase();
return this;
}
public void close()
{
dataModel.close();
}
public void insertData(String title, String genre, int year) {
ContentValues values = new ContentValues();
values.put(ZitoDataModel.MOVIE_TITLE, title);
values.put(ZitoDataModel.MOVIE_GENRE, genre);
values.put(ZitoDataModel.MOVIE_YEAR, year);
database.insert(ZitoDataModel.TABLE_MOVIES, null, values);
}
public Cursor readEntry() {
String[] allColumns = new String[]{ZitoDataModel.MOVIE_ID, ZitoDataModel.MOVIE_TITLE,
ZitoDataModel.MOVIE_GENRE, ZitoDataModel.MOVIE_YEAR};
Cursor dataCursor = database.query(ZitoDataModel.TABLE_MOVIES,
allColumns, null, null, null, null, null);
if (dataCursor != null) {
dataCursor.moveToFirst();
}
return dataCursor;
}
}
You possibly modified the table in a later moment (after the very first run).
Uninstall and reinstall your app.
Or, alternatively, increase the value of this constant: DATABASE_VERSION
In the first case, the database will be created normally (for the first time).
The second case causes the onUpgrade() method to fire which will in turn call
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MOVIES);
onCreate(db);
So, de facto, deleting the existing table and then re-creating it.
I am getting this Error when i enter the existing RegId in Database..
**DatabaseHandler.java**
package com.example.aaqib.scoolbag;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper {
//Creating a Database ScoolBag
SQLiteDatabase mDb;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ScoolBag";
public static final String KEY_NAME = "Name";
public static final String KEY_MOBILENO = "Contact";
public static final String KEY_REGID = "Registration";
public static final String KEY_EMAIL = "Email";
public static final String KEY_PASSWORD = "Password";
// Table name
public static final String tblReg="tblReg";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String vQuery = "Create Table " + tblReg + "(Registration Text primary key,Name Text not null,Password Text not null,Email Text not null,Contact Text not null)";
Log.d("StudentData", "onCreate: " + vQuery);
db.execSQL(vQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS tblReg");
onCreate(db);
}
//using to insert
public void InsertRecord(String vInsertRecord) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(vInsertRecord);
db.close();
}
public void close()
{
mDb.close();
}
/*public Cursor login(String regid)throws SQLiteException
{
String where =(KEY_REGID + "=?");
Cursor m = mDb.query(true, tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{regid}, null, null, null, null);
if (m != null) {
// m.moveToFirst();
}
return m;
}*/
//fetching a emailid
public Cursor getEmailid(String email)throws SQLiteException
{
String where =(KEY_EMAIL + "=?");
Cursor m = mDb.query(true,tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{email}, null, null, null, null);
if (m != null) {
}
return m;
}
//fetching cursor id
public Cursor getRegid(String reg)throws SQLiteException
{
String where =(KEY_REGID + "=?");
Cursor j = mDb.query(true, tblReg, new String[]{KEY_REGID, KEY_NAME, KEY_PASSWORD,KEY_EMAIL,KEY_MOBILENO}, where, new String[]{reg}, null, null, null, null);
if (j!= null) {
//j.moveToFirst();
}
return j;
}
public DatabaseHandler open() throws SQLiteException {
mDb = getWritableDatabase();
return this;
}
}
acitivity_registration.java
package com.example.aaqib.scoolbag;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.view.View.OnClickListener;
public class activity_registration extends Activity {
EditText reg, Name, Pas1, Pas2, Email, Contact;
String regid,emailid;
SQLiteDatabase db;
DatabaseHandler dbh = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_registration);
reg = (EditText) findViewById(R.id.editText);
Name = (EditText) findViewById(R.id.editText2);
Pas1 = (EditText) findViewById(R.id.editText3);
Pas2 = (EditText) findViewById(R.id.editText4);
Email = (EditText) findViewById(R.id.editText5);
Contact = (EditText) findViewById(R.id.editText6);
Button btnReg = (Button) findViewById(R.id.btnRegister);
//button used to register
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbh.open();
try {
//get the id from database
dbh.open();
Cursor c=dbh.getRegid(reg.getText().toString().trim());
if((c != null) && c.moveToFirst())
{
regid = c.getString(c.getColumnIndex("RegId"));
c.close();
}
//get the email id from database
Cursor email = dbh.getEmailid(Email.getText().toString().trim());
if (email != null && email.moveToFirst()) {
emailid = email.getString(email.getColumnIndex("Email"));
email.close();
}
if (reg.getText().toString().equals("") || Name.getText().toString().equals("") || Pas1.getText().toString().equals("") || Pas2.getText().toString().equals("") || Email.getText().toString().equals("") || Contact.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Fill All Mandatory Fields", Toast.LENGTH_SHORT).show();
}
else if (!Email.getText().toString().trim().matches("[a-zA-Z0-9._-]+#[a-z]+.[a-z]+"))
{
Email.setError("Invalid Email Address");
Email.requestFocus();
}
else if (Email.getText().toString().equals(emailid))
{
Toast.makeText(getApplicationContext(), "Email is already registered", Toast.LENGTH_SHORT).show();
}
else if (Email.getText().toString().equals(regid))
{
Toast.makeText(getApplicationContext(), "Registration Id already exist", Toast.LENGTH_SHORT).show();
}
else if (!Contact.getText().toString().trim().matches("^[0-9]{10}$")) {
Contact.setError("Invalid Contact Number");
Contact.requestFocus();
}
else if (!Name.getText().toString().trim().matches("([a-zA-Z ]+)$")) {
Name.setError("Invalid Name");
Name.requestFocus();
}
else if (!Pas1.getText().toString().trim().matches(Pas2.getText().toString().trim())) {
Pas2.setError("Password Not Matched");
Pas2.requestFocus();
}
else {
InsertRecord();
Refresh();
Intent i = new Intent(activity_registration.this, activity_home.class);
startActivity(i);
finish();
}
}
catch (Exception e)
{
String ex=e.toString();
Toast.makeText(getApplicationContext(), ex, Toast.LENGTH_SHORT).show();
}
}
});
}
public void InsertRecord()
{
String vQuery = "insert into tblReg (Registration,Name,Password,Email,Contact)values('" + reg.getText().toString().trim() + "','" + Name.getText().toString().trim() + "','"+ Pas2.getText().toString().trim()+"','"+ Email.getText().toString().trim()+"','"+ Contact.getText().toString().trim() +"')";
DatabaseHandler db = new DatabaseHandler(this);
db.InsertRecord(vQuery);
Toast.makeText(getApplicationContext(), "Inserted successful", Toast.LENGTH_SHORT).show();
}
public void Refresh()
{
reg.setText("");
Name.setText("");
Pas1.setText("");
Pas2.setText("");
Email.setText("");
Contact.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_registration, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Any help would be appreciated.
In your table there is no column as RegId so change following line
regid = c.getString(c.getColumnIndex("RegId"));
to
regid = c.getString(c.getColumnIndex("Registration"));
Hope this will helps you.
I have Created a database in Sqllite Android Application and I tried to add two tables in my Database, but I have problem to create that Database. First Table only Created. Can anyBody help me?
package com.android.cdtech;
import java.sql.SQLException;
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;
public class saveData {
public static final String KEY_ROWID = "rowid"; public static final String KEY_DATE = "Date";public static final String KEY_NAME = "CustomerName";public static final String KEY_AMOUNT = "Amount";public static final String KEY_BANK = "Banks";
private static final String TAG = "DBAdapter";
public static final String KEY_BUSNAME="BusinessName";public static final String KEY_ADD="Address";public static final String KEY_CPERSON="ContactPerson";;
private static final String DATABASE_NAME = "EXPORTDETAILS";
private static final String DATABASE_TABLE = "Payment";
private static final String DATABASE_TABLE2 = "Customer";
private static final int DATABASE_VERSION = 1;
private static String DATABASE_CREATE =
"create table Payment (_id integer primary key autoincrement, "
+ "Date text not null,"+"CustomerName text not null,"+"Amount text not null,"+"Banks text not null);";
private static final String DATABASE_CREATECUS =
"create table Customer (_id integer primary key autoincrement, "
+ "BusinessName text not null,"+"Address text not null,"+"ContactPerson text not null,"+"PhoneNumber text not null,);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public saveData(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATECUS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}
public saveData open()throws SQLException
{
db=DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insert(String Date,String CustomerName,String Amount,String Banks) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_DATE,Date);
cv.put(KEY_NAME,CustomerName);
cv.put(KEY_AMOUNT,Amount);
cv.put(KEY_BANK,Banks);
return db.insert(DATABASE_TABLE, null,cv);
}
public long insertForm(String BusinessName ,String Address ,String ContactPerson) {
// TODO Auto-generated method stub
ContentValues cv=new ContentValues();
cv.put(KEY_BUSNAME,BusinessName);
cv.put(KEY_ADD,Address);
cv.put(KEY_CPERSON,ContactPerson);
}
public Cursor getlatlng()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
public Cursor order()
{
Cursor latlngCursor = db.rawQuery("select * from " + DATABASE_TABLE2,null);
if (latlngCursor != null)
{
latlngCursor.moveToFirst();
}
db.close();
return latlngCursor;
}
}
Error Code =1 No Such table for Customer
use below two class
package Your 'packagename';
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "BistroDB";
private static final int DATABASE_VERSION =1;
// Database creation sql statement
public static final String Table1= "create table table1name ("Your cloumns");";
public static final String Table2 = "create table table2name ("Your cloumns");";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(table1);
database.execSQL(table2);
}
// Method is called during an upgrade of the database, e.g. if you increase
// the database version
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS table1");
database.execSQL("DROP TABLE IF EXISTS table2");
onCreate(database);
}
public boolean deleteDatabase(Context context) {
return context.deleteDatabase(DATABASE_NAME);
}
}
Use below class to insert values into table
package 'Your package name';
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DataBaseAdapter {
// Database fields
private Context context;
private SQLiteDatabase database;
private DBHelper dbHelper;
public DataBaseAdapter(Context context) {
this.context = context;
}
public DataBaseAdapter open() throws SQLException {
dbHelper = new DBHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public Cursor fetchAllTAble1data() {
return database.query("MenuData", new String[] { "id", "Title",
"Image", "Description" }, null, null, null, null, null);
}
public Cursor fetchAllTable2data() {
return database.query("RestaurantsData", new String[] {
"restaurant_id", "name", "phone", "email", "open_days",
"timing", "website", "loc_name", "street", "city", "longitude",
"latitude", "zip" }, null, null, null, null, null);
}
public void deleteTable(String tablename){
database.execSQL("drop table if exists "+tablename+';');
}
public void createIndividualTable(String query){
database.execSQL(query);
}
public void InsertTable1Data(TAble1 review) {
ContentValues values = new ContentValues();
values.put("Name", review.Name);
values.put("Email", review.Email);
values.put("Comment", review.Comment);
values.put("Rating", review.Rating);
database.insert("ReviewsData", null, values);
}
public void InsertTable2Data(TAble2 photos) {
ContentValues values = new ContentValues();
values.put("photo", photos.Photos);
database.insert("PhotosData", null, values);
}
public ContentValues createContentValues(String category, String summary,
String description) {
ContentValues values = new ContentValues();
return values;
}
}
Try removing the "," at the end of DATABASE_CREATECUS