How do I call variable form outside DbHandler? - java

In my case I have DbHandler.java,and ActivityKategori.java.
My problem is at DbHandler.java, I have query condition
SELECT * FROM TBL_**** WHERE COLUMN1 = 'VARIABEL_FROM_ACT_KATEGORI' "
and that is variable value is from bundle :D
I already make full of changes but nothing solved.
Here's the full code
ActivityKategori.java
This activity is get data from bundle and send it value to DBHandler to get sql CONDITION.
I know someone will suggest to using SharedPreference but im confused about it.
Right now, I want to learn passing using Bundle or Intents
package ptacs.ekatalog.com.e_katalogproduk.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import ptacs.ekatalog.com.e_katalogproduk.R;
import ptacs.ekatalog.com.e_katalogproduk.adapter.KategoriAdapter;
import ptacs.ekatalog.com.e_katalogproduk.helper.Constant;
import ptacs.ekatalog.com.e_katalogproduk.helper.DBHandler;
import ptacs.ekatalog.com.e_katalogproduk.helper.RecyclerItemClickListener;
import ptacs.ekatalog.com.e_katalogproduk.model.Produk;
public class ActivityKategori extends AppCompatActivity {
private SwipeRefreshLayout swLayout2;
private LinearLayout llayout2;
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private KategoriAdapter adapter;
private DBHandler dbHandler;
private List<Produk> kategoriList = new ArrayList<>();
private TextView tv1;
String mMerkProduk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kategori);
initRecyclerView();
cekDataRecyclerView();
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
mMerkProduk = bundle.getString(Constant.BUNDLE_MERK_PRODUK); //MERK kategori
//Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(mMerkProduk);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
dbHandler = new DBHandler(this);
}
//dbHandler.getKategoryProduk(mMerkProduk);
}
private void initRecyclerView(){
recyclerView = (RecyclerView) findViewById(R.id.rv_kategori);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
dbHandler = new DBHandler(ActivityKategori.this);
kategoriList = dbHandler.getKategoryProduk(mMerkProduk); //GET VALUE STRING
//kategoriList = dbHandler.getKategoryProduk(); //OLD CODE to GET OBJECT
adapter = new KategoriAdapter(kategoriList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void cekDataRecyclerView() {
if (adapter.getItemCount() == 0) {
recyclerView.setVisibility(View.GONE);
} else {
recyclerView.setVisibility(View.VISIBLE);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Handle item click
Bundle bundle = new Bundle();
//COMMIT MAS INDRA CS
bundle.putString(Constant.BUNDLE_JENIS_PRODUK, adapter.getItem(position).getJenis_produk());
Intent intent = new Intent(ActivityKategori.this, ActivityList.class);
intent.putExtras(bundle);
startActivity(intent);
}
})
);
}
swLayout2 = (SwipeRefreshLayout) findViewById(R.id.sw_layout2);
llayout2 = (LinearLayout) findViewById(R.id.ll_Layout);
//Mengeset warna yang berputar
swLayout2.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary);
//Setting Listener yang akan dijalankan saat layar difresh
swLayout2.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshItem();
}
void refreshItem(){
initRecyclerView();
cekDataRecyclerView();
onItemLoad();
}
void onItemLoad(){
swLayout2.setRefreshing(false);
}
});
}
}
ActivityKategori.java
package ptacs.ekatalog.com.e_katalogproduk.helper;
/**
* Created by Maxoto on 1/15/2018.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
import ptacs.ekatalog.com.e_katalogproduk.model.Produk;
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "db_ekatalog"; // NAMA DATABASE
private static final String TABLE_PRODUK = "tb_produk"; // NAMA TABEL
private static final String COLUMN_ID = "id_produk"; // NAMA KOLOM ID
private static final String COLUMN_KD = "kd_produk"; // KODE PRODUK
private static final String COLUMN_NAMA = "nama_produk"; // NAMA KOLOM NAMA
private static final String COLUMN_MERK = "merk_produk"; //MERK PRODUK
private static final String COLUMN_JENIS = "jenis_produk"; //JENIS PRODUK
private static final String COLUMN_VARIASI = "variasi_produk"; //VARIASI PRODUK
private static final String COLUMN_FOTO = "foto_produk"; // FOTO PRODUK
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// TODO : LANJUT SECTION 2
// FUNGSI UNTUK MEMBUAT DATABASENYA
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USER_TABLE = "CREATE TABLE "
+ TABLE_PRODUK +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_KD + " TEXT,"
+ COLUMN_NAMA + " TEXT, "
+ COLUMN_MERK + " TEXT, "
+ COLUMN_JENIS + " TEXT, "
+ COLUMN_VARIASI + " TEXT, "
+ COLUMN_FOTO + " TEXT" + ")";
db.execSQL(CREATE_USER_TABLE);
}
// FUNGSI UNTUK MENGECEK DATABASE ADA ATAU TIDAK.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUK);
onCreate(db);
}
// FUNGSI UNTUK TAMBAH DATA PRODUK
public void tambahProduk(Produk produk){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_KD, produk.getKd_produk());
values.put(COLUMN_NAMA, produk.getNama_produk());
values.put(COLUMN_MERK, produk.getMerk_produk());
values.put(COLUMN_JENIS, produk.getJenis_produk());
values.put(COLUMN_VARIASI, produk.getVariasi_produk());
values.put(COLUMN_FOTO, produk.getFoto_produk());
db.insert(TABLE_PRODUK, null, values);
db.close();
}
// FUNGSI UNTUK AMBIL 1 DATA PRODUK
public Produk getProduk(int id_produk){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PRODUK, new String[]{COLUMN_ID, COLUMN_KD ,COLUMN_NAMA, COLUMN_MERK
,COLUMN_JENIS, COLUMN_VARIASI , COLUMN_FOTO },
COLUMN_ID + "=?", new String[]{String.valueOf(id_produk)}, null, null,null, null);
if (cursor != null)
cursor.moveToFirst();
Produk produk = new Produk(cursor.getString(1), cursor.getString(2),cursor.getString(3),
cursor.getString(4),cursor.getString(5),cursor.getString(6));
return produk;
}
// FUNGSI UNTUK AMBIL SEMUA DATA PRODUK
public List<Produk> getSemuaProduk(){
List<Produk> produkList = new ArrayList<>();
String selectQuery = " SELECT * FROM " + TABLE_PRODUK ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()){
do {
Produk produk = new Produk(cursor.getString(1), cursor.getString(2),cursor.getString(3),
cursor.getString(4),cursor.getString(5),cursor.getString(6));
produkList.add(produk);
} while (cursor.moveToNext());
}
return produkList;
}
// FUNGSI MENGHITUNG ADA BEBERAPA DATA
public int getProdukCount(){
String countQuery = "SELECT * FROM " + TABLE_PRODUK;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
// FUNGSI UPDATE DATA PRODUK
public int updateDataProduk(Produk produk) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_KD, produk.getKd_produk());
values.put(COLUMN_NAMA, produk.getNama_produk());
values.put(COLUMN_MERK, produk.getMerk_produk());
values.put(COLUMN_JENIS, produk.getJenis_produk());
values.put(COLUMN_VARIASI, produk.getVariasi_produk());
values.put(COLUMN_FOTO, produk.getFoto_produk());
return db.update(TABLE_PRODUK, values, COLUMN_ID + " = ?",
new String[]{String.valueOf(produk.getId())});
}
// FUNGSI HAPUS DATA 1 PRODUK
public void hapusDataProduk(Produk produk) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PRODUK, COLUMN_ID + " = ?",
new String[]{String.valueOf(produk.getId())});
db.close();
}
// FUNGSI UNTUK MENGHAPUS SEMUA DATA PRODUK
public void hapusSemuaDataProduk(){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PRODUK);
}
//FUNGSI MENGAMBIL DATA WHERE DI ACTIVITY KATEGORY
public List<Produk> getKategoryProduk(String mMerkProduk) {
List<Produk> kategoriList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_PRODUK + " WHERE " + COLUMN_MERK + " =? " ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery,new String[]{ mMerkProduk } );
if (cursor.moveToFirst()) {
do {
Produk kategori = new Produk(cursor.getString(1), cursor.getString(2), cursor.getString(3),
cursor.getString(4), cursor.getString(5), cursor.getString(6));
kategoriList.add(kategori);
} while (cursor.moveToNext());
}
return kategoriList;
}
}
Here's the error:
01-29 14:10:25.342 370-370/ptacs.ekatalog.com.e_katalogproduk E/AndroidRuntime: FATAL EXCEPTION: main
Process: ptacs.ekatalog.com.e_katalogproduk, PID: 370
java.lang.RuntimeException: Unable to start activity ComponentInfo{ptacs.ekatalog.com.e_katalogproduk/ptacs.ekatalog.com.e_katalogproduk.activity.ActivityKategori}: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5235)
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:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at ptacs.ekatalog.com.e_katalogproduk.helper.DBHandler.getKategoryProduk(DBHandler.java:152)
at ptacs.ekatalog.com.e_katalogproduk.activity.ActivityKategori.initRecyclerView(ActivityKategori.java:68)
at ptacs.ekatalog.com.e_katalogproduk.activity.ActivityKategori.onCreate(ActivityKategori.java:43)
at android.app.Activity.performCreate(Activity.java:6001)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5235) 
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:898) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693) 
01-29 14:10:25.364 370-370/? I/Process: Sending signal. PID: 370 SIG: 9
ACTIVITY_MENU
ACTIVITY_KATEGORI

You are calling initRecyclerView(); before you initialise mMerkProduk. So just call initRecyclerView(); after if (getIntent().getExtras() != null) {....} block. Just like this
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
mMerkProduk = bundle.getString(Constant.BUNDLE_MERK_PRODUK); //MERK kategori
//Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(mMerkProduk);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
dbHandler = new DBHandler(this);
}
initRecyclerView();
cekDataRecyclerView();

As Logcat says
Caused by: java.lang.IllegalArgumentException: the bind value at index 1 is null
I think your mMerkProduk is null. Check mMerkProduk is null before query.
Check this answer. I think it's same case as yours.

variable value is from bundle
Not sure why that matters... Extract the value from the Bundle and use its value as a parameter to the database methods like any other value
You seem to already know how to use bundle.getString(), for example
If all you want is to see the data, your OnCreate should look like this.
Most importantly, you need to assign the value before you query the database and populate the list.
If you look at these lines of the error, then look at your code, the intent is not read yet, and your string is null
at ptacs.ekatalog.com.e_katalogproduk.helper.DBHandler.getKategoryProduk(DBHandler.java:152)
at ptacs.ekatalog.com.e_katalogproduk.activity.ActivityKategori.initRecyclerView(ActivityKategori.java:68)
Try instead separating the code that inits the list View object from the code the queries the database and populates the list
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kategori);
dbHandler = new DBHandler(ActivityKategori.this);
//Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initRecyclerView();
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
mMerkProduk = bundle.getString(Constant.BUNDLE_MERK_PRODUK);
setTitle(mMerkProduk);
fillRecyclerView(mMerkProduk);
}
// cekDataRecyclerView();
}
private void initRecyclerView(){
recyclerView = (RecyclerView) findViewById(R.id.rv_kategori);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
private void fillRecyclerView(String product) {
if (product!=null) {
kategoriList = dbHandler.getKategoryProduk(product);
adapter = new KategoriAdapter(kategoriList);
recyclerView.setAdapter(adapter);
}
}

Related

I get a NullPointerException, but I don't know where the error is [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
The logcat is here:
list view activity --> clicked item(admin_parents_item) ---> option selected EDIT (current activity)
When I click on my button to update/edit the database it crashes. Something is missing. How to fix this error?
03-08 06:44:57.163 11022-11022/edu.angelo.parentsportal E/AndroidRuntime: FATAL EXCEPTION: main
Process: edu.angelo.parentsportal, PID: 11022
java.lang.NullPointerException: Attempt to invoke virtual method 'void edu.angelo.parentsportal.DatabaseHelper.updateData(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at edu.angelo.parentsportal.Admin_Parents_Item_Edit$1.onClick(Admin_Parents_Item_Edit.java:63)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
admin_parent__item_edit.java (my current activity)
package edu.angelo.parentsportal;
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;
public class Admin_Parents_Item_Edit extends AppCompatActivity {
Button btn_update;
EditText ed_Name;
EditText ed_Surname;
EditText ed_Email;
EditText ed_Phone_Number;
EditText ed_Password;
String s_Id;
String s_Name;
String s_Surname;
String s_Email;
String s_Phone_Number;
String s_Password;
Integer getId;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__parents__item__edit);
ed_Name = findViewById(R.id.ed_name_update);
ed_Surname = findViewById(R.id.ed_surname_update);
ed_Email = findViewById(R.id.ed_email_update);
ed_Phone_Number = findViewById(R.id.ed_PhoneNumber_update);
ed_Password = findViewById(R.id.ed_password_update);
Intent intent = getIntent();
s_Id = intent.getStringExtra("ID");
s_Name = intent.getStringExtra("Name");
s_Surname = intent.getStringExtra("Surname");
s_Email = intent.getStringExtra("Email Address");
s_Phone_Number = intent.getStringExtra("Phone number");
s_Password = intent.getStringExtra("Password");
getId = Integer.parseInt(s_Id);
ed_Name.setText(s_Name);
ed_Surname.setText(s_Surname);
ed_Email.setText(s_Email);
ed_Phone_Number.setText(s_Phone_Number);
ed_Password.setText(s_Password);
btn_update = findViewById(R.id.btn_admin_parent_update);
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseHelper.updateData(getId,
ed_Name.getText().toString(),
ed_Surname.getText().toString(),
ed_Email.getText().toString(),
ed_Phone_Number.getText().toString(),
ed_Password.getText().toString());
finish();
}
});
}
}
Admin_parent_Item (my previous activity)
package edu.angelo.parentsportal;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class Admin_Parents_Item extends AppCompatActivity {
TextView tv_Id;
TextView tv_Name;
TextView tv_Surname;
TextView tv_Email;
TextView tv_Phone_Number;
TextView tv_Password;
String s_Id;
String s_Name;
String s_Surname;
String s_Email;
String s_Phone_Number;
String s_Password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__parents__item);
tv_Id = findViewById(R.id.tv_id_info);
tv_Name = findViewById(R.id.tv_name_info);
tv_Surname = findViewById(R.id.tv_surname_info);
tv_Email = findViewById(R.id.tv_email_info);
tv_Phone_Number = findViewById(R.id.tv_PhoneNumber_info);
tv_Password = findViewById(R.id.tv_password_info);
Intent intent = getIntent();
if (intent != null) {
s_Id = intent.getStringExtra("ID");
s_Name = intent.getStringExtra("Name");
s_Surname = intent.getStringExtra("Surname");
s_Email = intent.getStringExtra("Email Address");
s_Phone_Number = intent.getStringExtra("Phone Number");
s_Password = intent.getStringExtra("Password");
}
tv_Id.setText(s_Id);
tv_Name.setText(s_Name);
tv_Surname.setText(s_Surname);
tv_Email.setText(s_Email);
tv_Phone_Number.setText(s_Phone_Number);
tv_Password.setText(s_Password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.admin__parents_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.admin_parent_item_action_edit: {
Intent intent = new Intent(this, Admin_Parents_Item_Edit.class);
intent.putExtra("ID", s_Id);
intent.putExtra("Name", s_Name);
intent.putExtra("Surname", s_Surname);
intent.putExtra("Email Address", s_Email);
intent.putExtra("Phone number", s_Phone_Number);
intent.putExtra("Password", s_Password);
startActivity(intent);
finish();
break;
}
}
return super.onOptionsItemSelected(item);
}
}
DatabaseHelper.java
package edu.angelo.parentsportal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Parents_Portal.db";
public static final String TABLE_NAME = "Parents_Table";
public static final String COL_0 = "ID";
public static final String COL_1 = "NAME";
public static final String COL_2 = "SURNAME";
public static final String COL_3 = "EMAIL_ADDRESS";
public static final String COL_4 = "PHONE_NUMBER";
public static final String COL_5 = "PASSWORD";
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, NAME TEXT, SURNAME TEXT, EMAIL_ADDRESS TEXT, PHONE_NUMBER TEXT,
PASSWORD TEXT)");
}
#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 surname, String email_address,
String phone_number, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email_address);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public Cursor getAllData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.rawQuery("select * from " + TABLE_NAME, null);
return result;
}
public ArrayList<ParentModel> getAllParentsData() {
ArrayList<ParentModel> list = new ArrayList<>();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
ParentModel parentModel = new ParentModel();
parentModel.setID(cursor.getString(0));
parentModel.setName(cursor.getString(1));
parentModel.setSurname(cursor.getString(2));
parentModel.setEmail(cursor.getString(3));
parentModel.setPhone_number(cursor.getString(4));
parentModel.setPassword(cursor.getString(5));
list.add(parentModel);
}
while (cursor.moveToNext())
;
}
return list;
}
public void updateData(int id, String name, String surname, String email,
String phone_number, String password) {
ContentValues contentValues = new ContentValues();
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase mydb = this.getWritableDatabase();
Cursor cursor = mydb.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
contentValues.put(COL_1, name);
contentValues.put(COL_2, surname);
contentValues.put(COL_3, email);
contentValues.put(COL_4, phone_number);
contentValues.put(COL_5, password);
}
while (cursor.moveToNext());
}
mydb.update(TABLE_NAME, contentValues, COL_0 + "=" + id, null);
mydb.close();
}
}
Your databaseHelper is null. Initialize it in onCreate() like below.
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin__parents__item__edit);
databaseHelper = new DatabaseHelper (this); // Add this line
.........................

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

Why does my Activity get destroyed on adding a fragment?

So after editing a method in my MainAcivity, I'm getting a RuntimeException.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp
/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException:
Activity has been destroyed
I honestly have no idea where this is coming from. Searching online suggests that it's a big with the ChildFragmentManager, but doesn't give me a fix that works for me.
Any idea what I can do to fix this exception?
PS. If you need any more code or info, let me know. My mind is quite flustered by this error, so I might overlooked some stuff here.
Full log:
03-30 21:19:47.910 24785-24785/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tim.timapp, PID: 24785
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
at android.app.BackStackRecord.commit(BackStackRecord.java:663)
at com.example.tim.timapp.MainActivity.DrawVariableFragments(MainActivity.java:271)
at com.example.fragments.Settings.GeneralSettingsFragment.onCreateView(GeneralSettingsFragment.java:57)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1130)
at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1953)
at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:152)
at android.app.Activity.performCreateCommon(Activity.java:6232)
at android.app.Activity.performCreate(Activity.java:6239)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
MainActivity (Sorry about the mess, it's a WIP):
Sorry about this, but I went over the 30.000 characters limit with the entire file.
http://pastebin.com/XZ9k995G
DBHandler (Was giving me grief earlier, so might have something to do with it):
package com.example.tim.timapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper {
private static String tag = "TEST DBHandler";
private static DBHandler sInstance;
// Database Stuff
private static final int DATABASE_VERSION = 6;
private static final String DATABASE_NAME = "LinkDatabase.db";
// Table Stuff
private static final String TABLE_LinkTable = "LinkTable";
private static final String TABLE_SettingsTable = "SettingsTable";
// LinkTable Stuff
private static final String LT_COLUMN_ID = "_id";
private static final String LT_COLUMN_NAME = "name";
private static final String LT_COLUMN_TAG = "tag";
// SettingsTable Stuff
private static final String ST_COLUMN_ID = "_id";
private static final String ST_COLUMN_NAME = "name";
private static final String ST_COLUMN_IP = "ip";
private static final String ST_COLUMN_PORT = "port";
private static final String ST_COLUMN_USERNAME = "username";
private static final String ST_COLUMN_PASS = "pass";
// Table Create Statements
// LinkTable Create Statement
private static final String CREATE_TABLE_LINKS =
"CREATE TABLE " + TABLE_LinkTable + "(" +
LT_COLUMN_ID + " INTEGER PRIMARY KEY, " +
LT_COLUMN_NAME + " TEXT, " +
LT_COLUMN_TAG + " TEXT" + ");";
// SettingsTable Create Statement
private static final String CREATE_TABLE_SETTINGS =
"CREATE TABLE " + TABLE_SettingsTable + "(" +
ST_COLUMN_ID + " INTEGER PRIMARY KEY, " +
ST_COLUMN_NAME + " TEXT, " +
ST_COLUMN_IP + " TEXT, " +
ST_COLUMN_PORT + " TEXT, " +
ST_COLUMN_USERNAME + " TEXT, " +
ST_COLUMN_PASS + " TEXT" + ");";
// TODO: 28-Mar-16 DON"T FORGET TO UPDATE
// Don't forget to update this when adding a new table.
private static final ArrayList<String> createTablesArray = new ArrayList<String>() {{add(CREATE_TABLE_LINKS); add(CREATE_TABLE_SETTINGS);}};
private static final ArrayList<String> tableNamesArray = new ArrayList<String>() {{add(TABLE_LinkTable); add(TABLE_SettingsTable);}};
public ArrayList<String> tagArray;
public static synchronized DBHandler getInstance(Context context) {
if (sInstance == null) {
Log.d(tag, "sInstance == null");
sInstance = new DBHandler(context.getApplicationContext());
}
return sInstance;
}
private DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
for (String s : createTablesArray) {
db.execSQL(s);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (String s : tableNamesArray) {
db.execSQL("DROP TABLE IF EXISTS " + s);
}
onCreate(db);
}
public ArrayList<String> returnArray(String base, String column) {
SQLiteDatabase db;
db = getWritableDatabase();
String TABLENAME;
if (base.equalsIgnoreCase("StuffManager")) {
TABLENAME = TABLE_LinkTable;
} else if (base.equalsIgnoreCase("GeneralSettings")) {
TABLENAME = TABLE_SettingsTable;
} else {
Log.e(tag, "String Base not recognised");
return null;
}
String query = "SELECT * FROM " + TABLENAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
ArrayList<String> tempArray = new ArrayList<>();
int i = 0;
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex(column)) != null){
tempArray.add(i, c.getString(c.getColumnIndex(column)));
} else {
Log.e(tag, "String Column not recognised");
return null;
}
c.moveToNext();
i++;
}
c.close();
if (db != null && db.isOpen()) {
db.close();
}
return tempArray;
}
// *** --------- ***
//
// All methods for the SETTINGS_TABLES
//
// *** --------- ***
public void addSettings(String name, String ip, String port, String username, String pass) {
ContentValues values = new ContentValues();
values.put(ST_COLUMN_NAME, name);
values.put(ST_COLUMN_IP, ip);
values.put(ST_COLUMN_PORT, port);
values.put(ST_COLUMN_USERNAME, username);
values.put(ST_COLUMN_PASS, pass);
SQLiteDatabase db;
db = getWritableDatabase();
db.insert(TABLE_SettingsTable, null, values);
db.close();
}
public void updateSettings(int id, String name, String ip, String port, String username, String pass) {
ContentValues values = new ContentValues();
values.put(ST_COLUMN_NAME, name);
values.put(ST_COLUMN_IP, ip);
values.put(ST_COLUMN_PORT, port);
values.put(ST_COLUMN_USERNAME, username);
values.put(ST_COLUMN_PASS, pass);
SQLiteDatabase db;
db = getWritableDatabase();
db.update(TABLE_SettingsTable, values, "_id=" + id, null);
db.close();
}
public void deleteSettings(String name) {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SettingsTable + " WHERE " + ST_COLUMN_NAME + "=\"" + name + "\";");
db.close();
}
public void deleteAllSettings() {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_SettingsTable + " WHERE 1");
db.close();
}
public float settingsTableSize() {
SQLiteDatabase db;
db = getReadableDatabase();
float amount = DatabaseUtils.queryNumEntries(db, TABLE_SettingsTable);
db.close();
return amount;
}
public ArrayList<String> settingsNameArrayMethod() {
SQLiteDatabase db;
db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_SettingsTable + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
int i = 0;
ArrayList<String> nameArray = new ArrayList<>();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("name")) != null) {
nameArray.add(i, c.getString(c.getColumnIndex("name")));
}
c.moveToNext();
i++;
}
c.close();
db.close();
return nameArray;
}
// *** --------- ***
//
// All methods for the LINK_TABLES
//
// *** --------- ***
public void addStuffLink(String name, String tag) {
ContentValues values = new ContentValues();
values.put(LT_COLUMN_NAME, name);
values.put(LT_COLUMN_TAG, tag);
SQLiteDatabase db;
db = getWritableDatabase();
db.insert(TABLE_LinkTable, null, values);
db.close();
}
public Bundle updateStuffLink(int id, String name, String tag) {
ContentValues values = new ContentValues();
values.put(LT_COLUMN_NAME, name);
values.put(LT_COLUMN_TAG, tag);
SQLiteDatabase db;
db = getWritableDatabase();
db.update(TABLE_LinkTable, values, "_id=" + id, null);
db.close();
ArrayList<String> nameArray = stuffLinksNameArrayMethod();
ArrayList<String> tagArray = tagArrayMethod();
Bundle bundle = new Bundle();
bundle.putStringArrayList("nameArray", nameArray);
bundle.putStringArrayList("tagArray", tagArray);
return bundle;
}
public void deleteStuffLink(String name) {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LinkTable + " WHERE " + LT_COLUMN_NAME + "=\"" + name + "\";");
db.close();
}
public void deleteAllStuffLinks() {
SQLiteDatabase db;
db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_LinkTable + " WHERE 1");
db.close();
}
public ArrayList<String> stuffLinksNameArrayMethod(){
SQLiteDatabase db;
db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LinkTable + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
int i = 0;
ArrayList<String> nameArray = new ArrayList<>();
tagArray = new ArrayList<>();
while(!c.isAfterLast()){
if(c.getString(c.getColumnIndex("name")) != null){
nameArray.add(i, c.getString(c.getColumnIndex("name")));
tagArray.add(i, c.getString(c.getColumnIndex("tag")));
}
c.moveToNext();
i++;
}
c.close();
db.close();
return nameArray;
}
public ArrayList<String> tagArrayMethod() {
stuffLinksNameArrayMethod();
return tagArray;
}
public float stuffTableSize(){
SQLiteDatabase db;
db = getReadableDatabase();
float amount = DatabaseUtils.queryNumEntries(db, TABLE_LinkTable);
db.close();
return amount;
}
}
GeneralSettingsFragment
package com.example.fragments.Settings;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.fragments.MainFragments.DialogFragments.GeneralSettingsInitialInputDialog;
import com.example.fragments.MainFragments.VariableFragments.GeneralSettingsEmptyFragment;
import com.example.fragments.MainFragments.VariableFragments.GeneralSettingsVariableFragment;
import com.example.fragments.MainFragments.VariableFragments.StuffManagerVariableFragment;
import com.example.tim.timapp.DBHandler;
import com.example.tim.timapp.MainActivity;
import com.example.tim.timapp.R;
import java.util.ArrayList;
public class GeneralSettingsFragment extends Fragment {
DBHandler dbHandler;
MainActivity ma = new MainActivity();
private static Menu optionsMenu;
public static boolean hideDeleteAllButton = false;
LinearLayout linearLayout;
View rootView;
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_generalsettings, container, false);
linearLayout = (LinearLayout) rootView.findViewById(R.id.FragmentContainerGeneralSettings);
if (linearLayout == null) {
Log.e("GMF", "Layout is null");
} else if (linearLayout.getChildCount() == 0) {
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
hideDeleteAllButton = true;
} else {
hideDeleteAllButton = false;
}
ma.DrawVariableFragments("GeneralSettings", "draw");
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.stuffmanager_actionbuttons, menu);
optionsMenu = menu;
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
optionsMenu.findItem(R.id.removeAllButton).setVisible(!hideDeleteAllButton);
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addButton:
GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
GSIID.show(getFragmentManager(), "dialog");
return true;
case R.id.removeAllButton:
dbHandler = DBHandler.getInstance(getActivity());
final ArrayList<String> nameArray = dbHandler.settingsNameArrayMethod();
final FragmentManager fm = getFragmentManager();
AlertDialog.Builder removeAllDialog = new AlertDialog.Builder(getActivity())
.setTitle("Delete all?")
.setMessage("Are you sure you want to delete all your devices? This is irreversible.")
.setIcon(R.drawable.ic_delete_black)
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbHandler.deleteAllSettings();
for (String name : nameArray){
fm.beginTransaction().remove(fm.findFragmentByTag(name)).commit();
}
fm.executePendingTransactions();
// TODO: 30-Mar-16 Add "No devices created" screen like stuffmanager
hideDeleteAllButton = true;
getActivity().invalidateOptionsMenu();
}
})
.setNegativeButton("Cancel", null);
removeAllDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
MainActivity ma = new MainActivity();
This isn't valid in Android. You can't create an instance of an Activity like this because it isn't actually attached to the Android processes. This instance of MainActivity isn't going to step through any of the lifecycle methods, which is why you're seeing the error that the activity has been stopped. It was never actually started.
Instead, remove this reference to MainActivity, as it's bad practice to keep references like this around in your fragment. Any time you need an instance of MainActivity inside a fragment, use the following example:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...
MainActivity ma = (MainActivity) getActivity();
ma.DrawVariableFragments("GeneralSettings", "draw");
// ...
}

Android- No such column error

Error is popping up for me where its telling me a column of mine does not exist. This column exists within my Contract class for my database but for some reason isn't recognized by the cursor.
LOGCAT
03-16 16:37:29.029 8240-8240/com.compscitutorials.basigarcia.ramfernoscout E/SQLiteLog: (1) no such column: TEAM_NUMBER
03-16 16:37:29.030 8240-8240/com.compscitutorials.basigarcia.ramfernoscout D/AndroidRuntime: Shutting down VM
03-16 16:37:29.030 8240-8240/com.compscitutorials.basigarcia.ramfernoscout E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.compscitutorials.basigarcia.ramfernoscout, PID: 8240
android.database.sqlite.SQLiteException: no such column: TEAM_NUMBER (code 1): , while compiling: SELECT TEAM_NUMBER, PORTCULLIS, CHEVAL_DE_FRISE, MOAT, RAMPARTS, DRAWBRIDGE, SALLY_PORT, ROCK_WALL, ROCK_TERRAIN, LOW_BAR FROM scout_table
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.compscitutorials.basigarcia.ramfernoscout.DatabaseHelper.getInformation(DatabaseHelper.java:63)
at com.compscitutorials.basigarcia.ramfernoscout.ScoutFragment.onCreateView(ScoutFragment.java:40)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
DatabaseHelper.java
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 {
public static final String DATABASE_NAME = "Scout.db";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY = "CREATE TABLE " + DatabaseContract.NewDataInfo.TABLE_NAME + "(" + DatabaseContract.NewDataInfo.COL_NUMBER +
" INTEGER," + DatabaseContract.NewDataInfo.COL_PORTCULLIS + " TEXT," + DatabaseContract.NewDataInfo.COL_CHEVAL_FRISE + " TEXT," +
DatabaseContract.NewDataInfo.COL_MOAT + " TEXT," + DatabaseContract.NewDataInfo.COL_RAMPARTS + " TEXT," + DatabaseContract.NewDataInfo.COL_DRAWBRIDGE +
" TEXT," + DatabaseContract.NewDataInfo.COL_SALLY_PORT + " TEXT," + DatabaseContract.NewDataInfo.COL_ROCK_WALL + " TEXT," +
DatabaseContract.NewDataInfo.COL_ROCK_TERRAIN + " TEXT," + DatabaseContract.NewDataInfo.COL_LOW_BAR + " TEXT);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.e("DATABASE OPERATIONS", "Database created / opened ...");
} //End of DatabaseHelper
#Override
public void onCreate(SQLiteDatabase db) {
//Create Query
db.execSQL(CREATE_QUERY);
//Display Log message
Log.e("DATABASE OPERATIONS", "Table created...");
} //End of onCreate
public void addInformation(String eNumber, String ePoticullis, String eChevalFrise, String eMoat, String eRamparts, String eDrawbridge, String eSallyPort,
String eRockWall, String eRockTerrain, String eLowBar, SQLiteDatabase db) {
//Instantiate contentValues
ContentValues contentValues = new ContentValues();
//Insert all content values
contentValues.put(DatabaseContract.NewDataInfo.COL_NUMBER, eNumber);
contentValues.put(DatabaseContract.NewDataInfo.COL_PORTCULLIS, ePoticullis);
contentValues.put(DatabaseContract.NewDataInfo.COL_CHEVAL_FRISE, eChevalFrise);
contentValues.put(DatabaseContract.NewDataInfo.COL_MOAT, eMoat);
contentValues.put(DatabaseContract.NewDataInfo.COL_RAMPARTS, eRamparts);
contentValues.put(DatabaseContract.NewDataInfo.COL_DRAWBRIDGE, eDrawbridge);
contentValues.put(DatabaseContract.NewDataInfo.COL_SALLY_PORT, eSallyPort);
contentValues.put(DatabaseContract.NewDataInfo.COL_ROCK_WALL, eRockWall);
contentValues.put(DatabaseContract.NewDataInfo.COL_ROCK_TERRAIN, eRockTerrain);
contentValues.put(DatabaseContract.NewDataInfo.COL_LOW_BAR, eLowBar);
//Insert content values into table
db.insert(DatabaseContract.NewDataInfo.TABLE_NAME, null, contentValues);
//Display log message
Log.e("DATABASE OPERATIONS", "One row inserted...");
} //End of addInformation
public Cursor getInformation(SQLiteDatabase db){
Cursor cursor;
String[] projections = {DatabaseContract.NewDataInfo.COL_NUMBER, DatabaseContract.NewDataInfo.COL_PORTCULLIS,
DatabaseContract.NewDataInfo.COL_CHEVAL_FRISE, DatabaseContract.NewDataInfo.COL_MOAT,DatabaseContract.NewDataInfo.COL_RAMPARTS,
DatabaseContract.NewDataInfo.COL_DRAWBRIDGE, DatabaseContract.NewDataInfo.COL_SALLY_PORT, DatabaseContract.NewDataInfo.COL_ROCK_WALL,
DatabaseContract.NewDataInfo.COL_ROCK_TERRAIN, DatabaseContract.NewDataInfo.COL_LOW_BAR};
cursor = db.query(DatabaseContract.NewDataInfo.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
} //End of getInformation
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
} //End of onUpgrade
} //End of class
ScoutFragment.java
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
/**
* A simple {#link Fragment} subclass.
*/
public class ScoutFragment extends Fragment {
FloatingActionButton addDataScout;
ListView eListScoutInfo;
SQLiteDatabase sqLiteDatabase;
DatabaseHelper databaseHelper;
Cursor cursor;
ListScoutInfoAdapter listScoutInfoAdapter;
public ScoutFragment() {
// Required empty public constructor
} //End of ScoutFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scout, null, false);
view.setBackgroundColor(Color.WHITE);
eListScoutInfo = (ListView) view.findViewById(R.id.listScoutInfo);
listScoutInfoAdapter = new ListScoutInfoAdapter(getActivity().getApplicationContext(), R.layout.row_layout);
eListScoutInfo.setAdapter(listScoutInfoAdapter);
databaseHelper = new DatabaseHelper(getActivity().getApplicationContext());
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformation(sqLiteDatabase);
//Checks if information is available in cursor
if(cursor.moveToFirst()){
do {
//Delcare all strings
String teamNumber, portcullis, chevalFrise, moat, ramparts, drawbridge, sallyPort, rockWall, rockTerrain, lowBar;
//Get strings from cursor
teamNumber = cursor.getString(0);
portcullis = cursor.getString(1);
chevalFrise = cursor.getString(2);
moat = cursor.getString(3);
ramparts = cursor.getString(4);
drawbridge = cursor.getString(5);
sallyPort = cursor.getString(6);
rockWall = cursor.getString(7);
rockTerrain = cursor.getString(8);
lowBar = cursor.getString(9);
//Get methods from DatabaseProvider
DatabaseProvider databaseProvider = new DatabaseProvider(teamNumber, portcullis, chevalFrise, moat, ramparts,
drawbridge, sallyPort, rockWall, rockTerrain, lowBar);
//Pass objects to add method
listScoutInfoAdapter.add(databaseProvider);
} while (cursor.moveToNext());
} //End of if statement
//Setups Floating Action Button
addDataScout = (FloatingActionButton) view.findViewById(R.id.fab);
addDataScout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AddScoutDataFragment fragment = new AddScoutDataFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} //End of onClick
}); //End of setOnClickListener
return view;
} //End of onCreateView
} //End of class
DatabaseContract.java
public class DatabaseContract {
public static abstract class NewDataInfo {
public static final String TABLE_NAME = "scout_table";
public static final String COL_NUMBER = "TEAM_NUMBER";
public static final String COL_PORTCULLIS = "PORTCULLIS";
public static final String COL_CHEVAL_FRISE = "CHEVAL_DE_FRISE";
public static final String COL_MOAT = "MOAT";
public static final String COL_RAMPARTS = "RAMPARTS";
public static final String COL_DRAWBRIDGE = "DRAWBRIDGE";
public static final String COL_SALLY_PORT = "SALLY_PORT";
public static final String COL_ROCK_WALL = "ROCK_WALL";
public static final String COL_ROCK_TERRAIN = "ROCK_TERRAIN";
public static final String COL_LOW_BAR = "LOW_BAR";
} //End of NewDataInfo
} //End of class
As discussed you should clear the app data if it still in development as you created the database before without this column, if it in the production phase you should do such upgrades in OnUpgrad method.

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