I'm trying to insert some values into an SQLite Database which are entered by the user, however when I press the button to save the values it crashes and a NullPointer exception is thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference at com.example.w4e74.farmanimalfinal.DatabaseHelper.insertRecord(DatabaseHelper.java:61)at com.example.w4e74.farmanimalfinal.Activity_item.onOptionsItemSelected(Activity_item.java:66)
I do not know what is causing the exception. My code is below, any help would be very appreciated.
Activity_item.java
package com.example.w4e74.farmanimalfinal;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewDebug;
import android.widget.EditText;
import android.widget.ListView;
public class Activity_item extends AppCompatActivity {
EditText editText_item;
boolean newItem;
long item_index;
private SQLiteDatabase db;
private Cursor cursor;
CustomCursorAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
DatabaseHelper db = new DatabaseHelper(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_item);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
item_index = intent.getLongExtra("item_index", -1);
if(item_index == -1) {
newItem = true;
} else {
newItem = false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_item:
DatabaseHelper.insertRecord(db, (R.id.editText_date),(R.id.editText_time), Integer.toString(R.id.editText_staff),(R.id.editText_animal),Integer.toString(R.id.editText_activity),Integer.toString(R.id.editText_details));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabaseHelper.java
package com.example.w4e74.farmanimalfinal;
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 {
private static final String DB_NAME = "farmanimals";
private static final int DB_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE RECORD ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "DATE INTEGER, "
+ "TIME INTEGER, "
+ "STAFF TEXT,"
+ "ANIMAL INTEGER,"
+ "ACTIVITY TEXT,"
+ "DETAIL TEXT);"
);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
#Override
public void onDowngrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public static long insertRecord(SQLiteDatabase db, int date, int time, String staff, int animal, String activity, String detail ) {
ContentValues recordValues = new ContentValues();
recordValues.put("DATE", date);
recordValues.put("TIME", time);
recordValues.put("STAFF", staff);
recordValues.put("ANIMAL", animal);
recordValues.put("ACTIVITY", activity);
recordValues.put("DETAIL", detail);
long newRecordID = db.insert("RECORD", null, recordValues);
return newRecordID;
}
public static String getDatabaseContentsAsString(SQLiteDatabase db) {
Cursor cursor = db.query("RECORD",
new String[]{"_id", "DATE", "TIME", "STAFF", "ANIMAL", "ACTIVITY", "DETAIL"},
null, null, null, null, "_id ASC");
String databaseAsString = System.getProperty("line.separator");
if(cursor.getCount() != 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
for (int i=0; i < cursor.getColumnCount() - 1; i++) {
databaseAsString += cursor.getString(i) + " ";
}
databaseAsString += System.getProperty("line.separator");
cursor.moveToNext();
}
if(cursor != null) cursor.close();
}
return databaseAsString;
}
public static void deleteRecord(SQLiteDatabase db, Long id) {
db.delete("RECORD", "_id=?", new String[] {Long.toString(id)});
}
public static void deleteAllRecords(SQLiteDatabase db) {
db.delete("RECORD", null, null);
db.delete("SQLITE_SEQUENCE","NAME = ?",new String[]{"RECORD"});
}
}
Edit: Error message received:
Incompatible types.
Required:
android.database.sqlite.SQLiteDatabase
Found:
com.example.w4e74.farmanimalfinal.DatabaseHelper
Your problem is the scope of db In onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
DatabaseHelper db = new DatabaseHelper(this);
...
}
You have this instance of db declared as a local variable, effectively creating two variables, both called db but operating at different scopes. This means that as soon as onCreate() is finished, this reference to db will be lost and garbage collected.
Your two instances of db are also of different types - SQLiteDatabase and DatabaseHelper, so a better variable naming strategy would help avoid problems like this in the future. As we'll be using the SQLiteDatabase version of db, we'll need to grab a writable instance of your database to use with the helper in future:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_item);
db = new DatabaseHelper(this).getWritableDatabase();
...
}
This will ensure that you're setting the member variable rather than a local variable.
Related
I have created two tables user_table and vehicle_table in a sqlite database user_data in which i am accepting data using two .xml activities. One activity page works fine but the page i used to operate the second table isn't working. its showing: "App has stopped working". here are all the codes. Please help me find the errors here.
Database: user_data_sql.java
package com.example.login;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class user_data_sql extends SQLiteOpenHelper {
public static final String DATABASE_NAME= "user_data1.db";
public static final String TABLE_NAME= "user_table";
public static final String TABLE_NAME2= "vehicle_table";
public static final String COL_1= "USER_ID";
public static final String COL_2= "FIRST_NAME";
public static final String COL_3= "LAST_NAME";
public static final String COL_4= "PHN_NO";
public static final String COL_5= "DOB";
public static final String COL_6= "ADHAR_NO";
public static final String COL_7= "LICENSE_NO";
public static final String COL_8= "LICENSE_VALIDITY";
public static final String COLV_1 = "VehicleID";
public static final String COLV_3 = "RCNumber";
public static final String COLV_4 = "RCValidity";
public static final String COLV_5 = "ChassisNumber";
public static final String COLV_6 = "InsuranceNumber";
public static final String COLV_7 = "InsuranceValidity";
public static final String COLV_8 = "PUCValidity";
public user_data_sql(#Nullable Context context) {
super(context, DATABASE_NAME,null, 1);
SQLiteDatabase db= this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+ TABLE_NAME+"(USER_ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST_NAME TEXT, " +
"LAST_NAME TEXT, PHN_NO INT, DOB TEXT, ADHAR_NO INT, LICENSE_NO TEXT, LICENSE_VALIDITY INT)");
//recentchanges
db.execSQL("create table "+ TABLE_NAME2+"(VehicleID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"RCNUMBER TEXT,RCValidity Date,ChassisNumber TEXT,InsuranceNumber INTEGER,InsuranceValidity Date," +
"PUCValidity Date,USER_ID INT, FOREIGN KEY(USER_ID) REFERENCES user_table(USER_ID))");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME2);
onCreate(db);
}
public boolean insertData(String FIRST_NAME,String LAST_NAME, String PHN_NO, String DOB, String ADHAR_NO,
String LICENSE_NO, String LICENSE_VALIDITY)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, FIRST_NAME);
contentValues.put(COL_3, LAST_NAME);
contentValues.put(COL_4, PHN_NO);
contentValues.put(COL_5, DOB);
contentValues.put(COL_6, ADHAR_NO);
contentValues.put(COL_7, LICENSE_NO);
contentValues.put(COL_8, LICENSE_VALIDITY);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1;
}
public boolean insertData1(String rcNumber,String rcValidity,String chassisNumber,
String insuranceNumber,String insuranceValidity,String pucValidity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COLV_3,rcNumber);
contentValues1.put(COLV_4,rcValidity);
contentValues1.put(COLV_5,chassisNumber);
contentValues1.put(COLV_6,insuranceNumber);
contentValues1.put(COLV_7,insuranceValidity);
contentValues1.put(COLV_8,pucValidity);
long result = db.insert(TABLE_NAME2,null,contentValues1);
return result != -1;
}
}
page1: qr2.java
package com.example.login;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
public class QR2 extends AppCompatActivity {
user_data_sql myDb;
EditText etFirstName,etLastName,etPhoneNumber, etDOB, etAadhar, etLicenseNumber, etLicenseValidity;
Button Generate2, Save, Next;
ImageView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q_r2);
myDb =new user_data_sql(this);
etFirstName=(EditText) findViewById(R.id.etFirstName);
etLastName=(EditText) findViewById(R.id.etLastName);
etPhoneNumber=(EditText) findViewById(R.id.etPhoneNumber);
etDOB=(EditText) findViewById(R.id.etDOB);
etAadhar=(EditText) findViewById(R.id.etAadhar);
etLicenseNumber=(EditText) findViewById(R.id.etLicenseNumber);
etLicenseValidity=(EditText) findViewById(R.id.etLicenseValidity);
Generate2=(Button) findViewById(R.id.btnGenerate2);
output=(ImageView) findViewById(R.id.Output);
Save=(Button) findViewById(R.id.btnSave);
Next=(Button) findViewById(R.id.btnNext);
AddData();
Generate2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//get input value from edit text
String data = etFirstName.getText().toString().trim();
MultiFormatWriter writer=new MultiFormatWriter();
try {
BitMatrix matrix=writer.encode(data, BarcodeFormat.QR_CODE,350,350);
//Initialise barcode encoder
BarcodeEncoder encoder=new BarcodeEncoder();
//Initialise bitmap
Bitmap bitmap=encoder.createBitmap(matrix);
//set bitmap to image view
output.setImageBitmap(bitmap);
//initialise input manager
InputMethodManager manager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//hide soft keyboard
manager.hideSoftInputFromWindow(etFirstName.getApplicationWindowToken(),0);
} catch (WriterException e) {
e.printStackTrace();
}
}
});
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent3 = new Intent(QR2.this, Vehicle_info.class);
startActivity(intent3);
}
});
}
public void AddData()
{
Save.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
boolean isInserted= myDb.insertData(etFirstName.getText().toString(),
etLastName.getText().toString(),etPhoneNumber.getText().toString(),
etDOB.getText().toString(),etAadhar.getText().toString(),
etLicenseNumber.getText().toString(),
etLicenseValidity.getText().toString());
if(isInserted)
Toast.makeText(QR2.this,"Data Inserted",
Toast.LENGTH_LONG).show();
else
Toast.makeText(QR2.this,"Data NOT Inserted",
Toast.LENGTH_LONG).show();
}
}
);
}
}
page2: Vehicle_info.java
package com.example.login;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class Vehicle_info extends AppCompatActivity {
user_data_sql myDb;
EditText editrcNumber,editrcValidity,editchassisNumber,editinsuranceNumber,editinsuranceValidity,editpucValidity;
Button btnAddData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vehicle_info);
myDb = new user_data_sql(this);
editrcNumber = (EditText)findViewById(R.id.etRCNumber);
editrcValidity = (EditText)findViewById(R.id.etRCValidity);
editchassisNumber = (EditText)findViewById(R.id.etChassisNumber);
editinsuranceNumber = (EditText)findViewById(R.id.etInsuranceNumber);
editinsuranceValidity = (EditText)findViewById(R.id.etInsuranceValidity);
editpucValidity = (EditText)findViewById(R.id.etPUCValidity);
btnAddData = (Button)findViewById(R.id.btnSave);
AddData1();
}
public void AddData1()
{
btnAddData.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v) {
boolean isInserted= myDb.insertData1(editrcNumber.getText().toString(),
editrcValidity.getText().toString(),editchassisNumber.getText().toString(),
editinsuranceNumber.getText().toString(),editinsuranceValidity.getText().toString(),
editpucValidity.getText().toString());
if(isInserted)
Toast.makeText(Vehicle_info.this,"Data Inserted",
Toast.LENGTH_LONG).show();
else
Toast.makeText(Vehicle_info.this,"Data NOT Inserted",
Toast.LENGTH_LONG).show();
}
}
);
}
}
Without the stack-trace "App has stopped working" could have many causes.
You should perhaps check out https://developer.android.com/studio/debug/ to finds out how to obtain a stack-trace amongst other debugging techniques.
However, a clue to very likely cause is "//recentchanges". It looks as though you may have added the second table after running the App but not properly catered for the changes to be applied to the database.
The onCreate method in the DatabaseHelper (i.e. your user_data_sql class) is only run/invoked when the database doesn't exist. As such this was probably run only with the first table.
The onUpgrade method where you drop and recreate the tables will only run if the database version is increased. The database version is the 4th parameter passed to the super call. You have:-
super(context, DATABASE_NAME,null, 1);
As such it appears that you have not allowed for the onUpgrade method to run.
Fix 1
Changing the super call to :-
super(context, DATABASE_NAME,null, 2 /*<<<<<<<<<< INCREASED DATABASE VERSION*/);
comment after 4th parameter included just to highlight the change made to the Database Version number.
Should result in the onUpgrade method being called which should then drop the tables and then create them (losing any existing data) and it is quite probable that your code will then work, or at least progress further.
Note that typically you would limit the code run in the onUpgrade method to only those steps needed to introduce the changes by utilising/inspecting the oldversion (2nd parameter i in your code) and the newversion (3rd parameter or i1 in your code).
Fix 2/3
An alternative and perhaps simpler could be to delete the database in which case the Databasehelper's onCreate method would run, the database version number can remain as 1. The simplest way to delete the database would be to uninstall the app and then rerun the app. You could also delete the files in the data/data/<package_name>/databases folder (e.g. via Android Studio's Device Explorer) and then re run the app.
Note as originally stated this is just a guess as to a likely cause of your problem(s).
I am using sqlite for database. When i add data in ListView. Data added correctly. But when i close app then updated list lost data which i added before. With code Statically added data shows but using app when create reminder then data added successfully in ListView. But when i restart app new data lost after restart app I mean creating reminder delete automatically after restart app.
Even I delete reminders which added by code after restart app all deleted reminders showing in ListView again. But Dynamically added data not show.
Please help me to solve this problem.
Here is my Activity code
RemindersActivity.java
package com.example.remindersapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
public class RemindersActivity extends AppCompatActivity {
private ListView mlistView;
private RemindersDbAdapter remindersDbAdapter;
private ReminderSimpleCursorAdapter reminderSimpleCursorAdapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminders);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.mipmap.ic_launcher_reminder);
mlistView = (ListView) findViewById(R.id.reminder_listView);
// mlistView.setDivider(null);
remindersDbAdapter = new RemindersDbAdapter(this);
remindersDbAdapter.open();
if (savedInstanceState == null) {
//clear all data
remindersDbAdapter.deleteAllReminders();
//add some data
insertSomeReminders();
}
Cursor cursor = remindersDbAdapter.fetchAllReminders();
//from columns defined in the db
String[] from = new String[]{remindersDbAdapter.COL_CONTENT};
//to the ids of views in the layout
int[] to = new int[]{R.id.row_text};
reminderSimpleCursorAdapter = new ReminderSimpleCursorAdapter(
RemindersActivity.this,
//the layout of the row
R.layout.reminders_row,
cursor,
//from columns defined in the db
from,
//to the ids of views in the layout
to,
//flag - not used
0);
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
// this,
// R.layout.reminders_row,
// R.id.row_text,
// new String[]{"fisrt record", "second record", "third record"
// , "fourth record", "fifth record"});
mlistView.setAdapter(reminderSimpleCursorAdapter);
//Adapter is a
//special Java class defined as part of the Android SDK that functions as the Controller in
//the Model-View-Controller relationship
//when we click an individual item in the listview
mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int masterposition, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(RemindersActivity.this);
ListView modeListView = new ListView(RemindersActivity.this);
String[] modes = new String[]{"Edit Reminder", "Delete Reminder", "Scheduled Reminder"};
ArrayAdapter<String> modeAdapter = new ArrayAdapter<>(RemindersActivity.this,
android.R.layout.simple_list_item_1, android.R.id.text1, modes);
modeListView.setAdapter(modeAdapter);
builder.setView(modeListView);
final Dialog dialog = builder.create();
dialog.show();
modeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//edit reminder
// if (position == 0) {
// Toast.makeText(RemindersActivity.this, "edit" + masterposition, Toast.LENGTH_SHORT).show();
// } else {
// Toast.makeText(RemindersActivity.this, "delete" + masterposition, Toast.LENGTH_SHORT).show();
// }
// dialog.dismiss();
int nId = getIdFromPosition(masterposition);
final Reminder reminder = remindersDbAdapter.fetchReminderById(nId);
if (position == 0) {
fireCustomDialog(reminder);
//delete reminder
} else if (position == 1) {
remindersDbAdapter.deleteReminderById(getIdFromPosition(masterposition));
reminderSimpleCursorAdapter.changeCursor(remindersDbAdapter.fetchAllReminders());
}
else {
// final Date today = new Date();
// new TimePickerDialog(RemindersActivity.this,null,today.getHours(),today.getMinutes(),
// false).show();
TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Date alarm = new Date(today.getYear(), today.getMonth(), today.getDate(), hourOfDay, minute);
// scheduleReminder(alarm.getTime(), reminder.getmContent());
//This creates a listener for the time picker dialog box. Inside this listener, you use today’s
//date as the base time for your alarm. You then include the hour and minute chosen from
//the dialog box to create the alarm date variable for your reminder. You use both the alarm
//time and the reminder’s content in a new scheduleReminder() method
//Fix the deprecation warnings
final Calendar alarmTime = Calendar.getInstance();
alarmTime.set(Calendar.HOUR, hourOfDay);
alarmTime.set(Calendar.MINUTE, minute);
scheduleReminder(alarmTime.getTimeInMillis(), reminder.getmContent());
}
};
final Calendar today = Calendar.getInstance();
// new TimePickerDialog(RemindersActivity.this, null,
// today.get(Calendar.HOUR), today.get(Calendar.MINUTE), false).show();
//the following change to connect the
//listener that invokes the BroadcastReceiver to the TimePickerDialog
new TimePickerDialog(RemindersActivity.this, listener,
today.get(Calendar.HOUR), today.get(Calendar.MINUTE), false).show();
}
dialog.dismiss();
}
});
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mlistView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mlistView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
//The preceding logic defines a MultiChoiceModeListener and attaches it to the ListView.
//Whenever you long-press an item in the ListView, the runtime invokes the onCreateActionMode()
//method on the MultiChoiceModeListener. If the method returns with the boolean true value,
//multichoice action mode is entered.
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.cam_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_reminder:
for (int nC = reminderSimpleCursorAdapter.getCount() - 1; nC >= 0; nC--) {
if (mlistView.isItemChecked(nC)) {
remindersDbAdapter.deleteReminderById(getIdFromPosition(nC));
}
}
mode.finish();
reminderSimpleCursorAdapter.changeCursor(remindersDbAdapter.fetchAllReminders());
return true;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
}
private void scheduleReminder(long time, String getmContent) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, ReminderAlarmReceiver.class);
alarmIntent.putExtra(ReminderAlarmReceiver.REMINDER_TEXT, getmContent);
PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, broadcast);
}
private int getIdFromPosition(int nC) {
return (int) reminderSimpleCursorAdapter.getItemId(nC);
}
private void insertSomeReminders() {
remindersDbAdapter.createReminder("Learn android Development", true);
remindersDbAdapter.createReminder("data Mining Assignment", false);
remindersDbAdapter.createReminder("Networking Assignment", false);
remindersDbAdapter.createReminder("English Assignment", true);
// //There are several calls to the createReminder() method, each taking a String value
//with the reminder text and a boolean value flagging the reminder as important. We set
//a few values to true to provide a good visual effect.
}
private void fireCustomDialog(final Reminder reminder) {
// custom dialog
Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_custom);
TextView titleView = (TextView) dialog.findViewById(R.id.custom_title);
final EditText editCustom = (EditText) dialog.findViewById(R.id.custom_edit_reminder);
Button commitButton = (Button) dialog.findViewById(R.id.custom_button_commit);
final CheckBox checkBox = (CheckBox) dialog.findViewById(R.id.custom_check_box);
// checkBox.setChecked(true);
LinearLayout rootLayout = (LinearLayout) dialog.findViewById(R.id.custom_root_layout);
final boolean isEditOperation = (reminder != null);
//this is for an edit
if (isEditOperation) {
titleView.setText("Edit Reminder");
checkBox.setChecked(reminder.getImportant() == 1);
editCustom.setText(reminder.getmContent());
rootLayout.setBackgroundColor(getResources().getColor(R.color.check_box));
}
commitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String reminderText = editCustom.getText().toString();
if (isEditOperation) {
Reminder reminderEdit = new Reminder(reminder.getmId(),
reminderText, checkBox.isChecked() ? 1 : 0);
remindersDbAdapter.updateReminder(reminderEdit);
} else {
remindersDbAdapter.createReminder(reminderText, checkBox.isChecked());
}
reminderSimpleCursorAdapter.changeCursor(remindersDbAdapter.fetchAllReminders());
dialog.dismiss();
}
});
Button buttonCancel = (Button) dialog.findViewById(R.id.custom_button_cancel);
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.reminder_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_new:
//create new reminder
Log.d(getLocalClassName(), "create new reminder");
fireCustomDialog(null);
return true;
case R.id.action_exit:
finish();
return true;
case R.id.action_about:
fireAboutDialog();
return true;
default:
return false;
}
}
private void fireAboutDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_about);
dialog.show();
}
}
RemindersDbAdapter.java
package com.example.remindersapp;
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 RemindersDbAdapter {
//these are the column names
public static final String COL_ID = "_id";
public static final String COL_CONTENT = "content" ;
public static final String COL_IMPORTANT = "important";
//these are the corresponding indices
private static final int INDEX_ID = 0;
private static final int INDEX_CONTENT = INDEX_ID + 1;
private static final int INDEX_IMPORTANT = INDEX_ID + 2;
//used for logging
private static final String TAG = "RemindersDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "dba_reminder";
private static final String TABLE_NAME = "table_reminder";
private static final int DATABASE_VERSION = 3;
private final Context mCtx;
////SQL statement used to create the database
private static final String DATABSE_CREATE = "CREATE TABLE if not exists " + TABLE_NAME + " ( " +
COL_ID + " INTEGER PRIMARY KEY autoincrement, " +
COL_CONTENT + " TEXT, " +
COL_IMPORTANT + " INTEGER );";
public RemindersDbAdapter(Context Ctx) {
//The constructor saves an instance of Context, which is passed to DatabaseHelper
this.mCtx = Ctx;
}
//The open()
//method initializes the helper and uses it to get an instance of the database,
public void open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
}
//the close()
//method uses the helper to close the database.
public void close() throws SQLException {
if (mDbHelper != null) {
mDbHelper.close();
}
}
//CREATE
//note that the id will be created for you automatically
public void createReminder(String name, boolean important) {
ContentValues values = new ContentValues();
values.put(COL_CONTENT, name);
values.put(COL_IMPORTANT, important ? 1 : 0);
mDb.insert(TABLE_NAME, null, values);
}
////overloaded to take a reminder
public long createReminder(Reminder reminder) {
ContentValues values = new ContentValues();
values.put(COL_CONTENT, reminder.getmContent()); //Contact name
values.put(COL_IMPORTANT, reminder.getImportant()); //Contact phone number
//// Inserting Row
return mDb.insert(TABLE_NAME, null, values);
}
//READ
public Reminder fetchReminderById(int id) {
Cursor cursor = mDb.query(TABLE_NAME,
new String[]{COL_ID, COL_CONTENT, COL_IMPORTANT},
COL_ID + " =? ",
new String[]{String.valueOf(id)},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
return new Reminder(
cursor.getInt(INDEX_ID),
cursor.getString(INDEX_CONTENT),
cursor.getInt(INDEX_IMPORTANT));
}
public Cursor fetchAllReminders() {
Cursor mcursor = mDb.query(TABLE_NAME, new String[]{COL_ID, COL_CONTENT, COL_IMPORTANT},
null, null, null, null, null);
if (mcursor != null) {
mcursor.moveToFirst();
}
return mcursor;
}
//UPDATE
public void updateReminder(Reminder reminder) {
ContentValues values = new ContentValues();
values.put(COL_CONTENT, reminder.getmContent());
values.put(COL_IMPORTANT, reminder.getImportant());
mDb.update(TABLE_NAME, values, COL_ID + " =? ", new String[]{String.valueOf(reminder.getmId())});
}
//DELETE
public void deleteReminderById(int id){
mDb.delete(TABLE_NAME,COL_ID + "=?", new String[]{String.valueOf(id)});
}
public void deleteAllReminders(){
mDb.delete(TABLE_NAME,null,null);
}
//sqlite open helper
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABSE_CREATE);
db.execSQL(DATABSE_CREATE);
}
#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 " + TABLE_NAME);
onCreate(db);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
onCreate(db);
}
}
}
ReminderSimpleCursorAdapter.java
package com.example.remindersapp;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import androidx.recyclerview.widget.RecyclerView;
public class ReminderSimpleCursorAdapter extends SimpleCursorAdapter {
public ReminderSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int i) {
super(context, layout, c, from, to,i);
}
////to use a viewholder, you must override the following two methods and define a ViewHolder class
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return super.newView(context, cursor, parent);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
ViewHolder holder=(ViewHolder)view.getTag();
if (holder == null){
holder=new ViewHolder();
holder.colImp=cursor.getColumnIndexOrThrow(RemindersDbAdapter.COL_IMPORTANT);
holder.listTab=view.findViewById(R.id.row_tab);
view.setTag(holder);
}
if (cursor.getInt(holder.colImp) > 0){
holder.listTab.setBackgroundColor(context.getResources().getColor(R.color.false_result));
}else {
holder.listTab.setBackgroundColor(context.getResources().getColor(R.color.txt_color));
}
}
//Here you see an example of the ViewHolder pattern. This is a well-known Android pattern
//in which a small ViewHolder object is attached as a tag on each view. This object adds
//decoration for View objects in the list by using values from the data source, which in this
//example is the Cursor. The ViewHolder is defined as a static inner class with two instance
//variables, one for the index of the Important table column and one for the row_tab view you
//defined in the layout.
static class ViewHolder{
//store the column index
int colImp;
//store the view
View listTab;
}
}
Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.
package ie.wit.andrew.drivingschool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER"; //Making up my
//database of the
//information I will
//be entering into my
//application
public static final String COL_5 = "LESSON NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //when this constructor is
//called your Database has been
//created
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,dateofbirth);
contentValues.put(COL_4,logbooknumber);
contentValues.put(COL_5,lessonnumber);
long result = db.insert(TABLE_NAME,null,contentValues); //This method
//returns -1
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
return res;
}
}
package ie.wit.andrew.drivingschool;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DrivingSchool extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driving_school);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
AddData();
viewAll();
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(editName.getText().toString(),
editDateofBirth.getText().toString(),
editLogbookNumber.getText().toString(),
editLessonNumber.getText().toString());
if(isInserted = true)
Toast.makeText(DrivingSchool.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(DrivingSchool.this,"Data not
Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//Show Message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append("ID : "+ res.getString(0)+"\n");
buffer.append("NAME : "+ res.getString(1)+"\n");
buffer.append("DATE OF BIRTH : "+
res.getString(2)+"\n");
buffer.append("LOGBOOK NUMBER : "+
res.getString(3)+"\n\n");;
}
//showdata
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
Try removing space from your column name's
you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Im creating an app where users can enter the movies they own, to show in a listview, and for random picking a movie from that list.
Now what my problem is, that when clicking on an item in the listview a new activity opens op where the item clicked is the title in a textview. So far i can get the movie from the list who is number 1 to show, but that shows it's title no matter which list item I click, how can i get the specific name depending on what item is clicked?? Thanks in advance.
My Database class:
package com.example;
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 MovieDatabaseHelper {
private static final String TAG = MovieDatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "mymoviedatabase.db";
// table configuration
private static final String TABLE_NAME = "movie_table"; // Table name
private static final String MOVIE_TABLE_COLUMN_ID = "_id"; // a column named "_id" is required for cursor
private static final String MOVIE_TABLE_COLUMN_TITLE = "movie_title";
private static final String MOVIE_TABLE_COLUMN_YEAR = "production_year";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with MovieDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public MovieDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aMovieTitle, String aMovieYear) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(MOVIE_TABLE_COLUMN_TITLE, aMovieTitle);
contentValues.put(MOVIE_TABLE_COLUMN_YEAR, aMovieYear);
database.insert(TABLE_NAME, null, contentValues);
}
//Retrieves all the records
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME + " ORDER BY " + MOVIE_TABLE_COLUMN_TITLE + " COLLATE NOCASE";
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// Retrieves specific record
public String getMovieTitle()
{
Cursor c =
database.query(TABLE_NAME,
new String[] { MOVIE_TABLE_COLUMN_TITLE }, null, null, null, null, null);
if (c.moveToFirst())
return c.getString(c.getColumnIndex(MOVIE_TABLE_COLUMN_TITLE ));
else
return "Nothing";
}
// Retrieves a random entry from the Database
public String getRandomMovie()
{
Cursor c = database.query(TABLE_NAME + " ORDER BY RANDOM() LIMIT 1",
new String[] { MOVIE_TABLE_COLUMN_TITLE }, null, null, null, null, null);
if(c.moveToFirst())
return c.getString(c.getColumnIndex(MOVIE_TABLE_COLUMN_TITLE ));
else
return "nothing";
}
//Check if record exist
//---deletes a particular record---
public void delete(int _id)
{
database.delete(TABLE_NAME, MOVIE_TABLE_COLUMN_ID+"="+_id, null);
}
//---updates a record---
public boolean updateRecord(long _id, String movie_title)
{
ContentValues args = new ContentValues();
args.put(MOVIE_TABLE_COLUMN_TITLE, movie_title);
return database.update(TABLE_NAME, args, MOVIE_TABLE_COLUMN_ID + "=" + _id, null) > 0;
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + MOVIE_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
MOVIE_TABLE_COLUMN_TITLE + " TEXT, " + MOVIE_TABLE_COLUMN_YEAR + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
My listview class:
package com.example;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
//import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
private MovieDatabaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
MediaPlayer mp;
private static final String TAG = MyActivity.class.getSimpleName();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dblist);
databaseHelper = new MovieDatabaseHelper(this);
final MediaPlayer mp = MediaPlayer.create(MyActivity.this, R.raw.cartoon015);
listView = (ListView) findViewById(R.id.list_data);
ImageButton okay = (ImageButton) findViewById(R.id.okay);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
Intent i = new Intent(MyActivity.this,IMDb.class);
startActivity(i);
Log.d(TAG, "clicked on item: " + position);
}
}
);
okay.setOnClickListener
(new View.OnClickListener()
{
public void onClick(View v)
{
mp.start();
mp.setVolume((float) 0.3, (float) 0.3);
Intent intent = new Intent(MyActivity.this,MovieActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
);
// Database query can be a time consuming task ..
// so its safe to call database query in another thread
// Handler, will handle this stuff for you <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g" alt=":)" class="wp-smiley">
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
}
public void onClickEnterData(View btnAdd) {
final MediaPlayer mp = MediaPlayer.create(MyActivity.this, R.raw.cartoon015);
mp.start();
mp.setVolume((float) 0.1, (float) 0.1);
startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(data.getExtras().getString("tag_movie_title"), data.getExtras().getString("tag_movie_year"));
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
}
My movie detail class:
package com.example;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class IMDb extends Activity {
TextView Movietitle;
private MovieDatabaseHelper databaseHelper;
MediaPlayer mp;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.imdb);
Movietitle = (TextView) findViewById(R.id.movietitle);
databaseHelper = new MovieDatabaseHelper(this);
Button delete = (Button) findViewById(R.id.delete);
Movietitle.setText( databaseHelper.getMovieTitle());
}
}
Well, there is lot of code you are asking for. But I can tell you the steps
Create a Model Class for your movie,, where you can hold the db records
Create list of Model Class and then when you click the item, you get the position of record in list.
Your movie Model class must have getter and setter functions to retrieve record details.
Can somebody help me I wrote this app, but it doesn't work and I don't find the solution.
1st error:
java.lang.illegalstateexception could not read row 0 col 1 from cursor window. Make sure the cursor is initialized correctly before accessing data from it
2nd error:
android.database.sqlite.SQLite Exception: near "=": syntax error (code 1): while compiling: SELECT ZAHL1 FROM Verlauf WHERE ID =
package com.example.to_doliste2;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivityT extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t);
datasource = new VerlaufDataSource(this);
}
private VerlaufDataSource datasource;
List<Entry> AufgabenListe = new ArrayList<Entry>();
public void VerlaufKlick(View view)
{
try
{
String zahl1;
EditText Feld1 = (EditText)findViewById(R.id.editText1);
if (Feld1.getText().toString().length() == 0)
{
return;
}
zahl1 = (Feld1.getText().toString());
Feld1.setText(String.valueOf(zahl1));
try
{
datasource.open();
datasource.createEntry(zahl1);
datasource.close();
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
AufgabenListe.clear();
try
{
datasource.open();
AufgabenListe = datasource.getAllEntries();
datasource.close();
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
ArrayAdapter<Entry> adapterVerlauf = new ArrayAdapter<Entry>(MainActivityT.this, android.R.layout.simple_list_item_1, AufgabenListe);
ListView lVerlauf = (ListView)findViewById(R.id.listView1);
lVerlauf.setAdapter(adapterVerlauf);
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
}
}
package com.example.to_doliste2;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class MySQLHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "verlaufAufgaben.db";
public static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE_VERLAUF = ""
+"create table VERLAUF ("
+" ID integer primary key, "
+" Zahl1 int) ";
public MySQLHelper(Context context)
{
super (context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_CREATE_VERLAUF);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(MySQLHelper.class.getName(),
"Upgrading database from version " + oldVersion + "to "
+ newVersion + ", which all destroy all old data");
db.execSQL("DROP TABLE IF EXISTS SCANITEM");
onCreate(db);
}
}
package com.example.to_doliste2;
public class Entry {
private int zahl1;
public int getZahl1()
{
return zahl1;
}
public void setZahl1(int zahl1)
{
this.zahl1 = zahl1;
}
#Override
public String toString()
{
return String.format("%d", zahl1);
}
}
package com.example.to_doliste2;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class VerlaufDataSource {
private SQLiteDatabase database;
private MySQLHelper dbHelper;
private String[] allColumns = {"ZAHL1"};
public VerlaufDataSource(Context context)
{
dbHelper = new MySQLHelper(context);
}
public void open() throws SQLException
{
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public Entry createEntry(String zahl1)
{
ContentValues values = new ContentValues();
values.put("ZAHL1", zahl1);
long insertId = database.insert("Verlauf", null, values);
Cursor cursor = database.query("Verlauf", allColumns, "ID = " + insertId, null, null, null, null);
cursor.moveToFirst();
return cursorToEntry(cursor);
}
protected List<Entry> getAllEntries()
{
List<Entry> EntriesList = new ArrayList<Entry>();
EntriesList = new ArrayList<Entry>();
Cursor cursor = database.query("Verlauf", allColumns, "ID =" , null, null, null, null, null);
cursor.moveToFirst();
if(cursor.getCount() == 0) return EntriesList;
while (cursor.isAfterLast()==false)
{
Entry entry = cursorToEntry(cursor);
EntriesList.add(entry);
cursor.moveToNext();
}
cursor.close();
return EntriesList;
}
private Entry cursorToEntry(Cursor cursor)
{
Entry entry = new Entry();
entry.setZahl1(cursor.getInt(1));
return entry;
}
}
if you are retrieving all columns from database then change your query as:
Cursor cursor = database.query("Verlauf",
allColumns, null, null, null, null, null);
First, change the cursor.getInt(1) inside VerlaufDataSource.cursorToEntry(Cursor) to cursor.getInt(0), because the count starts from 0, and you have queried for only one column (allColumns == { "ZAHL1" }).
Secondly, as ρяσѕρєя K mentioned above, "ID =" is not a correct WHERE-clause in VerlaufDataSource.getAllEntries(). Change it to null if you want all the columns.