SQLite Database issue in TextView - java

I've been working on an app where the main Activity leads to CalendarActivity, which has a button leading to another Activity where the user creates an event. Once the event is created, the user is taken back to CalendarActivity, and a previously empty TextView displays the event. The code I've used seems like it should work, and is near verbatim from an online tutorial. I researched the comments of the video and the video maker's blog, and many others seem to say it works fine. I've check over and over, and I believe that its grammatically correct, etc, but I can not get it to load the event into the TextView. Any pointers even would help. I would ask you keep it near basic english, I am just getting into programming and am using this app as a learning experience.
Thanks!
CalendarActivity:
package com.bm.sn.sbeta;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class CalendarActivity extends AppCompatActivity {
CalendarView calendar;
Button createEvent;
public static String createEventDate;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
Cursor result = db.getAllData();
if (result.getCount() == 0) {
noEventToday();
}else{
TextView eventList = (TextView)findViewById(R.id.eventList);
StringBuffer stringBuffer = new StringBuffer();
while (result.moveToNext()) {
stringBuffer.append("eventDat : "+result.getString(0)+"\n");
stringBuffer.append("timeHour : "+result.getString(1)+"\n");
stringBuffer.append("timeMinue : "+result.getString(2)+"\n");
stringBuffer.append("event : "+result.getString(3)+"\n");
stringBuffer.append("location : "+result.getString(4)+"\n");
stringBuffer.append("crew : "+result.getString(5)+"\n\n");
eventList.setText(stringBuffer);
}
}
calendar = (CalendarView)findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
createEventDate = (month+"."+dayOfMonth+"."+year);
createEvent.setText("Create Event for "+createEventDate);
}
});
createEvent = (Button)findViewById(R.id.eventCreateButton);
createEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toEventCreateActivity = new Intent(CalendarActivity.this, EventCreateActivity.class);
startActivity(toEventCreateActivity);
}
});
}
/*public void fillEventList (){
}
public void noEventToday(){
TextView eventList = (TextView)findViewById(R.id.eventList);
eventList.setText("Nothing scheduled for today.");
}*/
}
EventCreateActivity:
package com.bm.sn.sbeta;
import android.content.Intent;
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.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class EventCreateActivity extends AppCompatActivity {
DatabaseHelper db;
String textViewText = CalendarActivity.createEventDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_create);
db = new DatabaseHelper(this);
final TextView titleTextView = (TextView)findViewById(R.id.titleTextView);
titleTextView.setText("Create event for "+textViewText);
final TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
final EditText entryEvent = (EditText)findViewById(R.id.entryEvent);
final EditText entryLocation = (EditText)findViewById(R.id.entryLocation);
final EditText entryCrew = (EditText)findViewById(R.id.entryCrew);
Button createEventButton = (Button)findViewById(R.id.saveEvent);
createEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertData(
titleTextView.toString(),
timePicker.getCurrentHour().toString(),
timePicker.getCurrentMinute().toString(),
entryEvent.getText().toString(),
entryLocation.getText().toString(),
entryCrew.getText().toString()
);
Toast.makeText(EventCreateActivity.this, "I'll keep that in mind.", Toast.LENGTH_LONG).show();
Intent toCalendarActivity = new Intent(EventCreateActivity.this, CalendarActivity.class);
startActivity(toCalendarActivity);
}
});
}
}
DatabaseHelper:
package com.bm.sn.sbeta;
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 = "SavitaCalendar.db";
public static final String TABLE_NAME = "CalendarEvents";
public static final String col_0 = "ID";
public static final String col_1 = "eventDate" ;
public static final String col_2 = "timeHour";
public static final String col_3 = "timeMinute";
public static final String col_4 = "event";
public static final String col_5 = "location";
public static final String col_6 = "crew";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT,EVENTDATE TEXT,TIMEHOUR TEXT,TIMEMINUTE TEXT, EVENT TEXT, LOCATION TEXT, CREW TEXT); ");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public void insertData (String eventDate, String timeHour, String timeMinute, String event, String location, String crew){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col_1, eventDate);
contentValues.put(col_2, timeHour);
contentValues.put(col_3, timeMinute);
contentValues.put(col_4, event);
contentValues.put(col_5, location);
contentValues.put(col_6, crew);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("select * from "+TABLE_NAME, null);
return result;
}
}

