Android crashes to previous screen debug in the post - java

I was adding a list view to my database when in the end the database list view windows opens and crashes
Do you have any idea what this crash code mean? I can add code later if you need it
(Edit still no luck finding anything that could throw this command)
Can you check with a command any way?
Database form:
package com.example.laivumusis;
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 com.example.laivumusis.KlausimuContracts.*;
import java.util.ArrayList;
import java.util.List;
public class KlausimynoDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Klausimynas.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public KlausimynoDatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
KlausimuLentele.TABLE_NAME + " ( " +
KlausimuLentele._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KlausimuLentele.COLUMN_QUESTION + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION1 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION2 + " TEXT, " +
KlausimuLentele.COLLUMN_OPTION3 + " TEXT, " +
KlausimuLentele.COLLUMN_ANSWER_NR + " INTEGER" +
")";
db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
fillKlausimuLentele();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + KlausimuLentele.TABLE_NAME);
onCreate(db);
}
public boolean addData (String pasirinkimas1){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KlausimuLentele.COLLUMN_OPTION1, pasirinkimas1);
long result = db.insert(KlausimuLentele.TABLE_NAME, null, contentValues);
if (result == -1){
return false;
}else{
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME,null );
return data;
}
private void fillKlausimuLentele() {
Klausimai q1 = new Klausimai("Kelintais metais buvo išleista java proogramavimo kalba?", "1991", "1995", "1989", 1);
addQuestion(q1);
Klausimai q2 = new Klausimai("Ar destytojas pasigailės mūsų?", "Priklauso nuo darbo", "Priklauso nuo pingų", "Prklauso nuo nuotaikos", 1);
addQuestion(q2);
Klausimai q3 = new Klausimai("Kai sunervina žaidimas koks geriausias būdas iš jo išeiti?", "Alt+F4", "Quit To desktop", "Ištraukti maitinimo laida",1);
addQuestion(q3);
Klausimai q4 = new Klausimai("A is correct again", "A", "B", "C", 1);
addQuestion(q4);
Klausimai q5 = new Klausimai("B is correct agian", "A", "B", "C", 2);
addQuestion(q5);
}
private void addQuestion(Klausimai klausimai) {
ContentValues cv = new ContentValues();
cv.put(KlausimuLentele.COLUMN_QUESTION, klausimai.getKlausimas());
cv.put(KlausimuLentele.COLLUMN_OPTION1, klausimai.getPasirinkimas1());
cv.put(KlausimuLentele.COLLUMN_OPTION2, klausimai.getPasirinkimas2());
cv.put(KlausimuLentele.COLLUMN_OPTION3, klausimai.getPasirinkimas3());
cv.put(KlausimuLentele.COLLUMN_ANSWER_NR, klausimai.getAtsakymoNr());
db.insert(KlausimuLentele.TABLE_NAME, null, cv);
}
public List<Klausimai> getAllQuestions() {
List<Klausimai> klausimuSarasas = new ArrayList<>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + KlausimuLentele.TABLE_NAME, null);
if (c.moveToFirst()) {
do {
Klausimai klausimai = new Klausimai();
klausimai.setKlausimas(c.getString(c.getColumnIndex(KlausimuLentele.COLUMN_QUESTION)));
klausimai.setPasirinkimas1(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION1)));
klausimai.setPasirinkimas2(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION2)));
klausimai.setPasirinkimas3(c.getString(c.getColumnIndex(KlausimuLentele.COLLUMN_OPTION3)));
klausimai.setAtsakymoNr(c.getInt(c.getColumnIndex(KlausimuLentele.COLLUMN_ANSWER_NR)));
klausimuSarasas.add(klausimai);
} while (c.moveToNext());
}
c.close();
return klausimuSarasas;
}
}
But i think the problem is in here because this is the form which crashes:
package com.example.laivumusis;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ViewListData extends AppCompatActivity {
KlausimynoDatabaseHelper myDB;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editlistview_layout);
ListView listView = (ListView) findViewById(R.id.listView);
myDB = new KlausimynoDatabaseHelper(this);
ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getListContents();
if (data.getCount() == 0) {
Toast.makeText(ViewListData.this,"Database tuščias!",Toast.LENGTH_LONG).show();
}else{
while (data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}
Debug:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.laivumusis, PID: 3859
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

Your object seems to be null while converting to string. use the following to check if null:
if (obj !=null){
//store in database
}

Related

Android Studio, Databasehelper Class not working for some reason

Alright, So. I've been trying for the last couple of hours to display a database on a list view widget in android studio. I used this exact code in another project and it worked find, but now that I am trying to integrate it into this one, the app continuously crashes when ever I try to pull from the database. this includes the getLight Method and the getAllLight Method. I am at a complete lost here. Again, this code worked, idk why i am getting an error now. is there something wrong with my methods? is there something I can try?
package com.studios.primitive.safealwayz.ui.main.Light;
import com.studios.primitive.safealwayz.ui.main.Account.AccountModel;
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;
import java.util.List;
public class LightDatabaseHelper extends SQLiteOpenHelper {
public static final String LIGHTS = "LIGHTS";
public static final String COLUMN_LIGHTID = "LIGHTID";
public static final String COLUMN_USERNAME = "USERNAME";
public static final String COLUMN_LOCATION = "LOCATION";
public static final String COLUMN_STATUS = "STATUS";
public LightDatabaseHelper(#Nullable Context context) {
super(context, "lights.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + LIGHTS + " (" + COLUMN_LIGHTID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_USERNAME + " TEXT, " + COLUMN_LOCATION + " TEXT, " + COLUMN_STATUS + " BOOL)";
db.execSQL(createTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addLight(LightModel light, AccountModel accountModel) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_USERNAME, accountModel.getUserName());
cv.put(COLUMN_LOCATION, light.getLocation());
cv.put(COLUMN_STATUS, light.isActive());
long insert = db.insert(LIGHTS, null, cv);
return insert != -1;
}
public void changeLightStatus(LightModel light){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_LIGHTID, light.getLightID());
cv.put(COLUMN_LOCATION,light.getLocation());
cv.put(COLUMN_USERNAME, light.getUsername());
cv.put(COLUMN_STATUS, light.isActive());
db.update(LIGHTS, cv, COLUMN_LIGHTID + " = ?", new String[] { String.valueOf(light.getLightID())});
}
public List<LightModel> getAllLights(AccountModel account){
List<LightModel> rtnList = new ArrayList<>();
String queryCommand = "SELECT * FROM " + LIGHTS +" WHERE " + COLUMN_USERNAME + " = " + "'"+account.getUserName()+"'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryCommand,null);
if(cursor.moveToFirst()){
do{
int LightID = cursor.getInt(0);
String username = cursor.getString(1);
String lightLocation = cursor.getString(2);
boolean lightStatus = cursor.getInt(3) == 1;
LightModel newLight = new LightModel(lightLocation, account);
newLight.setActive(lightStatus);
newLight.setLightID(LightID);
rtnList.add(newLight);
}while(cursor.moveToNext());
}else{
//returns an empty list
}
cursor.close();
db.close();
return rtnList;
}
public LightModel getLight(String id, String user){
LightModel light = new LightModel(user);
SQLiteDatabase db = this.getReadableDatabase();
String queryCommand = "SELECT * FROM " + LIGHTS + " WHERE "+ COLUMN_LIGHTID + " = "+ "'" + id +"'";
Cursor cursor = db.rawQuery(queryCommand,null);
if(cursor.moveToFirst()){
do{
int LightID = cursor.getInt(0);
String username = cursor.getString(1);
String location = cursor.getString(2);
boolean status = cursor.getInt(3) == 1? true: false;
light.setLightID(LightID);
light.setUsername(username);
light.setLocation(location);
light.setActive(status);
}while(cursor.moveToNext());
}else{
//returns an empty list
}
cursor.close();
db.close();
return light;
}
}
Here is the Activity Class
package com.studios.primitive.safealwayz;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.studios.primitive.safealwayz.ui.main.Account.AccountModel;
import com.studios.primitive.safealwayz.ui.main.Light.LightDatabaseHelper;
import com.studios.primitive.safealwayz.ui.main.Light.LightModel;
import java.util.List;
public class AccountLightActivity extends AppCompatActivity {
Button turn;
ListView listV;
EditText lightID;
ArrayAdapter<LightModel> lightArrayAdapter;
LightDatabaseHelper lightDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_light);
final AccountModel model = (AccountModel) getIntent().getSerializableExtra("obj");
turn = (Button) findViewById(R.id.turn_light);
listV = (ListView) findViewById(R.id.list_view);
lightID = (EditText) findViewById(R.id.light_id_input);
/*
lightArrayAdapter = new ArrayAdapter<LightModel>(AccountLightActivity.this, android.R.layout.simple_list_item_1,lightDatabaseHelper.getAllLights(model));
listV.setAdapter(lightArrayAdapter);
*/
turn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String lightInput = lightID.getText().toString();
Toast.makeText(AccountLightActivity.this, model.getUserName(), Toast.LENGTH_SHORT).show();
LightModel li = lightDatabaseHelper.getLight(lightInput, model.getUserName());
Toast.makeText(AccountLightActivity.this, li.toString(), Toast.LENGTH_SHORT).show();
/*
if (lightInput.isEmpty()) {
Toast.makeText(AccountLightActivity.this, "Please Choose a LightID", Toast.LENGTH_SHORT).show();
}else{
LightModel li = lightDatabaseHelper.getLight(lightInput, model.getUserName());
if(li.isActive()){
li.setActive(false);
}else{
li.setActive(true);
}
lightDatabaseHelper.changeLightStatus(li);
Toast.makeText(AccountLightActivity.this, li.toString() , Toast.LENGTH_SHORT).show();
lightArrayAdapter = new ArrayAdapter<LightModel>(AccountLightActivity.this, android.R.layout.simple_list_item_1,lightDatabaseHelper.getAllLights(model));
listV.setAdapter(lightArrayAdapter);
}
*/
}
});
}
}
and finally, here is the error I've been getting.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.studios.primitive.safealwayz, PID: 2269
java.lang.NullPointerException
at com.studios.primitive.safealwayz.AccountLightActivity$1.onClick(AccountLightActivity.java:53)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

