When I was releasing an apk on google play I had to use a different package name cause of "com.example". I tried this and I get crash after testing an application. Before that everything was ok. I can send a manifest.
There are my errors.
My classes
Details.java
public class Details extends AppCompatActivity {
NoteDatabase db;
Note note;
TextView mDetails;
TextView clientDetails;
TextView timeDetails;
TextView nameDetails;
TextView detailsDetails;
ImageView noteDetails;
private Bitmap getImageFromByte(byte[] zdjecie){
return BitmapFactory.decodeByteArray(zdjecie, 0, zdjecie.length);
}
#SuppressLint("WrongThread")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDetails = findViewById(R.id.detailsOfNote);
mDetails.setMovementMethod(new ScrollingMovementMethod());
clientDetails = findViewById(R.id.clientOfNote);
timeDetails = findViewById(R.id.timeofNote);
nameDetails = findViewById(R.id.nameOfNote);
detailsDetails = findViewById(R.id.detailsOfNote);
noteDetails = findViewById(R.id.noteImage);
Intent i = getIntent();
Long id = i.getLongExtra("ID", 0);
db = new NoteDatabase(this);
note = db.getNote(id);
getSupportActionBar().setTitle(note.getTitle());
mDetails.setText(note.getContent());
clientDetails.setText(note.getTitle());
timeDetails.setText(note.getTime());
nameDetails.setText(note.getName());
detailsDetails.setText(note.getDetails());
noteDetails.setImageBitmap(stringToImage(note.getImage()));
Toast.makeText(this, "Podgląd klienta", Toast.LENGTH_SHORT).show();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.deleteNote(note.getID());
Toast.makeText(getApplicationContext(), "Klient usunięty", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),klienci.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == R.id.editNote){
Toast.makeText(this, "Edytowanie notatki", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this,Edit.class);
i.putExtra("ID",note.getID());
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
private void goToMain() {
Intent i = new Intent(this,klienci.class);
startActivity(i);
}
private Bitmap stringToImage(String imgString){
byte[] decodedString = Base64.decode(imgString,Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString,0,decodedString.length);
return decodedByte;
}
NoteDatabase.java
public class NoteDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 42;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
private static final String KEY_PHONE = "phone";
private static final String KEY_CLIENT = "client";
private static final String KEY_DETAILS = "details";
private static final String KEY_IMAGE = "image";
NoteDatabase(Context context) {
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE "+ DATABASE_TABLE + "("+ KEY_ID+" INT PRIMARY KEY,"+
KEY_TITLE + " TEXT,"+
KEY_CONTENT + " TEXT,"+
KEY_DATE + " TEXT,"+
KEY_TIME + " TEXT,"+
KEY_CLIENT + " TEXT,"+
KEY_DETAILS + " TEXT,"+
KEY_PHONE + " TEXT,"+
KEY_IMAGE + " TEXT"+")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion >= newVersion)
return;
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public long addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
long ID = db.insert(DATABASE_TABLE,null, c);
Log.d("Inserted", "ID -> " + ID);
return ID;
}
public Note getNote(long id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,new String[] {KEY_ID,KEY_TITLE,KEY_CONTENT,KEY_PHONE,KEY_CLIENT,KEY_DETAILS,KEY_DATE,KEY_TIME,KEY_IMAGE}, KEY_ID+"=?",
new String[]{String.valueOf(id)}, null, null,null);
if (cursor != null)
cursor.moveToFirst();
return new Note
(cursor.getLong(0)
,cursor.getString(1)
,cursor.getString(2)
,cursor.getString(3)
,cursor.getString(4)
,cursor.getString(5)
,cursor.getString(6)
,cursor.getString(7)
,cursor.getString(8));
}
public List<Note> getNotes() {
SQLiteDatabase db = this.getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
String query = "SELECT * FROM " + DATABASE_TABLE + " ORDER BY "+KEY_TITLE+" ASC";
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setDetails(cursor.getString(2));
note.setPhone(cursor.getString(3));
note.setClient(cursor.getString(4));
note.setContent(cursor.getString(5));
note.setDate(cursor.getString(6));
note.setTime(cursor.getString(7));
note.setImage(cursor.getString(8));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
public int editNote(Note note){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
Log.d("Edited", "Edited Title: -> "+ note.getTitle() + "\n ID -> "+note.getZdjecie());
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_PHONE,note.getPhone());
c.put(KEY_CLIENT,note.getClient());
c.put(KEY_DETAILS,note.getDetails());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
c.put(KEY_IMAGE,note.getImage());
return db.update(DATABASE_TABLE,c,KEY_ID +"=?",new String[]{String.valueOf(note.getID())});
}
void deleteNote(long id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(DATABASE_TABLE, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You are trying to get 0 index in the database. Every time you add a new Note its ID will be 0. So, change your database KEY_ID to AUTOINCREMENT.
String query = "CREATE TABLE " + DATABASE_TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT," +
KEY_PIES + " TEXT," +
KEY_RASAPSA + " TEXT," +
KEY_TEL + " TEXT," +
KEY_ZDJECIE + " TEXT" + ")";
db.execSQL(query);
Then check your cursor not null in
getNote()
Related
The command to retrieve user data doesn't display correctly, it shows the information of the last registered user.
MainActivity/login
public class MainActivity extends AppCompatActivity {
Button btnRegister, btnLogin;
EditText edtAccount, edtPassword;
Database db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRegister = (Button) findViewById(R.id.buttonSignup);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(i);
}
});
edtAccount = (EditText) findViewById(R.id.editTextAccount);
edtPassword = (EditText) findViewById(R.id.editTextPassword);
btnLogin = (Button) findViewById(R.id.buttonLogin);
db=new Database(this);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String account = edtAccount.getText().toString();
String password = edtPassword.getText().toString();
if (account.equals("") || password.equals("")){
Toast.makeText(MainActivity.this,
"Account and password are empty",Toast.LENGTH_SHORT).show();
}
else {
Boolean result = db.checkUserNamePassword(account, password);
if(result==true) {
Intent intent = new Intent(MainActivity.this, TestActivity.class);
intent.putExtra("account", account);
startActivity(intent);
}
else{
Boolean userCheckResult = db.checkUserName(account);
if(userCheckResult == true){
Toast.makeText(MainActivity.this,
"invalid password!", Toast.LENGTH_SHORT).show();
edtPassword.setError("invalid password!");
} else{
Toast.makeText(MainActivity.this,
"Account does not exist", Toast.LENGTH_SHORT).show();
edtAccount.setError("Account does not exist!");
}
}
}
}
});
}
}
Database
public class Database extends SQLiteOpenHelper {
public static final String TB_USER = "USER";
public static final String TB_PERSONAL = "PERSONAL";
public static final String TB_GROUPSCHEDULE = "GROUPSCHEDULE";
public static String TB_USER_ACCOUNT = "ACCOUNT";
public static String TB_USER_PASSWORD = "PASSWORD";
public static String TB_USER_ID = "USERID";
public static String TB_USER_FIRSTNAME = "USERFIRSTNAME";
public static String TB_USER_LASTNAME = "USERLASTNAME";
public static String TB_USER_PHONENUMBER = "PHONENUMBER";
public static String TB_USER_EMAIL = "EMAIL";
public static String TB_PERSONAL_ID = "PERSONALID";
public static String TB_PERSONAL_TIME = "PERSONALTIME";
public static String TB_PERSONAL_EVENT = "PERSONALEVENT";
public static String TB_GROUP_ID = "GROUPID";
public static String TB_GROUP_MEMBERS = "GROUPMEMBERS";
public static String TB_GROUP_LEADER = "GROUPLEADER";
public static String TB_GROUP_EVENT = "GROUPEVENT";
public static String TB_GROUP_TIME = "GROUPTIME";
public Database(Context context) {
super(context, "Mysche", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tbUSER = " CREATE TABLE " + TB_USER + " ( "
+ TB_USER_ACCOUNT + " TEXT , "
+ TB_USER_PASSWORD + " TEXT , "
+ TB_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TB_USER_FIRSTNAME + " TEXT, "
+ TB_USER_LASTNAME + " TEXT, "
+ TB_USER_EMAIL + " TEXT, "
+ TB_USER_PHONENUMBER + " TEXT )";
String tbPERSONAL = " CREATE TABLE " + TB_PERSONAL + " ( "
+ TB_PERSONAL_ID + " TEXT PRIMARY KEY , "
+ TB_PERSONAL_EVENT + " TEXT, "
+ TB_PERSONAL_TIME + " DATE )";
String tbGROUP = " CREATE TABLE " + TB_GROUPSCHEDULE + " ( "
+ TB_GROUP_ID + "INTEGER PRIMARY KEY , "
+ TB_GROUP_LEADER + " TEXT, "
+ TB_GROUP_MEMBERS + " TEXT, "
+ TB_GROUP_EVENT + " TEXT, "
+ TB_GROUP_TIME + " TEXT )";
db.execSQL(tbUSER);
db.execSQL(tbPERSONAL);
db.execSQL(tbGROUP);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TB_USER);
db.execSQL("DROP TABLE IF EXISTS " + TB_PERSONAL);
db.execSQL("DROP TABLE IF EXISTS " + TB_GROUPSCHEDULE);
onCreate(db);
}
public Boolean insertData(String ACCOUNT, String PASSWORD, String USERFIRSTNAME, String USERLASTNAME, String PHONENUMBER, String EMAIL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ACCOUNT", ACCOUNT);
contentValues.put("PASSWORD", PASSWORD);
contentValues.put("USERFIRSTNAME", USERFIRSTNAME);
contentValues.put("USERLASTNAME", USERLASTNAME);
contentValues.put("PHONENUMBER", PHONENUMBER);
contentValues.put("EMAIL", EMAIL);
long result = db.insert("USER", null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Boolean checkUserName(String ACCOUNT) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM USER WHERE ACCOUNT = ?"
, new String[]{ACCOUNT});
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
public Boolean checkUserNamePassword(String ACCOUNT, String PASSWORD) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from USER where ACCOUNT = ? and PASSWORD = ?"
, new String[]{ACCOUNT, PASSWORD});
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT, null);
return cursor;
}
}
TestActivity
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Database database = new Database(this);
TextView textViewName = findViewById(R.id.textViewUserName);
TextView textViewEmail = findViewById(R.id.textViewUserEmail);
TextView textViewPhone = findViewById(R.id.textViewPhone);
TextView textViewAccount = findViewById(R.id.textViewAccount);
String account = getIntent().getStringExtra("account");
textViewPhone.setText(account);
Cursor cursor = database.getInfo();
while (cursor.moveToNext()){
textViewName.setText(cursor.getString(4 ) + " " +(cursor.getString(3)));
textViewPhone.setText(cursor.getString(5));
textViewEmail.setText(cursor.getString(6));
textViewAccount.setText(account);
}
}
}
I think I need to change this command:
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT, null);
return cursor;
}
to:
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT + "=" + loggingAccount();, null);
return cursor;
}
But I don't know how to create and insert that loggingAccount() function. I was able to display username by getIntent() in TestActivity.
String account = getIntent().getStringExtra("account");
textViewPhone.setText(account);
Or if anyone knows another way please guide me.
You could create an overloaded method getInfo(String acct) and invoke as follows:
Cursor cursor = database.getInfo(account);
and define it as such:
public Cursor getInfo(String account) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(" SELECT * FROM " + TB_USER
+ " WHERE " + TB_USER_ACCOUNT + " = '" + account + "'", null);
return cursor;
}
An overloaded method means methods within a class can have the same name (e.g. getInfo) but differ in method signature (parameters). And of course their implementation can differ.
Since your query is formed using data from user input you should use prepared statements. Check out PreparedStatement for more discussion on that.
I'm creating an SQLiteDatabase, I was able to add all the EditText values into the Database however when trying to add a Date which I have used a DatePicker to find and input into TextView, the app crashes.
Is there a different way to insert TextView values into SQLiteDatabase.
Main Activity:
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
DatabaseHelper peopleDB;
TextView etDate;
Button btnAddData, btnViewData;
EditText etName, etEmail, etAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
peopleDB = new DatabaseHelper(this);
etName = (EditText) findViewById(R.id.editName);
etEmail = (EditText) findViewById(R.id.editEmail);
etAddress = (EditText) findViewById(R.id.editAddress);
etDate = (TextView) findViewById(R.id.textView4);
btnAddData = (Button) findViewById(R.id.btnAddData);
btnViewData = (Button) findViewById(R.id.btnViewData);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
AddData();
ViewData();
}
public void AddData() {
btnAddData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String tvShow = etAddress.getText().toString();
String date = etDate.getText().toString();
boolean insertData = peopleDB.addData(name, email, tvShow, date);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = (TextView) findViewById(R.id.textView4);
textView.setText(currentDateString);
}
public void ViewData() {
btnViewData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor data = peopleDB.showData();
if(data.getCount() == 0) {
display("Error", "No Data Found.");
return;
}
//display message
String datestring = etDate.getText().toString();
StringBuffer buffer = new StringBuffer();
while (data.moveToNext()){
buffer.append("ID: " + data.getString(0) + "\n");
buffer.append("Name: " + data.getString(1) + "\n");
buffer.append("Email: " + data.getString(2) + "\n");
buffer.append("Address: " + data.getString(3) + "\n");
buffer.append("Date: " + data.getString(4) + "\n");
}
display("All Stored Data:", buffer.toString());
}
});
}
DatabaseHelper Activity:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "people.db";
public static final String TABLE_NAME = "people_table";
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "EMAIL";
public static final String COL4 = "ADDRESS";
public static final String COL5 = "DATE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" NAME TEXT, EMAIL TEXT, ADDRESS TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String name, String email, String address, String date){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, name);
contentValues.put(COL3, email);
contentValues.put(COL4, address);
contentValues.put(COL5, date);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
}
else {
return true;
}
}
public Cursor showData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}
I think that you did not add date column in create database statement so change this at DatabaseHelper class
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" NAME TEXT, EMAIL TEXT, ADDRESS TEXT)";
db.execSQL(createTable);
}
to
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" NAME TEXT, EMAIL TEXT, ADDRESS TEXT , DATE DATETIME)";
db.execSQL(createTable);
}
For best code refactor variables names by click shift+F6 then rename
public static final String COL1 = "ID";
public static final String COL2 = "NAME";
public static final String COL3 = "EMAIL";
public static final String COL4 = "ADDRESS";
public static final String COL5 = "DATE";
to
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_ADDRESS = "ADDRESS";
public static final String COL_DATE = "DATE";
and change create statement to
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME +" TEXT," +
COL_EMAIL +" TEXT,"+
COL_ADDRESS + " TEXT ,"+
COL_DATE + " DATETIME)";
db.execSQL(createTable);
}
public class Main2Activity extends AppCompatActivity {
private EditText editText1, editText2, editText3, editText4;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
editText3 = (EditText) findViewById(R.id.editText3);
editText4 = (EditText) findViewById(R.id.editText4);
button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String un, pw, cpw, ph;
un = editText1.getText().toString();
pw = editText2.getText().toString();
cpw = editText3.getText().toString();
ph = editText4.getText().toString();
DbHelper dbHelpero = new DbHelper(Main2Activity.this);
SQLiteDatabase db = dbHelpero.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Entry.C_UNAME, un);
values.put(Entry.C_PASS, pw);
values.put(Entry.C_CPASS, cpw);
values.put(Entry.C_PNO, ph);
long newRowId = db.insert(Entry.TABLE_NAME, null, values);
if (newRowId == -1) {
Toast.makeText(getApplicationContext(), "Error while adding", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Yo Registration is complete", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here is the Contract.java
public class Contract {
private Contract() {
}
public static final class Entry implements BaseColumns {
public final static String TABLE_NAME = "details";
public final static String _ID = BaseColumns._ID;
public final static String C_UNAME = "uname";
public final static String C_PASS = "pw";
public final static String C_CPASS = "cpw";
public final static String C_PNO = "pno";
}
}
And the DbHelper.java
public class DbHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = DbHelper.class.getSimpleName();
public final static String DATABASE_NAME = "contacts.db";
private static final int DATABASE_VERSION = 1;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " TEXT PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
There are no syntax errors but still, the app is crashing.
Replace your CREATE_TABLE query with:
String CREATE_TABLE = "CREATE TABLE " + Entry.TABLE_NAME + " ("
+ Entry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Entry.C_UNAME + " TEXT, "
+ Entry.C_PASS + " TEXT, "
+ Entry.C_CPASS + " TEXT, "
+ Entry.C_PNO + " TEXT" + ")";
You can't have a TEXT type have an AUTOINCREMENT property as you currently have it on your _ID field. You need to change it to be an INTEGER so it can be used as PRIMARY KEY and then have it AUTOINCREMENT
im getting problem in displaying my data from sqlite db
my apps stops working when run and display no errors.
please help me
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "ExpDatee.db";
public static final String TABLE_NAME = "EXPDATE_TABLE";
public static final String COL_1 = "PRO_ID";
public static final String COL_2 = "PRO_NAME";
public static final String COL_3 = "PRO_EXPDATE";
public static final String COL_4 = "PRO_DAYTILLEXP";
/**
private static final String SQL_CREATE_TABLE_EXPDATE = "CREATE TABLE " + TABLE_NAME + "("
+ PRO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PRO_NAME + " TEXT NOT NULL, "
+ PRO_EXPDATE+ " TEXT NOT NULL, "
+ PRO_DAYTILLEXP + " TEXT NOT NULL, "
+ ");";
**/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
// SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(PRO_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"PRO_NAME TEXT, " +
"PRO_EXPDATE TEXT," +
" PRO_DAYTILLEXP TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
//method to insert data
public boolean insertData(String PRO_NAME, String PRO_EXPDATE, String PRO_DAYTILLEXP)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,PRO_NAME);
contentValues.put(COL_3,PRO_EXPDATE);
contentValues.put(COL_4,PRO_DAYTILLEXP);
Log.d(TAG, "ADD DATA : ADDING " + PRO_NAME + " TO " + TABLE_NAME);
Log.d(TAG, "ADD DATA : ADDING " + PRO_EXPDATE + " TO " + TABLE_NAME);
Log.d(TAG, "ADD DATA : ADDING " + PRO_DAYTILLEXP + " TO " + TABLE_NAME);
long result = db.insert(TABLE_NAME,null ,contentValues );
if (result == -1)
return false;
else
return true;
}
//get all data
public Cursor getData()
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM" + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText etProductName, etDaysBeforeExp, etExpDate;
Button btnAddItem, btnViewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this);
etProductName = (EditText)findViewById(R.id.etProductName);
etDaysBeforeExp = (EditText)findViewById(R.id.etDaysBeforeExp);
etExpDate = (EditText)findViewById(R.id.etExpDate);
btnAddItem = (Button)findViewById(R.id.btnAddItem);
btnViewItem = (Button)findViewById(R.id.btnViewItem);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String PRO_NAME = etProductName.getText().toString();
String PRO_EXPDATE = etExpDate.getText().toString();
String PRO_DAYTILLEXP = etDaysBeforeExp.getText().toString();
if(etProductName.length() !=0)
{
AddData(PRO_NAME,PRO_EXPDATE,PRO_DAYTILLEXP);
etProductName.setText("");
etExpDate.setText("");
etDaysBeforeExp.setText("");
}
else
{
toastMessage("PLEASE INSERT VALUE");
}
}
});
btnViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String PRO_NAME, String PRO_EXPDATE, String PRO_DAYTILLEXP)
{
boolean InsertData = myDB.insertData(PRO_NAME,PRO_EXPDATE,PRO_DAYTILLEXP);
if(InsertData)
{
toastMessage("DATA INSERTED");
}
else
{
toastMessage("DATA NOT INSERTED");
}
}
private void toastMessage(String message) {
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
ListDataActivity.java
public class ListDataActivity extends AppCompatActivity {
DatabaseHelper myDB;
private ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
populateListView();
}
private void populateListView() {
Cursor data = myDB.getData();
ArrayList<String> listData = new ArrayList<>();
while (data.moveToNext())
{
listData.add(data.getString(1));
listData.add(data.getString(2));
listData.add(data.getString(3));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
}
private void toastMessage(String message) {
Toast.makeText(this,message, Toast.LENGTH_LONG).show();
}
}
Initialized Listdataactivity
myDB = new DatabaseHelper(this);
Use Arrayadapter
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
I'm using fragment to create tabs, and I'm trying to insert information from the fragment to my database.
So I've 3 RadioGroup and I'm adding to the database the 'Checked' radio button that the user has marked, and I'm not able to add into the database the data because the following error:
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
There are DatabaseHandler functions (which works) that I use such as
db.checkSetting() - Check if the database table is empty, if empty return false, if not return true.
db.updateSetting() - Update the data inside the table.
db.addSetting() - Create new table with new data.
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
//table name
private static final String TABLE_DETAILS = "details";
private static final String TABLE_FOOD = "food";
private static final String TABLE_OLDDETAILS = "oldDetails";
private static final String TABLE_SETTING = "setting";
//Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_HEIGHT = "height";
private static final String KEY_WEIGHT = "weight";
private static final String KEY_CALORIES = "calories";
private static final String KEY_DATE = "date";
private static final String KEY_LEVEL = "level";
private static final String KEY_DURATION = "duration";
private static final String KEY_DAYS = "days";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DETAILS_TABLE = "CREATE TABLE " + TABLE_DETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_FOOD_TABLE = "CREATE TABLE " + TABLE_FOOD + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_CALORIES + " INTEGER " + ")";
String CREATE_OLDDETAILS_TABLE = "CREATE TABLE " + TABLE_OLDDETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_SETTING_TABLE = "CREATE TABLE " + TABLE_SETTING + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_LEVEL + " INTEGER," + KEY_DURATION + " INTEGER," + KEY_DAYS + " INTEGER " + ")";
db.execSQL(CREATE_OLDDETAILS_TABLE);
db.execSQL(CREATE_DETAILS_TABLE);
db.execSQL(CREATE_FOOD_TABLE);
db.execSQL(CREATE_SETTING_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_DETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_OLDDETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOOD);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTING);
// Create tables again
onCreate(db);
}
public boolean addSetting(int level, int duration, int days) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, 1);
values.put(KEY_LEVEL, level);
values.put(KEY_DURATION, duration);
values.put(KEY_DAYS, days);
// Inserting Row
long result = db.insert(TABLE_SETTING, null, values);
if(result == -1){
return false;
}
else{
return true;
}
}
public boolean checkSetting(){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
Cursor cursor = db.rawQuery(selectQuery, null);
Boolean rowExists;
if (cursor.moveToFirst())
{
// DO SOMETHING WITH CURSOR
rowExists = true;
} else
{
// I AM EMPTY
rowExists = false;
}
return rowExists;
}
public setting getSetting() {
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
setting set = new setting(cursor.getInt(1), cursor.getInt(2), cursor.getInt(3));
return set;
}
public int updateSetting(setting set) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LEVEL, set.getLevel());
values.put(KEY_DURATION, set.getDuration());
values.put(KEY_DAYS, set.getDays());
Log.d("UPDATE: ", "updated all");
// updating row
return db.update(TABLE_SETTING, values, KEY_ID + " = ?", new String[] { String.valueOf(1) });
}
Fragment:
public class PageFragment extends Fragment {
DatabaseHandler db = new DatabaseHandler(getActivity()); //DATABASE
private int group1;
private int group2;
private int group3;
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_training, container, false);
ViewStub stub = (ViewStub) view.findViewById(R.id.stub);
if(mPage == 1) { // mPage represents the ID of the tab/page/fragment that in use.
stub.setLayoutResource(R.layout.fragment_trainingone); // Sets resource for each fragment
View inflated = stub.inflate();
return inflated;
}
else{
stub.setLayoutResource(R.layout.fragment_trainingtwo);
View inflated = stub.inflate();
RadioGroup rg1 = (RadioGroup) inflated.findViewById(R.id.group1);
RadioGroup rg2 = (RadioGroup) inflated.findViewById(R.id.group2);
RadioGroup rg3 = (RadioGroup) inflated.findViewById(R.id.group3);
Button update = (Button) inflated.findViewById(R.id.update);
rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
group1 = 1;
break;
case R.id.radio2:
group1 = 2;
break;
case R.id.radio3:
group1 = 3;
break;
}
}
});
rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio11:
group2 = 1;
break;
case R.id.radio22:
group2 = 2;
break;
case R.id.radio33:
group2 = 3;
break;
}
}
});
rg3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio111:
group3 = 1;
break;
case R.id.radio222:
group3 = 2;
break;
case R.id.radio333:
group3 = 3;
break;
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
setting set = new setting(group1, group2, group3);
if (db.checkSetting()) {
db.updateSetting(set);
} else {
db.addSetting(group1, group2, group3);
}
}
});
return inflated;
}
}
}
How can I insert data into database within fragment and avoiding NullPointerException?
You're calling
DatabaseHandler db = new DatabaseHandler(getActivity());
before the Activity is even attached to the Fragment. Initialise it in the onCreate(), or onAttach() method, so getActivity() doesn't return null.
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
According to Exception You Have to open database before querying from it follow the below linked post
public void openDataBase() throws SQLException
{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
SQLite database status on app uninstall