You're reading your data from the DB in onCreate().
onCreate() is called when the Activity is (re)created. It is not guaranteed that it will be called when you navigate back from EventCreateActivity.
Take a look at the docs on the Activity lifecycle.
As #nuccio pointed it out, you also seem to forgot to initialize your DatabaseHelper instance.
You should use a singleton pattern there, something like this:
private static DatabaseHelper instance;
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
public static DatabaseHelper getInstance(Context context) {
if (instance == null) {
instance = new DatabaseHelper(context.getApplicationContext());
}
return instance;
}
You could start EventCreateActivity using startActivityForResult(), and override onActivityResult() in CalendarActivity to update your TextView.
For example:
public class CalendarActivity extends AppCompatActivity {
private static final int REQUEST_CREATE_EVENT = 0;
CalendarView calendar;
Button createEvent;
public static String createEventDate;
TextView eventList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
eventList = (TextView) findViewById(R.id.eventList);
getEvents();
calendar = (CalendarView) findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
createEventDate = (month + "." + dayOfMonth + "." + year);
createEvent.setText("Create Event for " + createEventDate);
}
});
createEvent = (Button) findViewById(R.id.eventCreateButton);
createEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toEventCreateActivity = new Intent(CalendarActivity.this, EventCreateActivity.class);
startActivityForResult(toEventCreateActivity, REQUEST_CREATE_EVENT);
}
});
}
private void getEvents() {
// getting our DatabaseHelper instance
DatabaseHelper db = DatabaseHelper.getInstance(this);
Cursor result = db.getAllData();
if (result.getCount() == 0) {
noEventToday();
} else {
StringBuffer stringBuffer = new StringBuffer();
while (result.moveToNext()) {
stringBuffer.append("eventDat : " + result.getString(0) + "\n");
stringBuffer.append("timeHour : " + result.getString(1) + "\n");
stringBuffer.append("timeMinue : " + result.getString(2) + "\n");
stringBuffer.append("event : " + result.getString(3) + "\n");
stringBuffer.append("location : " + result.getString(4) + "\n");
stringBuffer.append("crew : " + result.getString(5) + "\n\n");
eventList.setText(stringBuffer);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode == REQUEST_CREATE_EVENT) {
getEvents();
}
}
public void noEventToday(){
TextView eventList = (TextView)findViewById(R.id.eventList);
eventList.setText("Nothing scheduled for today.");
}
}
And in EventCreateActivity:
createEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertData(
titleTextView.toString(),
timePicker.getCurrentHour().toString(),
timePicker.getCurrentMinute().toString(),
entryEvent.getText().toString(),
entryLocation.getText().toString(),
entryCrew.getText().toString()
);
Toast.makeText(EventCreateActivity.this, "I'll keep that in mind.", Toast.LENGTH_LONG).show();
setResult(RESULT_OK);
finish();
}
});
An even better approach would be to pass your new event data in the Intent, so you don't have to read the DB when going back to CalendarActivity.
Or at least return the new row ID, so only one record needs to be queried.

You didn't instantiate your db properly in CalendarActivity.
add this
db = new DatabaseHelper(this);
Here is where to add this to the class:
package com.mac.training.calendaractivitysqlhelperthing;
imports ...
public class CalendarActivity extends AppCompatActivity {
CalendarView calendar;
Button createEvent;
public static String createEventDate;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
//ADD this line here
db = new DatabaseHelper(this);
Cursor result = db.getAllData();
if (result.getCount() == 0) {
//noEventToday();
}else{
//etc
That alone should work, but if not. Also update your Manifest as well with this:
activity android:name=".EventCreateActivity"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mac.training.calendaractivitysqlhelperthing">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".CalendarActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".EventCreateActivity" />
</application>
</manifest>

Related

How to show records from sqlite database on my app in a listview

I'm creating an app for doctor's appointment.. So I want to see the booked appointments records in the listview for different activities with a delete button to delete a specific record..
this is my code for making appointments...
that is Appo.java
package com.example.medilyf;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class Appo extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet, confirm, seeappo;
TextView tvw, text, receiver_msg;
DBHelper myDB;
CheckBox android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appo);
tvw = findViewById(R.id.textView1);
eText = findViewById(R.id.editText1);
myDB = new DBHelper(Appo.this);
android = findViewById(R.id.checkBox);
angular = findViewById(R.id.checkBox1);
java = findViewById(R.id.checkBox2);
python = findViewById(R.id.checkBox3);
text = findViewById(R.id.txt);
Button btn = findViewById(R.id.getbtn);
receiver_msg =findViewById(R.id.textView5);
// create the get Intent object
Intent intent = getIntent();
String str = intent.getStringExtra("dr_name");
// display the string into textView
receiver_msg.setText(str);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(Appo.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet = findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt = eText.getText().toString();
tvw.setText(txt);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result ="";
if (android.isChecked()) {
result += "\n9:00 - 10:30";
}
if (angular.isChecked()) {
result += "\n10:30 -11:30";
}
if (java.isChecked()) {
result += "\n11:30 -12:30";
}
if (python.isChecked()) {
result += "\n2:00 - 3:00";
}
text.setText(result);
}
});
confirm = findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = text.getText().toString();
String date = tvw.getText().toString();
if (str.equals("")) {
Toast.makeText(Appo.this, "Blank values", Toast.LENGTH_SHORT).show();
} else {
boolean booking = myDB.insertData2(str, time, date);
if (booking) {
Toast.makeText(Appo.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Appo.this, "Booking not confirmed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox:
str = checked?"9:00 - 10:30 Selected":"9:00 - 10:30 Deselected";
break;
case R.id.checkBox1:
str = checked?"10:30 -11:30 Selected":"10:30 -11:30 Deselected";
break;
case R.id.checkBox2:
str = checked?"11:30 -12:30 Selected":"11:30 -12:30 Deselected";
break;
case R.id.checkBox3:
str = checked?"2:00 - 3:00 Selected":"2:00 - 3:00 Deselected";
break;
}
Toast.makeText(Appo.this, str, Toast.LENGTH_SHORT).show();
}
}
This is the code for sqlite database... that is DBHelper.java
package com.example.medilyf;
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;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
public static final String col1="name";
public static final String col2="username";
public static final String col3="email";
public static final String col4="PhoneNo";
public static final String col5="password";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String col6="Appointment_id ";
public static final String col7="full_Name ";
public static final String col9="Doc_name ";
public static final String col12="ATime ";
public static final String col8="Phone_Number";
public DBHelper(#Nullable Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(name Text, username Text primary key, email Text, PhoneNo Text, password Text)");
myDB.execSQL("create table appo(Dr Text,time Text, date Text)");
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
myDB.execSQL("Drop Table if exists users");
myDB.execSQL("Drop Table if exists appo");
}
public boolean insertData(String name, String username, String email, String PhoneNo, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1,name);
contentValues.put(col2,username);
contentValues.put(col3,email);
contentValues.put(col4,PhoneNo);
contentValues.put(col5,password);
long result = myDB.insert("users",null,contentValues);
return result != -1;
}
public boolean insertData2(String Dr, String time, String date){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Dr",Dr);
contentValues.put("time",time);
contentValues.put("date",date);
long result = myDB.insert("appo",null,contentValues);
return result != -1;
}
public boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?", new String[] {username});
return cursor.getCount() > 0;
}
public boolean checkusernamepassword(String username, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?", new String[] {username,password});
return cursor.getCount() > 0;
}
}
Can anyone help me with the code to retrieve and display the records of the appointment for another activity in list view..???

