Android Database EditText NumberSigned - java

I made an android SQLDatabase with two edittext. One save the name and the other some number. This is my activity
public class AccountActivity extends ActionBarActivity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView name ;
TextView amount;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
name = (TextView) findViewById(R.id.input_name);
amount = (TextView) findViewById(R.id.input_amount);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.ACCOUNT_COLUMN_NAME));
String amo = rs.getString(rs.getColumnIndex(DBHelper.ACCOUNT_COLUMN_AMOUNT));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.btn_save);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
amount.setText((CharSequence) amo);
amount.setFocusable(false);
amount.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.menu_account, menu);
}
else{
getMenuInflater().inflate(R.menu.menu_main, 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;
}
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.btn_save);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
amount.setEnabled(true);
amount.setFocusableInTouchMode(true);
amount.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteAccount)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteAccount(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateAccount(id_To_Update, name.getText().toString(), amount.getText().length())){
Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else{
if(mydb.insertAccount(name.getText().toString(), amount.getText().length())){
}
else{
}
Intent intent = new Intent(getApplicationContext(),com.tubapps.accountdb.MainActivity.class);
startActivity(intent);
}
}
}
}
And this is my xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E0EEEE"
tools:context="com.tubapps.accountdb.AccountActivity">
<EditText
android:id="#+id/input_name"
android:layout_width="fill_parent"
android:inputType="text"
android:layout_height="wrap_content"
android:hint="#string/account_name"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip" />
<EditText
android:id="#+id/input_amount"
android:layout_width="fill_parent"
android:inputType="numberSigned"
android:layout_height="wrap_content"
android:hint="#string/initial_value"
android:layout_below="#+id/input_name"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:adjustViewBounds="true"
android:orientation="horizontal"
android:showDividers="middle">
<Button
android:id="#+id/btn_cnc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FFFFFF"
android:clickable="true"
android:focusable="true"
android:text="#string/cancel" />
<Button
android:id="#+id/btn_save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="run"
android:background="#FFFFFF"
android:text="#string/save_income" />
</LinearLayout>
</RelativeLayout>
And this is my DBHelper.
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String ACCOUNT_TABLE_NAME = "accounts";
public static final String ACCOUNT_COLUMN_ID = "id";
public static final String ACCOUNT_COLUMN_NAME = "name";
public static final String ACCOUNT_COLUMN_AMOUNT = "amount";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table accounts " +
"(id integer primary key, name text,amount integer)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS accounts");
onCreate(db);
}
public boolean insertAccount (String name, Integer amount)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("amount", amount);
db.insert("accounts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from accounts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, ACCOUNT_TABLE_NAME);
return numRows;
}
public boolean updateAccount (Integer id, String name, Integer amount)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("amount", amount);
db.update("accounts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteAccount (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("accounts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllAccounts()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from accounts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(ACCOUNT_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
When I insert a number it saves just the number 3. I don't know where is the problem.

You are getting the "length" of the number, not the value on these lines:
amount.getText().length()
I suspect you should be doing something like:
Integer.valueOf(amount.getText())

Related

Search and display entries in SQLite Database

So I recently got into Android programming and have been following this tutorial on how to insert, update, delete and view data in an SQLite database. Now, I would also like to add a search functionality to this SQLite database where I can search for a name (the columns I'm using are name, contact and DOB) and if the searched for name matches an existing one in the database, display this row/entry from the database in the application. I figured this could be done in a similar way as the viewing/updating the database, so I tried coming up with a solution for this with these as reference, however after having tried a good amount of ways that seemed reasonable to me I still haven't gotten it to work, so I'd greatly appreciate any help with this! I feel like I was close w/ some of my attempts but something with the logic didn't click completely.
MainActivity.java:
package com.example.sqliteapplication;
import ...
public class MainActivity extends AppCompatActivity {
EditText name, contact, dob;
Button insert, update, delete, view, search;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
contact = findViewById(R.id.contact);
dob = findViewById(R.id.dob);
insert = findViewById(R.id.btnInsert);
update = findViewById(R.id.btnUpdate);
delete = findViewById(R.id.btnDelete);
view = findViewById(R.id.btnView);
search = findViewById(R.id.btnSearch);
DB = new DBHelper(this);
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nameTXT = name.getText().toString();
String contactTXT = contact.getText().toString();
String dobTXT = dob.getText().toString();
Boolean checkinsertdata = DB.insertuserdata(nameTXT, contactTXT, dobTXT);
if(checkinsertdata==true)
Toast.makeText(MainActivity.this, "New Entry Inserted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "New Entry Not Inserted", Toast.LENGTH_SHORT).show();
} });
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nameTXT = name.getText().toString();
String contactTXT = contact.getText().toString();
String dobTXT = dob.getText().toString();
Boolean checkupdatedata = DB.updateuserdata(nameTXT, contactTXT, dobTXT);
if(checkupdatedata==true)
Toast.makeText(MainActivity.this, "Entry Updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "New Entry Not Updated", Toast.LENGTH_SHORT).show();
} });
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nameTXT = name.getText().toString();
Boolean checkudeletedata = DB.deletedata(nameTXT);
if(checkudeletedata==true)
Toast.makeText(MainActivity.this, "Entry Deleted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Entry Not Deleted", Toast.LENGTH_SHORT).show();
} });
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor res = DB.getdata();
if(res.getCount()==0){
Toast.makeText(MainActivity.this, "No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("Name :"+res.getString(0)+"\n");
buffer.append("Contact :"+res.getString(1)+"\n");
buffer.append("Date of Birth :"+res.getString(2)+"\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("User Entries");
builder.setMessage(buffer.toString());
builder.show();
} });
}
}
DBHelper.java:
package com.example.sqliteapplication;
import ...
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "Userdata.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create Table Userdetails(name TEXT primary key," +
"contact TEXT, dob TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
DB.execSQL("drop Table if exists Userdetails");
}
public Boolean insertuserdata(String name, String contact, String dob) {
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("contact", contact);
contentValues.put("dob", dob);
long result = DB.insert("Userdetails",
null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Boolean updateuserdata(String name, String contact, String dob) {
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("contact", contact);
contentValues.put("dob", dob);
Cursor cursor = DB.rawQuery(
"Select * from Userdetails where name = ?", new String[]{name});
if (cursor.getCount() > 0) {
long result = DB.update("Userdetails",
contentValues, "name=?",
new String[]{name});
if (result == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public Boolean deletedata(String name) {
SQLiteDatabase DB = this.getWritableDatabase();
Cursor cursor = DB.rawQuery(
"Select * from Userdetails where name = ?", new String[]{name});
if (cursor.getCount() > 0) {
long result = DB.delete("Userdetails", "name=?",
new String[]{name});
if (result == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public Cursor getdata () {
SQLiteDatabase DB = this.getWritableDatabase();
Cursor cursor = DB.rawQuery(
"Select * from Userdetails ", null);
return cursor;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity">
<TextView
android:id="#+id/texttitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please enter details below"
android:textSize="24dp"
android:layout_marginTop="20dp"
/>
<EditText
android:id="#+id/name"
android:hint="Name"
android:textSize="24dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/texttitle"
android:inputType="textPersonName"
/>
<EditText
android:id="#+id/contact"
android:hint="Contact"
android:textSize="24dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:inputType="number"
/>
<EditText
android:id="#+id/dob"
android:hint="Date of Birth"
android:textSize="24dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/contact"
android:inputType="number"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnInsert"
android:textSize="24dp"
android:text="Insert New Data"
android:layout_marginTop="30dp"
android:layout_below="#+id/dob"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnUpdate"
android:textSize="24dp"
android:text="Update Data"
android:layout_below="#+id/btnInsert"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnDelete"
android:textSize="24dp"
android:text="Delete Data"
android:layout_below="#+id/btnUpdate"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnView"
android:textSize="24dp"
android:text="View Data"
android:layout_below="#+id/btnDelete"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnSearch"
android:textSize="24dp"
android:text="Search Data"
android:layout_below="#+id/btnView"
/>
</RelativeLayout>
Sorry in advance for perhaps some bad explanations/something not making sense, I'm only a few weeks into this and got a lot to learn for sure! Thanks
You can modify getdata() so that it takes as an argument the name, or part of the name that you search for:
public Cursor getdata(String name) {
SQLiteDatabase DB = this.getWritableDatabase();
String sql = "Select * from Userdetails";
String[] selectionArgs = null;
if (name != null) {
sql += " where name LIKE '%' || ? || '%'";
selectionArgs = new String[] {name};
}
return DB.rawQuery(sql, selectionArgs);
}
and you should also modify in the listener of the button view the call to getdata() to pass null so that you get as result all the rows of the table:
Cursor res = DB.getdata(null);
Then you create the listener for the button search:
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchName = name.getText().toString().trim();
if (searchName.length() == 0) return;
Cursor res = DB.getdata(searchName);
if(res.getCount()==0){
Toast.makeText(MainActivity.this, "No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("Name :"+res.getString(0)+"\n");
buffer.append("Contact :"+res.getString(1)+"\n");
buffer.append("Date of Birth :"+res.getString(2)+"\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("User Entries");
builder.setMessage(buffer.toString());
builder.show();
}
});
Note that there is no need to query the table before you insert, update, delete a row.
You can perform the operation that you want and then examine the result of the method insert() or update() or delete() to decide whether it was successful or not.
Remember that only insert() returns -1 if unsuccessful.
update() and delete() return the number of affected (updated/deleted) rows.
So, I would write the code like this:
package com.example.sqliteapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "Userdata.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create Table Userdetails(name TEXT primary key, contact TEXT, dob TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase DB, int oldVersion, int newVersion) {
DB.execSQL("drop Table if exists Userdetails");
}
public Boolean insertuserdata(String name, String contact, String dob) {
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("contact", contact);
contentValues.put("dob", dob);
long result = DB.insert("Userdetails", null, contentValues);
return (result != -1);
}
public Boolean updateuserdata(String name, String contact, String dob) {
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("contact", contact);
contentValues.put("dob", dob);
long result = DB.update("Userdetails", contentValues, "name = ?", new String[]{name});
return (result > 0);
}
public Boolean deletedata(String name) {
SQLiteDatabase DB = this.getWritableDatabase();
long result = DB.delete("Userdetails", "name = ?", new String[]{name});
return (result > 0);
}
public Cursor getdata(String name) {
SQLiteDatabase DB = this.getWritableDatabase();
String sql = "Select * from Userdetails";
String[] selectionArgs = null;
if (name != null) {
sql += " where name LIKE '%' || ? || '%'";
selectionArgs = new String[] {name};
}
return DB.rawQuery(sql, selectionArgs);
}
}
and for the activity class:
package com.example.sqliteapplication;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name, contact, dob;
Button insert, update, delete, view, search;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
contact = findViewById(R.id.contact);
dob = findViewById(R.id.dob);
insert = findViewById(R.id.btnInsert);
update = findViewById(R.id.btnUpdate);
delete = findViewById(R.id.btnDelete);
view = findViewById(R.id.btnView);
search = findViewById(R.id.btnSearch);
DB = new DBHelper(this);
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nameTXT = name.getText().toString().trim();
String contactTXT = contact.getText().toString().trim();
String dobTXT = dob.getText().toString().trim();
Boolean checkinsertdata = DB.insertuserdata(nameTXT, contactTXT, dobTXT);
if(checkinsertdata==true)
Toast.makeText(MainActivity.this, "New Entry Inserted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "New Entry Not Inserted", Toast.LENGTH_SHORT).show();
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nameTXT = name.getText().toString().trim();
String contactTXT = contact.getText().toString().trim();
String dobTXT = dob.getText().toString().trim();
Boolean checkupdatedata = DB.updateuserdata(nameTXT, contactTXT, dobTXT);
if(checkupdatedata==true)
Toast.makeText(MainActivity.this, "Entry Updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "New Entry Not Updated", Toast.LENGTH_SHORT).show();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nameTXT = name.getText().toString().trim();
Boolean checkudeletedata = DB.deletedata(nameTXT);
if(checkudeletedata==true)
Toast.makeText(MainActivity.this, "Entry Deleted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Entry Not Deleted", Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor res = DB.getdata(null);
if(res.getCount()==0){
Toast.makeText(MainActivity.this, "No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("Name :"+res.getString(0)+"\n");
buffer.append("Contact :"+res.getString(1)+"\n");
buffer.append("Date of Birth :"+res.getString(2)+"\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("User Entries");
builder.setMessage(buffer.toString());
builder.show();
}
});
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchName = name.getText().toString().trim();
if (searchName.length() == 0) return;
Cursor res = DB.getdata(searchName);
if(res.getCount()==0){
Toast.makeText(MainActivity.this, "No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("Name :"+res.getString(0)+"\n");
buffer.append("Contact :"+res.getString(1)+"\n");
buffer.append("Date of Birth :"+res.getString(2)+"\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("User Entries");
builder.setMessage(buffer.toString());
builder.show();
}
});
}
}
In DBHelper.java add:
public Cursor getDataByName(String name){
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("SELECT * FROM Userdetails WHERE name LIKE '%"+name+"'%", null);
}
In MainActivity.java:
Add a new global EditText:
EditText name, contact, dob, **search**;
onCreate() add:
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
searchInDatabase();
}
}
Somewhere in your MainActivity.java add this new method.
private void searchInDatabaseByName(){
Cursor res = DB.getDataByName(name.getText().toString());
if(res.getCount()==0){
Toast.makeText(MainActivity.this, "No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}
Cursor res = DB.getdata();
if(res.getCount()==0){
Toast.makeText(MainActivity.this, "No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){
buffer.append("Name :"+res.getString(0)+"\n");
buffer.append("Contact :"+res.getString(1)+"\n");
buffer.append("Date of Birth :"+res.getString(2)+"\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setTitle("User Entries");
builder.setMessage(buffer.toString());
builder.show();
}
Now the explanation:
In sqlite you can query for data using the LIKE keyword. for example in order to find all the rows with the name 'Bob' you can query for
SELECT * FROM Userdetails WHERE name LIKE '%Bob%'
Then, the returned cursor will contain all the rows that have the name Bob.
Then we've added another EditText variable to search (you'll need to add it to the main_acitivity.xml as well).
Now you can use that to type in the name you want to search and then click the 'search' button, which in return will call the 'searchInDatabaseByName' method which does the exact same thing as your 'view' button but simply goes to our new DBHelper method 'getDataByName'.
Please notice that its recommended to let the DBHelper do all the stuff of fetching the actual data (meaning it will get the cursor and also parse it)
You might want to create a model class for your User entity.
and then the database method will return an arraylist of users which will later be much easier to show in a Dialog (or even better, in a ListView)

RecyclerView only adds one item in the List instead of adding all the entries

I am trying to build an app using where entries are stored in a sqlitedatabase and the mainactivity contains recyclerview which displays the entries from the database. The problem is that the recyclerview displays only the first entry that has been entered.
For example if the first entry is "A" and the second entry is "B", the recyclerview only displays "A" and not "B"
The Code for the recyclerview adapter is given below :
RecyclerView Adapter
public class PasswordRecyclerViewAdapter extends RecyclerView.Adapter<PasswordRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<String> accounts;
private int position;
public PasswordRecyclerViewAdapter() {
}
public PasswordRecyclerViewAdapter(Context context, List<String> accounts) {
this.context = context;
this.accounts = accounts;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(R.layout.linear_layout_simple_text, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.title.setText(accounts.get(position));
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = accounts.get(position);
Intent intent=new Intent(context, DetailsActivity.class);
intent.putExtra("Site",data);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return accounts.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textview_title);
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String SHARED_PREFS_NAME="MyPrefs";
private RecyclerView recyclerView;
TextView emptyText;
PasswordRecyclerViewAdapter adapter;
List<String> collection;
List<String> myList=new ArrayList<String>();
PasswordDatabase passwordDatabase;
AdapterView.AdapterContextMenuInfo info;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
passwordDatabase = new PasswordDatabase(getApplicationContext());
myList = getArray();
collection = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.listViewID);
emptyText = (TextView)findViewById(R.id.text2);
adapter = new PasswordRecyclerViewAdapter(this, myList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
registerForContextMenu(recyclerView);
}
public List<String> getArray(){
/*SharedPreferences sp=this.getSharedPreferences(SHARED_PREFS_NAME,Activity.MODE_PRIVATE);
Set<String> set=sp.getStringSet("list",new HashSet<String>());
return new ArrayList<String>(set);*/
List accounts=passwordDatabase.getAcc();
return accounts;
}
}
In the function getArray() in MainActivity, the passwordDatabase.getAcc() returns the list of items stored in the sqlitedatabase. The code for the sqlitedatabase helper class is given below :
public final class PasswordDatabase extends SQLiteOpenHelper {
String data1;
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserCredentials.db";
public static final String TABLE_NAME = "Credentials";
public static final String COLUMN_PASSWORD = "Password";
public static final String COLUMN_ACCOUNT = "Account";
public static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TABLE_NAME;
private static final String TABLE_CREATE = "CREATE TABLE "
+ TABLE_NAME + " (" + COLUMN_ACCOUNT + " TEXT, " + COLUMN_PASSWORD
+ " TEXT,UNIQUE("+ COLUMN_ACCOUNT + "));";
public PasswordDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion){
onUpgrade(db, oldVersion, newVersion);
}
public void addCredentials(Context context,String account, String password){
SQLiteDatabase db = this.getWritableDatabase();
long newRowId=0;
Boolean flag=false;
ContentValues values = new ContentValues();
values.put(COLUMN_ACCOUNT, account);
values.put(COLUMN_PASSWORD, password);
newRowId = db.insert(TABLE_NAME, null, values);
}
public void deleteRow(String account){
SQLiteDatabase db=this.getWritableDatabase();
String whereClause=COLUMN_ACCOUNT+"=?";
String[] whereArgs=new String[] {account};
db.delete(TABLE_NAME,whereClause,whereArgs);
}
public void modify(String account,String pass){
SQLiteDatabase db=this.getWritableDatabase();
String sql="UPDATE "+ TABLE_NAME +" SET " +COLUMN_PASSWORD +" = " +pass + " WHERE "+ COLUMN_ACCOUNT +" = " + account;
db.execSQL(sql);
}
public int modifyCredentials(String account,String newPass){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COLUMN_PASSWORD,newPass);
String whereClause=COLUMN_ACCOUNT + " =?";
String[] whereArgs=new String[]{account};
int update=db.update(TABLE_NAME,contentValues,whereClause,whereArgs);
return update;
}
public void deleteAllCredentials(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
}
public boolean checkdb(){
SQLiteDatabase db;
db=this.getWritableDatabase();
Cursor cursor=db.rawQuery("SELECT * FROM"+TABLE_NAME,null);
Boolean rowExists;
if (cursor.moveToFirst()){
rowExists=false;
}
else {
rowExists=true;
}
return rowExists;
}
public List<String> getAcc(){
SQLiteDatabase db=this.getReadableDatabase();;
List<String> collection=new ArrayList<>();
String acc=null;
Cursor c=null;
try{
String query="SELECT " + COLUMN_ACCOUNT + " FROM " + TABLE_NAME;
c=db.rawQuery(query,null);
if(c!=null){
if(c.moveToFirst()){
do{
acc=c.getString(c.getColumnIndex(COLUMN_ACCOUNT));
collection.add(acc);
}
while (c.moveToNext());
}
}
}
finally {
if(c!=null){
c.close();
}
if(db!=null){
db.close();
}
}
return collection;
}
public String getData(String data){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { COLUMN_ACCOUNT,COLUMN_PASSWORD
}, COLUMN_ACCOUNT + " = ?", new String[] { data },
null, null, null, null);
if (cursor!=null && cursor.moveToFirst()){
do{
data1=cursor.getString(1);
}while (cursor.moveToNext());
}
return data1;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.nitsilchar.hp.passwordStorage.activity.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/listViewID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#9fece2"
android:dividerHeight="0.5dp">
</android.support.v7.widget.RecyclerView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:text="#string/main_xml_empty_text"/>
</RelativeLayout>
Can anyone help me for displaying all the entries stored in the database rather than only one entry
make sure your linear_layout_simple_text layout height to android:layout_height="wrap_content"
like below code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

Display SQLite data in Android tablelayout

Im trying to retrieve data from SQLite database table and display as tablelayout in android. However it only display the title and the textview. What is wrong with the codes?
Graf.java
public class Graf extends AppCompatActivity {
DatabaseHelper myDb;
TextView dt, water, inc;
TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graf);
myDb=new DatabaseHelper(this);
dt=(TextView)findViewById(R.id.date);
water=(TextView)findViewById(R.id.water);
inc=(TextView)findViewById(R.id.inc);
tableLayout=(TableLayout)findViewById(R.id.tableLayout1);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final String date=getDate();
Toast.makeText(getApplicationContext(),date, Toast.LENGTH_SHORT).show();
BuildTable(date);
}
private void BuildTable(String date){
Cursor c=myDb.readEntry(date);
int rows=c.getCount();
int cols=c.getColumnCount();
c.moveToFirst();
for (int i=0;i<rows;i++){
TableRow row=new TableRow(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
for (int j=0;j<cols;j++){
TextView tv=new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tv.setBackgroundResource(R.drawable.cell_shape);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0,5,0,5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
tableLayout.addView(row);
}
}
/*public void getData(){
buttonA.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
showMessage("Ralat", "Tiada Rekod.");
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Tarikh : " + res.getString(1) + "\n");
buffer.append("Air Diminum : " + res.getString(2) + "\n");
buffer.append("Pencapaian : " + res.getString(3) + "\n\n");
showMessage("Laporan", buffer.toString());
}
}
});
}
public void showMessage(String title, String message){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}*/
#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_graf, menu);
return true;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
#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);
}
}
activity_graf.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context="info.androidhive.materialdesign.activity.Graf">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="45dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="LAPORAN MINGGUAN ANDA"
android:id="#+id/textView7"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tarikh" />
<TextView
android:id="#+id/water"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Penambahan Air" />
<TextView
android:id="#+id/inc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Peningkatan Peratus" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
</TableLayout>
</ScrollView>
</LinearLayout>
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper myDb;
SQLiteDatabase db = this.getWritableDatabase();
public static final String DATABASE_NAME = "HU.db";
public static final String TABLE_NAME = "User_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_4 = "GENDER";
public static final String COL_5 = "WEIGHT";
public static final String COL_6 = "HEIGHT";
public static final String COL_7 = "ACTIVENESS";
public static final String COL_8 = "TARGET";
public static final String TABLE2_NAME = "Drink_Table";
public static final String COL2_1 = "DRINK_ID";
public static final String COL2_2 = "DATE";
public static final String COL2_3 = "AMOUNT";
public static final String COL2_4 = "PERCENT";
public static final String COL2_5 = "ID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, GENDER TEXT, WEIGHT DOUBLE, HEIGHT DOUBLE, ACTIVENESS INTEGER, TARGET DOUBLE)");
db.execSQL("create table " + TABLE2_NAME + " (DRINK_ID INTEGER PRIMARY KEY AUTOINCREMENT, DATE DATETIME DEFAULT CURRENT_DATE, AMOUNT DOUBLE, PERCENT DOUBLE, ID INTEGER, FOREIGN KEY(ID) REFERENCES " + TABLE_NAME + "(ID))");
db.execSQL("create table "+TABLE3_NAME+" (Entry_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , ID INTEGER, DATE DATETIME DEFAULT CURRENT_DATE, TOTALAMOUNT DOUBLE, TOTAL PERC DOUBLE, FOREIGN KEY(DATE) REFERENCES "+TABLE2_NAME+"(DATE), FOREIGN KEY(ID) REFERENCES "+TABLE_NAME+"(ID))");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String gender, String weight, String height, String activeness, String target) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_4, gender);
contentValues.put(COL_5, weight);
contentValues.put(COL_6, height);
contentValues.put(COL_7, activeness);
contentValues.put(COL_8, target);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean updateData(String id, String name, String gender, String weight, String height, String activeness, String target) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(COL_2, name);
contentValues.put(COL_4, gender);
contentValues.put(COL_5, weight);
contentValues.put(COL_6, height);
contentValues.put(COL_7, activeness);
contentValues.put(COL_8, target);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
return true;
}
public boolean addWater(String date, String id, double amount) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
double target = getTargetu(id);
contentValues.put(COL2_2, date);
contentValues.put(COL2_3, amount);
contentValues.put(COL2_4, (amount / target) * 100);
contentValues.put(COL2_5, id);
long result = db.insert(TABLE2_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor readEntry(String date) {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = ("SELECT DATE, AMOUNT, PERCENT FROM "+TABLE2_NAME+"WHERE DATE= ?");
Cursor c = db.query(TABLE2_NAME,new String[]{COL2_2,COL2_3,COL2_4},COL2_2+"=?", new String[] { String.valueOf(date)}, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
I think the problem is with picking wrong layout params. Should be:
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
Table layout requires table Layout params.

Can somebody help me solve the database?

Hello everybody i m building an android application which has timepicker. what i want is that i want to update the database when user clicks the save button twice. Please guide me how to do that. Now my application crashes because no updation of database takes place.
TimeTable.java
public class Monday extends FragmentActivity implements TimePickerFragment.TimePickerDialogListener {
EditText et1, et2, et3;
TextView tvm;
LinearLayout llm;
int fhour, fmin, thour, tmin, j;
private int cnt = 0;
View vi[] = new View[100];
TimeTableDbHelper db;
String txt,fmeridien,tmeridien,ftime,ttime;
private static final int START_TIME_PICKER_ID = 1;
private static final int END_TIME_PICKER_ID = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_monday);
tvm = (TextView) findViewById(R.id.tvm);
llm = (LinearLayout) findViewById(R.id.llm);
db = new TimeTableDbHelper(this);
cnt = db.check("timetableM");
if (cnt > 0) {
int i;
for (i = 0; i < cnt; i++) {
LinearLayout mn = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, mn, false);
vi[i] = view;
mn.addView(view);
et1 = (EditText) vi[i].findViewById(R.id.txtTime);
et1.setText(db.rd1(i,1));
//Log.i("Monday", "Database read" + db.read(2) + db.read(3));
et2 = (EditText) vi[i].findViewById(R.id.txtTime2);
et2.setText(db.rd1(i,2));
//Log.i("Monday", "Database read" + db.read(4) + db.read(5));
et3 = (EditText) vi[i].findViewById(R.id.txtSet);
et3.setText(db.rd1(i,3));
}
j = i;
} else {
j = 0;
}
}
#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_monday, 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
return super.onOptionsItemSelected(item);
}
public void setTime(View v) {
LinearLayout main = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, main, false);
view.setTag(j);
main.addView(view);
vi[j] = view;
}
public void setTime2(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(START_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
public void setTime3(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(END_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
#Override
public void onTimeSet(int id, TimePicker view, int hourOfDay, int minute) {
Log.i("TimePicker", "Time picker set from id " + id + "!");
if (id == START_TIME_PICKER_ID) {
et1 = (EditText) vi[j].findViewById(R.id.txtTime);
fmin = minute;
if(hourOfDay <= 12) {
fhour = hourOfDay;
fmeridien = "AM";
} else {
fhour = hourOfDay-12;
fmeridien = "PM";
}
ftime =fhour + ":" + fmin + fmeridien;
et1.setText(ftime);
} else {
et2 = (EditText) vi[j].findViewById(R.id.txtTime2);
tmin = minute;
if(hourOfDay < 12) {
thour = hourOfDay;
tmeridien = "AM";
} else {
thour = hourOfDay-12;
tmeridien = "PM";
}
ttime = thour + ":" + tmin +tmeridien;
et2.setText(ttime);
}
}
public void Save(View v)
{
int position = (int) v.getTag();
if(position<j);
else {
et3 = (EditText) vi[j].findViewById(R.id.txtSet);
txt = et3.getText().toString();
Log.i("Position", "Value is " + position);
db.write1(j, ftime, ttime, txt);
Toast.makeText(this, "Successfully saved", Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
int day = c.get(Calendar.DAY_OF_WEEK);
int value;
if(fmeridien=="AM") value=0;
else value=1;
c.set(Calendar.DAY_OF_WEEK,day);
c.set(Calendar.AM_PM, value);
c.set(Calendar.HOUR, fhour);
c.set(Calendar.MINUTE, fmin);
c.set(Calendar.SECOND,0);
Intent i = new Intent("com.example.annu.sheduler.DisplayNotification");
//---assign an ID of 1---
i.putExtra("NotifID", j);
i.putExtra("text",txt);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), j, i, 0);
j++;
//---sets the alarm to trigger---
alarmManager.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), displayIntent);}
}
}
activity_monday.xml
<LinearLayout android:id="#+id/llm"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.annu.sheduler.Monday"
android:background="#ffffa751"
android:label="Monday">
<TextView
android:id="#+id/tvm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setTime"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:text="Create a schedule"
android:textStyle="bold"
android:textSize="24sp"/>
</LinearLayout>
activity_timepicker.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txtTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="From"
android:onClick="setTime2"/>
<EditText
android:id="#+id/txtTime2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="To"
android:onClick="setTime3"/>
<EditText
android:id="#+id/txtSet"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".40"
android:hint="Description!!!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="Save"
android:minHeight="0dp"
android:minWidth="20dp"/>
</LinearLayout>
TimeTableDbHelper.java
public class TimeTableDbHelper extends SQLiteOpenHelper {
public static final String TABLE_NAMEM = "timetableM";
public static final String COLUMN_NO1 = "c_no1";
public static final String COLUMN_FROM_TIME1 = "FTIME1";
public static final String COLUMN_TO_TIME1 = "TTIME1";
public static final String COLUMN_DESC1 = "Description1";
private static final int DATABASE_VERSION = 1;
static final String DATABASE_NAME = "TimeTable.db";
public TimeTableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_TIME_TABLE1 = "CREATE TABLE " + TABLE_NAMEM + " (" +
COLUMN_NO1 + " INTEGER PRIMARY KEY, " +
COLUMN_FROM_TIME1 + " STRING NOT NULL," +
COLUMN_TO_TIME1 + " STRING NOT NULL," +
COLUMN_DESC1 + " TEXT NOT NULL" +
" );";
sqLiteDatabase.execSQL(SQL_CREATE_TIME_TABLE1);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAMEM);
onCreate(sqLiteDatabase);
}
public void write1(int column_no, String ftime, String ttime, String desc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NO1, column_no);
values.put(COLUMN_FROM_TIME1, ftime);
values.put(COLUMN_TO_TIME1, ttime);
values.put(COLUMN_DESC1, desc);
Boolean res = CheckIsDataAlreadyInDBorNot(TABLE_NAMEM, COLUMN_NO1, column_no);
if (res == false) db.insert(TABLE_NAMEM, null, values);
else db.update(TABLE_NAMEM, values, null, null);
db.close();
}
public int check(String tname) {
SQLiteDatabase db = this.getWritableDatabase();
String count = "SELECT count(*) FROM " + tname;
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
public String rd1(int c_no, int col) {
String selectQuery = "SELECT * FROM " + TABLE_NAMEM + " WHERE " + COLUMN_NO1 + " = " + c_no;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String data = "";
if (cursor.moveToFirst()) {
// get the data into array,or class variable
do {
data = cursor.getString(col);
//Log.i("TimeTableDbHelper", "Value read " + cursor.getString(6));
} while (cursor.moveToNext());
}
db.close();
return data;
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, int fieldValue) {
SQLiteDatabase db = this.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
}
As stated here
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#update(java.lang.String,%20android.content.ContentValues,%20java.lang.String,%20java.lang.String[]):
Returns:
the number of rows affected
So you can do just:
if (db.update(TABLE_NAMEM, values, null, null) == 0)
db.insert(TABLE_NAMEM, null, values);
db.close();

Android - Import database get nullpointerexception on rawquery

I followed this tutorial to import database. Then I try to read the data using ArrayList to display them in listview. But I got nullpointer exception on my rawQuery saying it is invoking a null object reference.
DB.java
public class DB extends SQLiteOpenHelper {
//The Android's default system path of your application database.
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
private static String TABLE_LOCATION = "Frasa";
private final Context context;
private SQLiteDatabase db;
// constructor
public DB(Context context) {
super( context , DB_NAME , null , 1);
this.context = context;
}
// Creates a empty database on the system and rewrites it with your own database.
public void create() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
// By calling this method and empty database will be created into the default system path
// of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// Check if the database exist to avoid re-copy the data
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String path = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
// database don't exist yet.
e.printStackTrace();
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
// copy your assets db to the new system DB
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
//Open the database
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch(SQLException sqle) {
db = null;
return false;
}
}
#Override
public synchronized void close() {
if(db != null)
db.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// PUBLIC METHODS TO ACCESS DB CONTENT
// -----------------------------------------------------------------------------------------------------------------
public ArrayList<Frasa> getFrasa(String situation) {
//ArrayList of Frasa class objects
ArrayList<Frasa> arrFrasa = null;
//String query = "SELECT * FROM Frasa WHERE Situation = " + situation;
String selectQuery = "SELECT " +
Frasa.KEY_ID + "," +
Frasa.KEY_PHRASE + "," +
Frasa.KEY_TRANSLATE + "," +
Frasa.KEY_PRONOUNCE +
" FROM " + TABLE_LOCATION + " WHERE situation = " +situation;
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
Cursor curFrasa = db.rawQuery(selectQuery, null);
if (curFrasa != null && curFrasa.moveToFirst()) {
arrFrasa = new ArrayList<Frasa>();
while (curFrasa.isAfterLast() == false) {
//Frasa is a class with list of fields
Frasa fra = new Frasa();
fra.setId(curFrasa.getInt(curFrasa.getColumnIndex(Frasa.KEY_ID)));
fra.setPhrase(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PHRASE)));
fra.setTranslate(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_TRANSLATE)));
fra.setPronounce(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PRONOUNCE)));
arrFrasa.add(fra);
curFrasa.moveToNext();
}
}
curFrasa.close();
db.close();
return arrFrasa;
}
}
Frasa.java (Database table and columns)
public class Frasa {
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_PHRASE = "phrase";
public static final String KEY_TRANSLATE = "translate";
public static final String KEY_PRONOUNCE = "pronounce";
// property help us to keep data
public int id;
public String situation;
public String phrase;
public String translate;
public String pronounce;
public Frasa() {
}
public Frasa(int id, String situation, String phrase, String translate, String pronounce) {
this.id = id;
this.situation = situation;
this.phrase = phrase;
this.translate = translate;
this.pronounce = pronounce;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhrase() {
return phrase;
}
public void setPhrase(String phrase) {
this.phrase = phrase;
}
public String getTranslate() {
return translate;
}
public void setTranslate(String translate) {
this.translate = translate;
}
public String getPronounce() {
return pronounce;
}
public void setPronounce(String pronounce) {
this.pronounce = pronounce;
}
}
public class GreetingAdapter extends ArrayAdapter<Frasa> {
Context context;
int layoutResourceId;
ArrayList<Frasa> data = new ArrayList<Frasa>();
public GreetingAdapter(Context context, int layoutResourceId, ArrayList<Frasa> data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textPhrase = (TextView) row.findViewById(R.id.textViewPhrase);
holder.textTranslate = (TextView) row.findViewById(R.id.textViewTranslate);
holder.btnSpeak = (Button) row.findViewById(R.id.buttonSpeak);
holder.btnRecord = (Button) row.findViewById(R.id.buttonRecord);
holder.btnPlay = (Button) row.findViewById(R.id.buttonPlay);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
Frasa frasa = data.get(position);
holder.textPhrase.setText(frasa.getPhrase());
holder.textTranslate.setText(frasa.getTranslate());
holder.btnSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Speak button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Play Button Clicked", "**********");
Toast.makeText(context, "Playing recorded audio",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textPhrase;
TextView textTranslate;
Button btnSpeak;
Button btnRecord;
Button btnPlay;
}
}
activity_list_greetings.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txt_header"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Greetings"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/black" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listGreetings"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/txt_header" />
list_item_greet.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewPhrase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phrase"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_above="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonSpeak"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Speak"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonRecord"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSpeak"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Record"
android:textColor="#0099CC" />
<Button
android:id="#+id/buttonPlay"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonRecord"
android:layout_marginTop="3dp"
android:background="#FFFFFF"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Play"
android:textColor="#0099CC" />
<TextView
android:id="#+id/textViewTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Translate"
android:textSize="20sp"
android:textColor="#color/background_material_dark"
android:layout_below="#+id/buttonRecord"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
ListGreetings.java
public class ListGreetings extends ActionBarActivity {
TextView txtPhrase, txtTranslate;
Button speakButton;
MediaPlayer pronounce;
ListView userList;
GreetingAdapter greetAdapter;
//ArrayList<Frasa> frasaArray = new ArrayList<Frasa>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_greetings);
DB db = new DB(this);
db.open();
//get Frasa data
ArrayList<Frasa> frasaArray = db.getFrasa("Greetings");
/**
* set item into adapter
*/
greetAdapter = new GreetingAdapter(ListGreetings.this, R.layout.list_item_greet, frasaArray);
userList = (ListView) findViewById(R.id.listGreetings);
userList.setItemsCanFocus(false);
userList.setAdapter(greetAdapter);
}
#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_list_greetings, 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);
}
}
Is it my way of calling getFrasa wrong? Or the database cannot be detected? I'm sure I already pushed the database file to both assets folder & inside the package. Sorry, if I'm not formatting the codes correctly. Thanks in advance for any help.
The problem is that you are trying to open the Database from a different location
private static String DB_PATH = "data/data/hairulhazri.malayforyou/databases/";
private static String DB_NAME = "malayforyou";
...
...
db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
db is returning NULL because your database is stored in /assets folder not in "data/data/hairulhazri.malayforyou/databases/"

Categories