Application keeps crashing when trying to save appointment information?

I'm building an application for a barber shop and im on a part now where I am creating an appointment and saving the data from that appointment, however when I go to click add to create the appointment, the application crashes and I left with this error;
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 2 rows, 3 columns.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ie.app.barbershop, PID: 31270
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at ie.app.barbershop.TableControllerAppointments.read(TableControllerAppointments.java:46)
at ie.app.barbershop.Landing.readRecords(Landing.java:47)
at ie.app.barbershop.OnClickListenerCreateAppointment$1.onClick(OnClickListenerCreateAppointment.java:38)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I/Process: Sending signal. PID: 31270 SIG: 9
Application terminated.
Here is my class for TableControllerAppointments.java
package ie.app.barbershop;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class TableControllerAppointments extends DatabaseHandler {
public TableControllerAppointments(Context context) {
super(context);
}
public boolean create(ObjectAppointment objectAppointments) {
ContentValues values = new ContentValues();
values.put("fullname", objectAppointments.fullName);
values.put("contactno", objectAppointments.contactNumber);
SQLiteDatabase db = this.getWritableDatabase();
boolean createSuccessful = db.insert("appointments", null, values) > 0;
db.close();
return createSuccessful;
}
public List<ObjectAppointment> read() {
List<ObjectAppointment> recordsList = new ArrayList<>();
String sql = "SELECT * FROM Appointments ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
int contactNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex("contactno")));
ObjectAppointment objectAppointment = new ObjectAppointment();
objectAppointment.fullName = fullName;
objectAppointment.contactNumber = contactNumber;
recordsList.add(objectAppointment);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return recordsList;
}
public int count() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "SELECT * FROM appointments";
int recordCount = db.rawQuery(sql, null).getCount();
db.close();
return recordCount;
}
}
And here is my class for OnClickListenerCreateAppointment.java
package ie.app.barbershop;
import android.view.View;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class OnClickListenerCreateAppointment implements View.OnClickListener {
public ObjectAppointment objectAppointment;
#Override
public void onClick(View view){
final Context context = view.getRootView().getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.appointment_input_form, null, false);
final EditText editTextFullName = formElementsView.findViewById(R.id.editTextFullName);
final EditText editTextContactNumber = formElementsView.findViewById(R.id.editTextContactNumber);
ObjectAppointment objectAppointment = new ObjectAppointment();
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Create Appointment")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String fullname = editTextFullName.getText().toString();
String contactno = editTextContactNumber.getText().toString();
((Landing) context).countRecords();
((Landing) context).readRecords();
dialog.cancel();
}
}).show();
boolean createSuccessful = new TableControllerAppointments(context).create(objectAppointment);
if(createSuccessful){
Toast.makeText(context, "Appointment Information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save appointment information", Toast.LENGTH_SHORT).show();
}
}
}
and this is my Landing.java class
package ie.app.barbershop;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.List;
public class Landing extends AppCompatActivity{
public Button buttonProducts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_landing);
countRecords();
buttonProducts = findViewById(R.id.buttonProducts);
Button buttonCreateAppointment = findViewById(R.id.buttonCreateAppointment);
buttonCreateAppointment.setOnClickListener(new OnClickListenerCreateAppointment());
buttonProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Landing.this, Products.class));
}
});
}
public void readRecords() {
LinearLayout linearLayoutRecords = findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<ObjectAppointment> appointments = new TableControllerAppointments(this).read();
if (appointments.size() > 0) {
for (ObjectAppointment obj : appointments) {
String fullName = obj.fullName;
int contactNumber = obj.contactNumber;
String textViewContents = fullName + " - " + contactNumber;
TextView textViewAppointmentItem= new TextView(this);
textViewAppointmentItem.setPadding(0, 10, 0, 10);
textViewAppointmentItem.setText(textViewContents);
textViewAppointmentItem.setTag(Integer.toString(contactNumber));
linearLayoutRecords.addView(textViewAppointmentItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
public void countRecords(){
int recordCount = new TableControllerAppointments(this).count();
TextView textViewRecordCount = findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
}
Database Handler Class
package ie.app.barbershop;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS students";
db.execSQL(sql);
onCreate(db);
}
}
The -1 is being returned from getColumnIndex meaning that the column firstname
doesn't exist in the cursor in the following line.
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
You create the table using :-
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
Where the columns are id fullname and contactno.
--
Fix
To fix this change to use :-
String fullName = cursor.getString(cursor.getColumnIndex("fullname"));
Additional
Better still define column and tables names as constants and always refer to them.
e.g.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public static final String TABLE_NAME = "appointments";
public static final String COL_ID = "id";
public static final String COl_FULLNAME = "fullname";
public static final String COL_CONTACTNO = "contactno";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME +
"( " + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_FULLNAME + " TEXT, " +
COL_CONTACTNO + " NUMBER ) ";
db.execSQL(sql);
}
.... and so on
and later as one example :-
String fullName = cursor.getString(cursor.getColumnIndex(DatabaseHandler.COL_FULLNAME));

SQLiteDatabase: Get column and store into an array

Is there a way to grab a column from the database created, and store the
values found in the column into an array?
My main goal, is to get values in from a column, and store them into a spinner.
Look below for code!
PatientDbHelper.java
package tanav.sharma;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tanav on 11/4/2016.
*/
public class PatientDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "PATIENTINFO.db";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY = "CREATE TABLE "
+ PatientInfo.NewPatientInfo.TABLE_NAME + " ("
+ PatientInfo.NewPatientInfo.PATIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PatientInfo.NewPatientInfo.PATIENT_FNAME+ " TEXT,"
+ PatientInfo.NewPatientInfo.PATIENT_LNAME+" TEXT,"
+ PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT+" TEXT);";
private static final String CREATE_QUERY_TEST =
"CREATE TABLE "
+ TestInfo.NewTestInfo.TABLE_TEST_NAME + " ("
+ TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE + " TEXT,"
+ TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL + " TEXT,"
+ TestInfo.NewTestInfo.TEST_RESPITORY_RATE +" TEXT,"
+ TestInfo.NewTestInfo.TEST_HEART_RATE +" TEXT);";
public PatientDbHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS","Database created / opened ...");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
db.execSQL(CREATE_QUERY_TEST);
Log.e("DATABASE OPERATIONS","Table created...");
}
public void addInformations(int id, String fname, String lname, String department, SQLiteDatabase db){
ContentValues contentValues = new ContentValues();
if ( id != 0 ){ contentValues.put(PatientInfo.NewPatientInfo.PATIENT_ID, id); }
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_FNAME,fname);
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_LNAME,lname);
contentValues.put(PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT,department);
db.insert(PatientInfo.NewPatientInfo.TABLE_NAME, null,contentValues);
Log.e("DATABASE OPERATIONS","One in row inserted...");
}
public void addTestInformation(/*String BP*/ int BL, int RR, int HR, SQLiteDatabase db){
ContentValues contentTestValues = new ContentValues();
//contentTestValues.put(TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE, BP);
contentTestValues.put(TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL,BL);
contentTestValues.put(TestInfo.NewTestInfo.TEST_RESPITORY_RATE, RR);
contentTestValues.put(TestInfo.NewTestInfo.TEST_HEART_RATE, HR);
db.insert(TestInfo.NewTestInfo.TABLE_TEST_NAME, null, contentTestValues);
Log.e("DATABASE OPERATIONS", "One in row inserted...");
}
/* public Cursor getPatientDepartment(String departments, SQLiteDatabase sqLiteDatabase){
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_LNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
String selection = PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT+ " LIKE ?";
String[] selection_args = {departments};
Cursor cursor = sqLiteDatabase.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}*/
public Cursor getPatientsId(int patient_id,SQLiteDatabase sqLiteDatabase){
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_ID, PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
String selection = PatientInfo.NewPatientInfo.PATIENT_ID+ " LIKE ?";
String convert = String.valueOf(patient_id);
String[] selection_args = {convert};
Cursor cursor = sqLiteDatabase.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {PatientInfo.NewPatientInfo.PATIENT_FNAME, PatientInfo.NewPatientInfo.PATIENT_LNAME, PatientInfo.NewPatientInfo.PATIENT_DEPARTMENT};
cursor = db.query(PatientInfo.NewPatientInfo.TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
public Cursor getTestInformation(SQLiteDatabase db){
Cursor cursorTest;
String[] testProjections = {TestInfo.NewTestInfo.TEST_HEART_RATE, TestInfo.NewTestInfo.TEST_RESPITORY_RATE, TestInfo.NewTestInfo.TEST_BLOOD_OXYGEN_LEVEL, TestInfo.NewTestInfo.TEST_BlOOD_PRESSURE};
cursorTest = db.query(TestInfo.NewTestInfo.TABLE_TEST_NAME,testProjections,null,null,null,null,null);
return cursorTest;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Above is my Database handler class, I want to grab the column PATIENT_FNAME and store all those values into an Array. Then Later on, in my AddTest.java file, i want to display these values into an spinner.
Below is my AddTest.java
package tanav.sharma;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddTest extends AppCompatActivity {
private RadioGroup radioGroup;
private RadioButton radioButton;
EditText etBL, etRR, etHBR;
Spinner patients;
Context context;
PatientDbHelper patientDbHelper;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_test);
getSupportActionBar().setTitle(R.string.add_test);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etBL = (EditText) findViewById(R.id.etBOL);
etRR = (EditText) findViewById(R.id.etRR);
etHBR = (EditText) findViewById(R.id.etHBR);
patients = (Spinner) findViewById(R.id.spinner);
}
public void addTest(View view){
radioGroup = (RadioGroup) findViewById(R.id.radio);
Button addTest = (Button) findViewById(R.id.addTest);
addTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(selectedId);
}
});
//String BP = radioButton.getText().toString();
int BL = Integer.parseInt(etBL.getText().toString());
int RR = Integer.parseInt(etRR.getText().toString());
int HR = Integer.parseInt(etHBR.getText().toString());
patientDbHelper = new PatientDbHelper(this);
sqLiteDatabase = patientDbHelper.getWritableDatabase();
patientDbHelper.addTestInformation(BL,RR,HR,sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_LONG).show();
patientDbHelper.close();
}
}
You can do something like
List<String> names = new ArrayList<>();
Cursor cursor = patientDbHelper.getInformations(sqLiteDatabase);
if (cursor != null){
while(cursor.moveToNext()){
names.add(cursor.getString(cursor.getColumnIndex(PatientInfo.NewPatientInfo.PATIENT_FNAME)));
}
cursor.close();
}