Nullpointerexception when trying to insert a value into SQLite

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.

Android Studio project

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/

How to get the list item name from a listview to a textview in another activity?

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.

Trying to create a simple clock (ish) app in java - can't seem to do so

So... I'm building a little app that stores a time value when the user sets one from the TimePicker buttons. Since the android TimePicker has two values currentHour and currentMinute I figure I need to create two strings (one for the hour one for the minute) then concatonate them into a single string which can be displayed as a time value.
Pretty simple, right?
As of now I've come up with the source below - and I feel like I almost have the TimePicker connected to the string for the time value however I have 3 issues:
timePicker cannot be resolved AddEditCountry.java line 104
minEdit cannot be resolved or is not a field AddEditCountry.java line 37
timePicker cannot be resolved AddEditCountry.java line 103
...not to mention the TimePicker buttons don't change the (combined currentHour and currentMinute) string.
^ - The BIG problem
AddEditCountry.java
import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TimePicker;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TimePicker minEt;
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
minEt = (TimePicker) findViewById(R.id.minEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
timeEt.setCurrentHour(extras.containsKey(KEY_BUNDLE_TIME) ? extras.getInt(KEY_BUNDLE_TIME) : 0);
minEt.setCurrentMinute(extras.getInt("min"));
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString(),
minEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
timePicker.getCurrentHour().toString(),
timePicker.getCurrentMinute().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString(),
minEt.getCurrentMinute().toString(),/* Storing as String*/
codeEt.getText().toString());
}
}
}
DatabaseConnector.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}
public void insertContact(String name, String cap, String code, String time, String min)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("time", time);
newCon.put("min", min);
newCon.put("code", code);
newCon.put(AddEditCountry.KEY_BUNDLE_TIME, time);
newCon.put(AddEditCountry.KEY_BUNDLE_MIN, min);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String cap,String code, String time, String min)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("time", time);
editCon.put("min", min);
editCon.put("code", code);
editCon.put(AddEditCountry.KEY_BUNDLE_TIME, time);
editCon.put(AddEditCountry.KEY_BUNDLE_MIN, min);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id", "name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null, null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
There are quite a few issues in the code.
First, you don't need separate TimePicker widgets for hour and minute. So remove minEt from your code as well as from layout file.
Second, timePicker variable is not declared in the class. Use timeEt instead.
Third, i couldn't find minEdit variable in the class and if its declared in the layout then the compiler shouldn't complain. Anyways remove it as you don't need it.
You may want to take a look at a working example of using TimePicker. Check this out.
Sample Activity:
public class TimePickerActivity extends Activity {
public static final int DIALOG_TIME = 100;
private TextView timeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
timeText = new TextView(this);
setContentView(timeText);
}
#Override
protected void onResume() {
super.onResume();
showDialog(DIALOG_TIME);
}
#Override
protected Dialog onCreateDialog(final int id) {
switch(id) {
case DIALOG_TIME:
Calendar cal = Calendar.getInstance();
TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
timeText.setText(hourOfDay+":"+minute);
}
};
return new TimePickerDialog(this, mTimeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), true);
}
return super.onCreateDialog(id);
}
}

Categories