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);
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 want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 + " TEXT" + COL3 + " ,TEXT)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!
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);
}
My app isn't displaying the data i'm inserting into the interface, i'm creating a fighter database where my coach can add fighters from the gym into it. I'm using a card view and recycling adaptor to display all the data but when I click submit it wont display.
Error log:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ArrayList<Item>list = new ArrayList<Item>();
private ItemAdapter adapter;
private RecyclerView recyclerView;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fetchRecords();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getLayoutInflater();
View mView1 = inflater.inflate(R.layout.activity_add,null);
final EditText input_name = (EditText) mView1.findViewById(R.id.Name);
final EditText input_age = (EditText) mView1.findViewById(R.id.Age);
final EditText input_weight = (EditText) mView1.findViewById(R.id.Weight);
final EditText input_height = (EditText) mView1.findViewById(R.id.Height);
final EditText input_reach = (EditText) mView1.findViewById(R.id.Reach);
final Button btnSave = (Button) mView1.findViewById(R.id.btnSave);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(mView1).setTitle("Add new Record")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialog.dismiss();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = input_name.getText().toString();
String age = input_age.getText().toString();
String weight = input_weight.getText().toString();
String height = input_height.getText().toString();
String reach = input_reach.getText().toString();
if (name.equals("") && age.equals("") && weight.equals("") && height.equals("")&& reach.equals("")){
Snackbar.make(view,"Field incomplete",Snackbar.LENGTH_SHORT).show();
}else {
Save(name,age,name,height,reach);
dialog.dismiss();
Snackbar.make(view,"Saving",Snackbar.LENGTH_SHORT).show();
}
}
});
dialog = builder.create();
dialog.show();
}
});
}
public void fetchRecords() {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
adapter = new ItemAdapter(this,list);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
list.clear();
Functions functions = new Functions(MainActivity.this);
ArrayList<Item>data = functions.getAllRecords();
if (data.size()>0){
for (int i = 0; i<data.size(); i++){
int id = data.get(i).getId();
String namel = data.get(i).getName();
String agel = data.get(i).getAge();
String weightl = data.get(i).getWeight();
String heightl = data.get(i).getHeight();
String reachl = data.get(i).getReach();
Item item = new Item();
item.setId(id);
item.setName(namel);
item.setAge(agel);
item.setWeight(weightl);
item.setHeight(heightl);
item.setReach(reachl);
list.add(item);
}adapter.notifyDataSetChanged();
}else {
Toast.makeText(MainActivity.this, "No Records found.", Toast.LENGTH_SHORT).show();
}
}
private void Save(String name, String age, String weight, String height, String reach) {
Functions functions = new Functions(MainActivity.this);
Item item = new Item();
item.setName(name);
item.setAge(age);
item.setWeight(weight);
item.setHeight(height);
item.setReach(reach);
functions.Insert(item);
Toast.makeText(MainActivity.this, "Saved...", Toast.LENGTH_SHORT).show();
fetchRecords();
}
#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_main, menu);
return true;
}
}
public class Functions extends SQLiteOpenHelper {
private static final String DB_NAME = "crud.db";
private static final int DB_VERSION = 1;
private Fighter fighter = new Fighter();
public Functions(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(fighter.CREATE_TABLE_PERSON);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + fighter.TABLE_FIGHTER);
}
public void Insert(Item item){
SQLiteDatabase database = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(fighter.ID,item.getId());
contentValues.put(fighter.NAME,item.getName());
contentValues.put(fighter.AGE,item.getAge());
contentValues.put(fighter.WEIGHT,item.getWeight());
contentValues.put(fighter.HEIGHT,item.getHeight());
contentValues.put(fighter.REACH,item.getReach());
database.insert(fighter.TABLE_FIGHTER,null,contentValues);
}
public ArrayList<Item>getAllRecords(){
ArrayList<Item>list = new ArrayList<Item>();
SQLiteDatabase database = getReadableDatabase();
String sql = "SELECT * FROM " + fighter.TABLE_FIGHTER;
Cursor cursor = database.rawQuery(sql,null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setAge(cursor.getString(2));
item.setWeight(cursor.getString(3));
item.setHeight(cursor.getString(4));
item.setReach(cursor.getString(5));
list.add(item);
}while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
public Item getSingleItem(int id){
SQLiteDatabase database = getReadableDatabase();
String sql = "SELECT * FROM " + fighter.TABLE_FIGHTER + " WHERE " + fighter.ID + "=?";
Cursor cursor = database.rawQuery(sql,new String[]{String.valueOf(id)});
if (cursor != null)
cursor.moveToNext();
Item item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setAge(cursor.getString(2));
item.setWeight(cursor.getString(3));
item.setHeight(cursor.getString(4));
item.setReach(cursor.getString(4));
cursor.close();
database.close();
return item;
}
public void DeleteItem(int id){
SQLiteDatabase database = getWritableDatabase();
database.delete(fighter.TABLE_FIGHTER,fighter.ID + "=?",new String[]{String.valueOf(id)});
database.close();
}
public void Update(Item item){
SQLiteDatabase database = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(fighter.NAME,item.getName());
contentValues.put(fighter.AGE,item.getAge());
contentValues.put(fighter.WEIGHT,item.getWeight());
contentValues.put(fighter.HEIGHT,item.getHeight());
contentValues.put(fighter.REACH,item.getReach());
database.update(fighter.TABLE_FIGHTER,contentValues,fighter.ID + "=?",new String[]{String.valueOf(item.getId())});
}
}
public class Fighter {
public static final String TABLE_FIGHTER = "fighter";
public static final String ID = "ID";
public static final String NAME = "Name";
public static final String AGE = "Age";
public static final String WEIGHT = "Weight";
public static final String HEIGHT = "Height";
public static final String REACH = "Reach";
public static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_FIGHTER + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ AGE + " TEXT,"
+ WEIGHT + " TEXT,"
+ HEIGHT + " TEXT"
+ REACH + " TEXT"+ ")";
}
According to your code, you have missed a comma after + HEIGHT + " TEXT" . therefore table is not created properly due to SQL syntax errors. please try with following. i have added the comma for you.
public static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_FIGHTER + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ AGE + " TEXT,"
+ WEIGHT + " TEXT,"
+ HEIGHT + " TEXT,"
+ REACH + " TEXT"+ ")";
I'm creating a Calorie App for my class project. I attempted to implement a database to store the information of the calories added by the user which would be displayed in a listview. The user will input the calories in the add_entry fragment and be displayed on the fragment_home page in the listview.
Problem: I'm not sure if I'm adding the information correctly to the database using the Entry Add Fragment in order to display the info in the listview. this is my first time working with Android Studio/App.
Problem 2:
For Some Reason when I click on imagebutton on my homefragment app crashes and
it doesnt go to the add_entry fragment
logcat:
04-06 00:33:41.213 30567-30567/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 30567
java.lang.IllegalStateException: Could not find method Click(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'AddItems'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
public static final String ARG_SECTION_NUMBER = "section_number";
public static final String ARG_ID = "_id";
private TextView label;
private int sectionNumber = 0;
private Calendar fragmentDate;
ListView listview;
ImageButton AddEntrybtn;
CalorieDatabase calorieDB;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
label= (TextView) myView.findViewById(R.id.section_label);
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain= (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
openDataBase();
}
private void openDataBase (){
calorieDB= new CalorieDatabase(getActivity());
calorieDB.open();
}
private void closeDataBase(){
calorieDB.close();
};
private void populateLVFromDB(){
Cursor cursor = calorieDB.getAllRows();
String[] fromFieldNames = new String[]
{CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
int[] toViewIDs = new int[]
{R.id.foodEditText, R.id.caloriesEditText, };
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
getActivity(),
R.layout.row_item,
cursor,
fromFieldNames,
toViewIDs
);
listview = (ListView) getActivity().findViewById(R.id.listView);
listview.setAdapter(myCursorAdapter);
}
#Override
public void onResume() {
super.onResume();
// set label to selected date. Get date from Bundle.
int dayOffset = sectionNumber - FragmentHomeDayViewPager.pagerPageToday;
fragmentDate = Calendar.getInstance();
fragmentDate.add(Calendar.DATE, dayOffset);
SimpleDateFormat sdf = new SimpleDateFormat(appMain.dateFormat);
String labelText = sdf.format(fragmentDate.getTime());
switch (dayOffset) {
case 0:
labelText += " (Today)";
break;
case 1:
labelText += " (Tomorrow)";
break;
case -1:
labelText += " (Yesterday)";
break;
}
label.setText(labelText);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity( new Intent(getContext(),MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder,addEntry)
.commit();
break;
}
}
}
CalorieDatabase.java
public class CalorieDatabase {
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "Description";
public static final String KEY_CalorieValue = "Calories";
public static final int COL_NAME = 1;
public static final int COL_CalorieValue= 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID,
KEY_NAME, KEY_CalorieValue};
public static final String DATABASE_NAME = "CalorieDb";
public static final String DATABASE_TABLE = "Calorie_Info";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public CalorieDatabase(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public CalorieDatabase open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(String description, int CalorieVal) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, description);
initialValues.put(KEY_CalorieValue, CalorieVal);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public boolean updateRow(long rowId, String description, int
CalorieValue) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, description);
newValues.put(KEY_CalorieValue, CalorieValue);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(_db);
}
}
}
AddEntry.java
public class AddEntry extends Fragment implements
View.OnClickListener {
EditText DescriptionET,CalorieET;
ImageButton savebtn;
String description , calorieAmt;
CalorieDatabase calorieDB;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_entry, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
break;
case R.id.CancelBtn:
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private static final String DATABASE_NAME = "CalorieDb.db";
And then call below method in oncreat()
public void checkDB() {
try {
//android default database location is : /data/data/youapppackagename/databases/
String packageName = this.getPackageName();
String destPath = "/data/data/" + packageName + "/databases";
String fullPath = "/data/data/" + packageName + "/databases/"
+ DATABASE_NAME;
//this database folder location
File f = new File(destPath);
//this database file location
File obj = new File(fullPath);
//check if databases folder exists or not. if not create it
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
}
//check database file exists or not, if not copy database from assets
if (!obj.exists()) {
this.CopyDB(fullPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Unintall app and clean and rebuild project then I think solve your problem.
Try Replaceing this, Removing the last Comma(,) from the statement
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
Remove , from last field
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null "
+ ");";
private static final String DATABASE_CREATE_SQL =
" create table " + DATABASE_TABLE
+ " ( " + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_CalorieValue + " integer not null, "
+ " ); ";
Add space " ) "