Android Deleting Row from SQLITE

I'm currently having trouble deleting one row when user long presses on an item in listview. I am able to only delete one row at a time which is what I want, but when I delete the first few items it is successful and when I attempt to delete an item with a later id. The id does not get deleted and stays. I need help to consistently delete items when ever an item is to be deleted. Thanks.
this is my database helper class
package com.example.health.adapter;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.health.dao.ExerciseDAO;
import com.example.health.dao.RecipeDAO;
import java.util.ArrayList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "HealthDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE recipe ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, " +
"description TEXT )";
db.execSQL(CREATE_RECIPE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS recipe");
this.onCreate(db);
}
//START OF CRUD FOR RECIPE
private static final String TABLE_RECIPE = "recipe";
//column names
private static final String KEY_RID = "id";
private static final String KEY_RTITLE = "title";
private static final String KEY_RDESCRIPTION = "description";
private static final String[] RCOLUMNS = {KEY_RID,KEY_RTITLE,KEY_RDESCRIPTION};
public void addRecipe(RecipeDAO r) {
Log.d("addRecipe", r.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RTITLE, r.getTitle());
values.put(KEY_RDESCRIPTION, r.getDescription());
db.insert(TABLE_RECIPE, null, values);
Log.d("Data Added", r.toString());
db.close();
}
public RecipeDAO getRecipe(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.query(TABLE_RECIPE, // a. table
RCOLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null);
if (cursor != null)
cursor.moveToFirst();
RecipeDAO r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
Log.d("getRecipe("+id+")", r.toString());
return r;
}
public List<RecipeDAO> getAllRecipe() {
List<RecipeDAO> recipe = new ArrayList<RecipeDAO>();
String query = "SELECT * FROM " + TABLE_RECIPE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
RecipeDAO r = null;
if (cursor.moveToFirst()) {
do {
r = new RecipeDAO();
r.setRecipeID(Integer.parseInt(cursor.getString(0)));
r.setTitle(cursor.getString(1));
r.setDescription(cursor.getString(2));
recipe.add(r);
} while (cursor.moveToNext());
}
Log.d("getAllRecipe()", recipe.toString());
return recipe;
}
public int updateRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", r.getTitle());
values.put("description", r.getDescription());
int i = db.update(TABLE_RECIPE, //table
values, // column/value
KEY_RID+" = ?", // selections
new String[] { String.valueOf(r.getRecipeID()) });
db.close();
return i;
}
public void deleteAllRecipe() {
RecipeDAO r = new RecipeDAO();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE,null,null);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_RECIPE + "'");
db.close();
Log.d("deleteRecipe", r.toString());
}
/*
public void deleteRecipe(RecipeDAO r) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECIPE, KEY_RID+ " = ? ", new String[] { String.valueOf(r.getRecipeID()) });
db.close();
}*/
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + "=" + id, null) > 0;
}
//END OF CRUD FOR RECIPE
}
Class for database CRUD operations
package com.example.health.recipe;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.health.adapter.MySQLiteHelper;
import com.example.health.dao.RecipeDAO;
import com.example.health.healthplanner.R;
import java.util.List;
public class Recipes extends Fragment {
MySQLiteHelper db;
Button deleteButton;
ListView lv;
List<RecipeDAO> data;
RecipeDAO r = new RecipeDAO();
public Recipes() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.recipe_fragment, container, false);
db = new MySQLiteHelper(getActivity());
/*
db.addRecipe(new RecipeDAO("Windows", "Bill Gates"));//hardcode test
db.addRecipe(new RecipeDAO("IOS", "Steve Jobs"));//same
db.addRecipe(new RecipeDAO("Android", "Andy Rubin"));//same*/
data = db.getAllRecipe();
final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, data);
lv = (ListView) v.findViewById(R.id.listView2);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
deleteButton = (Button) v.findViewById(R.id.deletebutton);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Delete");
alertDialog.setMessage("Are you sure you want to delete all data?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.deleteAllRecipe();
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), "All data delete", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setNegativeButton("No", null);
alertDialog.show();
/* data = db.getAllRecipe();
for(RecipeDAO re : data) { testing to see if data is in database
String log = "Id: " + re.getRecipeID() + ", Title: " + re.getTitle();
Log.d("Data", log);
}*/
}
});
return v;
}
}
try this
public void delete(String name) {
db.delete(your_table_name, "name= ?", new String[] { name });
}
Please revise this method,
//change code in setOnItemLongClickListener
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
data.remove(position);
db.deleteRecipe(id + 1);
data = db.getAllRecipe();
adapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, data);
//and call change adapter in listview
adapter.notifyDataSetChanged();
return false;
// db.deleteRecipeRow(r.getRecipeID());
//Toast.makeText(getActivity(),"ID = " + r.getRecipeID(), Toast.LENGTH_LONG).show();
}
});
//this method for delete in sqlite database
public boolean deleteRecipe(long id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_RECIPE, KEY_RID + " =?" , new String[]{id}) > 0;
}

