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();
}
Related
I am new to programming and to Android Studio.
I am trying to implement a ProfileActivity for a simple chat-project in which the user is able to update some rows in the User table of a SQLite Database through a simple profile-form after signing up and then signing in in the app.
That should appen through the method updateUser() through the query db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?", new String[]{ String.valueOf(user.getId()) }); in the DatabaseHelper Class, as you can see here:
/**
* This method to update user record
*
* #param user
*/
public void updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_CITY, user.getCity());
values.put(COLUMN_USER_AGE, user.getAge());
values.put(COLUMN_USER_SEX, user.getSex());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?", new String[]{ String.valueOf(user.getId()) });
db.close();
}
}
Anyway I was getting all the time from the User-model an id = 0 and the update did not work.
Now, after many attempts, I found a (pseudo)solution providing a global public static integer variable "user_id" and accessing it directly in ProfileActivity. The table-update works fine now. Anyway I know that it is a very bad practice against the principles of data encapsulation, as you can see here:
DatabaseHelper.java
package com.example.chat_project.Sql;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.chat_project.Model.User;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
private static final String COLUMN_USER_AGE = "user_age";
private static final String COLUMN_USER_CITY = "user_city";
private static final String COLUMN_USER_SEX = "user_sex";
private User user;
private Cursor userId;
int rv = -1;
public static int user_id;
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT," + COLUMN_USER_AGE +
" INTEGER," + COLUMN_USER_CITY + " TEXT," + COLUMN_USER_SEX + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
/**
* Constructor
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
/**
* This method to check user exist or not
*
* #param email
* #param password
* #return true/false
*/
#SuppressLint("Range")
public boolean checkLoggedUser (String email, String password) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
if (cursor.moveToFirst()) {
rv = cursor.getInt(cursor.getColumnIndex("user_id"));
getLoggedUser(rv);
}
//The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to fill user_id with column index
*
* #param i
*/
public int getLoggedUser(int i){
//stores index of columns
user_id = i;
return user_id;
}
/**
* This method to update user record
*
* #param user
*/
public void updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_CITY, user.getCity());
values.put(COLUMN_USER_AGE, user.getAge());
values.put(COLUMN_USER_SEX, user.getSex());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?", new String[] { String.valueOf(user_id) });
db.close();
}
}
ProfileActivity.java
package com.example.chat_project.Activities;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.widget.NestedScrollView;
import com.example.chat_project.Model.User;
import com.example.chat_project.R;
import com.example.chat_project.Sql.DatabaseHelper;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {
private static final int PICK_IMAGE = 100;
private final AppCompatActivity activity = ProfileActivity.this;
private ConstraintLayout constraintLayout;
private AppCompatEditText inputName;
private AppCompatEditText inputAge;
private AppCompatEditText inputCity;
private AppCompatEditText inputSex;
private AppCompatImageView profileImage;
private AppCompatButton saveProfile;
private AppCompatButton pickImage;
private DatabaseHelper databaseHelper;
private User user;
private String user_name, user_sex, user_city;
private int user_age;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().setTitle("");
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);
inputName = (AppCompatEditText) findViewById(R.id.editTextUserName);
inputAge = (AppCompatEditText)findViewById(R.id.editTextUserAge);
inputCity= (AppCompatEditText)findViewById(R.id.editTextCity);
inputSex = (AppCompatEditText)findViewById(R.id.editTextUserSex);
profileImage = (AppCompatImageView)findViewById(R.id.imageViewProfileImage);
saveProfile = (AppCompatButton) findViewById(R.id.buttonSaveProfile);
pickImage = (AppCompatButton) findViewById(R.id.buttonPickImage);
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
saveProfile.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
user = new User();
inputName.setText(user.getName());
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonPickImage:
/**
new MaterialDialog.Builder(this)
.title("set your image")
.items(R.array.uploadImages)
.itemsIds(R.array.itemIds)
.itemsCallback((dialog, view, which, text){
switch (which){
case 0:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
break;
case 1:
profileImage.setImageResource(R.drawable.no_profile_pic);
break;
}
})*/
//insertImageToSQLite();
break;
case R.id.buttonSaveProfile:
postDataToSQLite();
break;
}
}
/**
* This method is to post data to SQLite
*/
private void postDataToSQLite() {
user.setName(inputName.getText().toString().trim());
user.setAge(Integer.parseInt(inputAge.getText().toString().trim()));
user.setSex(inputSex.getText().toString().trim());
user.setCity(inputCity.getText().toString().trim());
// here the static variable from DatabaseHelper is retrieved
user.setId(databaseHelper.user_id);
databaseHelper.updateUser(user);
Toast.makeText(this, "Profile successfully saved", Toast.LENGTH_SHORT).show();
}
}
How can I do in order to update the rows in the User-table without declaring a public static variable for the id?
Thank you very much in advance for every hint!
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)
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
}
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));
I want all edit text content that I have saved in SQL to be displayed on the edit bills activity when I click on the list item, but I am only able to retrieve the name and display it again in the intent. Rather than saving another data it should update the record with the new data if I save the existing record another time in the editbills_activity. Here is my DBAdapter.java
package com.example.dhruv.bills;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "name VARCHAR not null, amount VARCHAR, duedate date );";
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
//return db.insert(DATABASE_TABLE, null, initialValues);
// Will return NULL POINTER EXCEPTION as db isn't set
// Replaces commented out line
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public void deleteName(int id, String name){
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "DELETE FROM " + DATABASE_TABLE + " WHERE "
+ KEY_ROWID + " = '" + id + "'" +
" AND " + KEY_NAME + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
/* public Cursor getRecord()
{String query1 ="SELECT * FROM" + KEY_TITLE;
Cursor mCursor = db.rawQuery(query1,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}*/
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
/* public boolean updateRecord(long rowId, String name, String amount, String duedate)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
// Will return NULL POINTER EXCEPTION as db isn't set
//return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// Replaces commented out line
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}*/
}
Here is my Bills.java (MainActivity)
Problem: Bills.java has the list view that shows the intent whenever the item in list view is clicked, but it does not put the amount and date or update the record. Instead it saves another record.
Solution: I want to retrieve it and display all (name ,amount,duedate) and instead of saving another record it should update it.
package com.example.dhruv.bill;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class bills extends AppCompatActivity {
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="assignments";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mrecycleview =(ListView) findViewById(R.id.mRecycleView);
dbAdapter = new DBAdapter(this);
// mlistview();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab1);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Editbills.class);
startActivity(i);
}
});
mlistview();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void mlistview(){
Log.d(TAG,"mlistview:Display data in listview");
Cursor mCursor = dbAdapter.getAllRecords();
ArrayList<String> listData = new ArrayList<>();
while (mCursor.moveToNext()){
listData.add(mCursor.getString(1));
}
ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = dbAdapter.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(bills.this, Editbills.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
}
}
});
}
}
here is my editbills.java code
package com.example.dhruv.bill;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag= "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private int selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.editText);
editText2=(EditText)findViewById(R.id.editText2);
editText3 =(EditText)findViewById(R.id.editText3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
editText.setText(selectedName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bills, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_Delete) {
db.deleteName(selectedID,selectedName);
editText.setText("");
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
Intent p = new Intent(getApplicationContext(),bills.class);
startActivity(p);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Instead of
DBHelper.getWritableDatabase().insert(DATABASE_TABLE, null, initialValues);
in insertRecord function of DBHelper, it should be
DBHelper.getWritableDatabase().update("markers", valores, where, whereArgs);