Why does Android Studio Keep Saying there is no title Column? - java

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.

Related

I'm having this error when I try to update/edit the Sqlite database java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 can any on help me

I'm having this error when I try to update/edit the Sqlite database java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 can any on helping me.
when I try to delete the existing data from the database it works. But when I try to update or edit the existing data from the database, it does not work and the app crashes.
when I check the database inspector then I find one thing that when I try to edit the table data on the database the Class_table will gone or you can say delete automatically. and I don't find any solution for this problem can anyone help me plz.
Here is the error code:
Process: com.example.attendance, PID: 20112
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.attendance.MainActivity.updateClass(MainActivity.java:135)
at com.example.attendance.MainActivity.lambda$showUpdateDialog$4$MainActivity(MainActivity.java:131)
at com.example.attendance.-$$Lambda$MainActivity$m9twlugKZZaVnr6kCG8LrRCoXMM.onClick(Unknown Source:4)
at com.example.attendance.MyDialog.lambda$getUpdateClassDialog$1$MyDialog(MyDialog.java:94)
at com.example.attendance.-$$Lambda$MyDialog$5v1iqgaO8riJO2phwUfadWXdoyM.onClick(Unknown Source:6)
at android.view.View.performClick(View.java:8160)
at android.widget.TextView.performClick(TextView.java:16222)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:8137)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30236)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8512)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
I/Process: Sending signal. PID: 20112 SIG: 9
Here is My Activity:
package com.example.attendance;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
RecyclerView recyclerView;
ClassAdapter classAdapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<ClassItem> classItems = new ArrayList<>();
Toolbar toolbar;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DbHelper(this);
floatingActionButton = findViewById(R.id.fab_main);
floatingActionButton.setOnClickListener(V -> showDialog());
loadData();
recyclerView = findViewById(R.id.att_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
classAdapter = new ClassAdapter(this, classItems);
recyclerView.setAdapter(classAdapter);
classAdapter.setOnItemClickListener(position -> gotoItemActivity(position));
setToolbar();
}
private void loadData() {
Cursor cursor = dbHelper.getClassTable();
classItems.clear();
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(DbHelper.C_ID));
String department = cursor.getString(cursor.getColumnIndex(DbHelper.CLASS_NAME_KEY));
String subject = cursor.getString(cursor.getColumnIndex(DbHelper.SUBJECT_NAME_KEY));
classItems.add(new ClassItem(id,department,subject));
}
}
private void setToolbar() {
toolbar = findViewById(R.id.toolbar);
TextView title = toolbar.findViewById(R.id.tool_title);
TextView subTitle = toolbar.findViewById(R.id.tool_sub_title);
TextView samiTitle = toolbar.findViewById(R.id.tool_sami_title);
ImageButton back = toolbar.findViewById(R.id.tool_back);
ImageButton save = toolbar.findViewById(R.id.tool_save);
title.setText("Attendance");
subTitle.setVisibility(View.GONE);
samiTitle.setVisibility(View.GONE);
save.setVisibility(View.GONE);
back.setOnClickListener(v -> onBackPressed());
}
private void gotoItemActivity(int position) {
Intent intent = new Intent(this,StudentActivity.class);
intent.putExtra("departmentName",classItems.get(position).getDepartment());
intent.putExtra("subjectName",classItems.get(position).getSubject());
intent.putExtra("position",position);
startActivity(intent);
}
private void showDialog() {
MyDialog dialog = new MyDialog();
dialog.show(getSupportFragmentManager(),MyDialog.CLASS_ADD_DIALOG);
dialog.setListener((department,subject)->addClass(department,subject));
}
private void addClass(String department, String subject) {
long cid = dbHelper.addClass(department,subject);
ClassItem classItem = new ClassItem(cid,department,subject);
classItems.add(classItem);
classAdapter.notifyDataSetChanged();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case 0:
showUpdateDialog(item.getGroupId());
case 1:
deleteClass(item.getGroupId());
}
return super.onContextItemSelected(item);
}
private void showUpdateDialog(int position) {
MyDialog updateDialog = new MyDialog();
updateDialog.show(getSupportFragmentManager(),MyDialog.CLASS_UPDATE_DIALOG);
updateDialog.setListener((department,subject)->updateClass(position,department,subject));
}
// when I try to Update the Data its don't work and the app will crash
private void updateClass(int position, String department, String subject) {
dbHelper.updateClass(classItems.get(position).getCid(),department,subject);
classItems.get(position).setDepartment(department);
classItems.get(position).setSubject(subject);
classAdapter.notifyItemChanged(position);
}
private void deleteClass(int position) {
dbHelper.deleteClass(classItems.get(position).getCid());
classItems.remove(position);
classAdapter.notifyItemRemoved(position);
}
}
Here is my Adepter
package com.example.attendance;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {
private OnItemClickListener onItemClickListener;
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public ClassAdapter(Context context, ArrayList<ClassItem> classItems) {
this.classItems = classItems;
this.context = context;
}
ArrayList<ClassItem> classItems;
Context context;
public static class ClassViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
TextView department, subject;
public ClassViewHolder(#NonNull View itemView,OnItemClickListener onItemClickListener) {
super(itemView);
department = itemView.findViewById(R.id.dep_tv);
subject = itemView.findViewById(R.id.sub_tv);
itemView.setOnClickListener(v -> onItemClickListener.onClick(getAdapterPosition()));
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(getAdapterPosition(),0,0,"EDIT");
menu.add(getAdapterPosition(),1,0,"DELETE");
}
}
#NonNull
#Override
public ClassViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.class_item, parent, false);
return new ClassViewHolder(itemView, onItemClickListener);
}
#Override
public void onBindViewHolder(#NonNull ClassViewHolder holder, int position) {
holder.department.setText(classItems.get(position).getDepartment());
holder.subject.setText(classItems.get(position).getSubject());
}
#Override
public int getItemCount() {
return classItems.size();
}
}
Here is Database
package com.example.attendance;
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 androidx.annotation.Nullable;
public class DbHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
//Class table
private static final String CLASS_TABLE_NAME= "CLASS_TABLE";
public static final String C_ID= "_CID";
public static final String CLASS_NAME_KEY= "CLASS_NAME";
public static final String SUBJECT_NAME_KEY= "SUBJECT_NAME";
private static final String CREATE_CLASS_TABLE=
"CREATE TABLE " + CLASS_TABLE_NAME + "(" +
C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
CLASS_NAME_KEY + " TEXT NOT NULL, " +
SUBJECT_NAME_KEY + " TEXT NOT NULL, " +
" UNIQUE ( " + CLASS_NAME_KEY + "," + SUBJECT_NAME_KEY + ")" +
");";
private static final String DROP_CLASS_TABLE = "DROP TABLE IF EXISTS "+CLASS_TABLE_NAME;
private static final String SELECT_CLASS_TABLE = "SELECT * FROM "+CLASS_TABLE_NAME;
//Student table
private static final String STUDENT_TABLE_NAME= "STUDENT_TABLE";
private static final String S_ID= "_SID";
private static final String STUDENT_NAME_KEY= "STUDENT_NAME";
private static final String STUDENT_ROLL_KEY= "ROLL";
private static final String CREATE_STUDENT_TABLE=
"CREATE TABLE "+ STUDENT_TABLE_NAME +
"( "+
S_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+
C_ID + " TEXT NOT NULL, "+
STUDENT_NAME_KEY + " TEXT NOT NULL, "+
STUDENT_ROLL_KEY + " INTEGER, "+
" FOREIGN KEY ( "+C_ID+ " ) REFERENCES "+ CLASS_TABLE_NAME + "("+C_ID+")"+
");";
private static final String DROP_STUDENT_TABLE = "DROP TABLE IF EXISTS "+STUDENT_TABLE_NAME;
private static final String SELECT_STUDENT_TABLE = "SELECT * FROM "+STUDENT_TABLE_NAME;
//Status table
private static final String STATUS_TABLE_NAME= "STATUS_TABLE";
private static final String STATUS_ID= "_STATUS_ID";
private static final String DATE_KEY= "STATUS_NAME";
private static final String STATUS_KEY= "STATUS";
private static final String CREATE_STATUS_TABLE=
"CREATE TABLE "+STATUS_TABLE_NAME+
"("+
STATUS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "+
S_ID + " INTEGER NOT NULL, "+
DATE_KEY + " DATE NOT NULL, "+
STATUS_KEY + " TEXT NOT NULL, "+
" UNIQUE ( " + S_ID + "," + DATE_KEY + ")," +
" FOREIGN KEY ( "+ S_ID+ " ) REFERENCES "+ STUDENT_TABLE_NAME + "( "+S_ID+")"+
");";
private static final String DROP_STATUS_TABLE = "DROP TABLE IF EXISTS "+ STATUS_TABLE_NAME;
private static final String SELECT_STATUS_TABLE = "SELECT * FROM "+ STATUS_TABLE_NAME;
public DbHelper(#Nullable Context context) {
super(context, "Attendance.db", null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CLASS_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STATUS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
long addClass(String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.insert(CLASS_TABLE_NAME,null,values);
}
Cursor getClassTable(){
SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery(SELECT_CLASS_TABLE,null);
}
int deleteClass(long cid){
SQLiteDatabase database = this.getReadableDatabase();
return database.delete(CLASS_TABLE_NAME,C_ID+"=?",new String[]{String.valueOf(cid)});
}
long updateClass(long cid,String className,String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
return database.update(CLASS_TABLE_NAME,values,C_ID+"=?",new String[]{String.valueOf(cid)});
}
}
After dropping your tables, you forgot to create them again in your onUpgrade method.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_CLASS_TABLE);
db.execSQL(DROP_STUDENT_TABLE);
db.execSQL(DROP_STATUS_TABLE);
onCreate(db);
} catch (SQLException e) {
e.printStackTrace();
}
}
Also it is a good idea to call .close() method every time you call .getWritableDatabase() or .getReadableDatabase(). Here is an example ...
long addClass(String className, String subjectName){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CLASS_NAME_KEY,className);
values.put(SUBJECT_NAME_KEY,subjectName);
database.close();
long id = database.insert(CLASS_TABLE_NAME,null,values);
return id;
}
Hope it helps, happy coding!
The issue is in your MainActivity.class and StudentActivity.class.
In your onContextItemSelected(#NonNull MenuItem item) method, you forgot to break; your switch statement.
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case 0:
showUpdateDialog(item.getGroupId());
break;
case 1:
deleteClass(item.getGroupId());
break;
} return true;
}
Also, instead of adding classItems or studentItems to their respective ArrayLists after updating or deleting data in your SQLite Database, just call loadData() method again!
private void deleteClass(int position) {
dbHelper.deleteClass(classItems.get(position).getCid());
loadData();
classAdapter.notifyDataSetChanged();
}
private void updateClass(int position, String department, String subject) {
dbHelper.updateClass(classItems.get(position).getCid(),department,subject);
loadData();
classAdapter.notifyDataSetChanged();
}
The same thing applies to your StudentActivity.class. Happy Coding!

I am trying to implement a search function into a custom list view. I using a menu for the search feature

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!

How to update record in listview as well as Database in android

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);

SQLlite causes crash upon button pressed

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.

cursor Error : Make sure the Cursor is initialized correctly before accessing data from 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.

Categories

Resources