Android SQLite problems, how to display data

Hi guys I'm currently creating an Android Application on Eclipse through various online tutorials. I have got as far as creating a SQLite database and being able to manually input information - although I'm not quite sure how to delete the information yet. What I would like is for the user to click a button and then it will display the information that they have inputted on a profile page - at the moment it is only two fields. I have spent hours going through various tutorials and research and just can not seem to get it to work. If anybody has the time to have a look through my code and tell me how I should call the methods to add new data via a button then it would be greatly appreciated. I think I am loosing my mind. I also understand I may not have gone around the correct way of setting things up but I am still learning.
Here is my DatabaseHandler.java file
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_EMAIL, contact.getEmail()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setEmail(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_EMAIL, contact.getEmail());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And below is my page that so far just sends forced information to the database as you will see.
package com.example.myapp;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class Addrecord extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Dan", "dljbrown#icloud.com"));
db.addContact(new Contact("Pash", "pashj#hotmail.com"));
db.addContact(new Contact("Nigel", "Dancinboyforever#hotmail.com"));
db.addContact(new Contact("Jit", "Jit#hotmail.com"));
// Log.d("Delete: ", "Deleting..");
// db.deleteContact(new Contact("Dan", "dljbrown#icloud.com"));
// db.deleteContact(new Contact("Pash", "pashj#hotmail.com"));
// db.deleteContact(new Contact("Nigel",
// "Dancinboyforever#hotmail.com"));
// db.deleteContact(new Contact("Jit", "dljbrown#icloud.com"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: " + cn.getID() + " ,Name: " + cn.getName()
+ " ,Email: " + cn.getEmail();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
So instead of the information being passed straight to the database and displayed in the log like below I would like the user to of pressed a button from a previous page and I will display their information.
Thanks if anybody gets round to replying!!
Here is the activity that I currently link to the "Addrecord" activity, once "Page1" in the list view has been clicked then I would like it to display the users information (Sample info at the moment)
package com.example.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Home extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
populateListView();
registerClickCallback();
}
public void populateListView() {
String[] homelist = { "Page1", "Page2", "Page3", "Page4", "Page5" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_home, homelist);
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setAdapter(adapter);
}
public void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.testhomelist);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// NOW COPY AND PASTE FOR ALL THE OTHERS
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
if (position == 0) {
Intent myintent = new Intent(getApplicationContext(),
Addrecord.class);
startActivity(myintent);
}
if (position == 1) {
Intent myintent2 = new Intent(getApplicationContext(),
Pagetwo.class);
startActivity(myintent2);
}
if (position == 2) {
Intent myintent3 = new Intent(getApplicationContext(),
Pagethree.class);
startActivity(myintent3);
}
if (position == 3) {
Intent myintent4 = new Intent(getApplicationContext(),
Pagefour.class);
startActivity(myintent4);
}
if (position == 4) {
Intent myintent5 = new Intent(getApplicationContext(),
Pagefive.class);
startActivity(myintent5);
}
if (position == 5) {
Intent myintent6 = new Intent(getApplicationContext(),
Pagesix.class);
startActivity(myintent6);
}
}
});
}

Categories

Resources