I need a serious help, my app is working fine until now. I am doing a project using sqLite database and displaying the search result. I used TextView to display search result and it worked fine but when i use ListView to display it crashes when i scroll it. Need help.......
My code in
SearchCustomer.java
public class SearchCustomer extends Activity {
Button searchCustomer;
String errormsg = "No Result Found";
String[] nameCus;
ListView Cusinfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_customer);
searchCustomer = (Button) findViewById(R.id.Bsearch);
Cusinfo = (ListView) findViewById(R.id.cusinfoList);
final AutoCompleteTextView CustomerName = (AutoCompleteTextView) findViewById(R.id.CustomerName);
final Customer name = new Customer(this);
searchCustomer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String CustomerNam = CustomerName.getText().toString().trim();
name.open();
nameCus = name.getDetails(CustomerNam);
name.close();
ListAdapter cus = new ArrayAdapter<>(SearchCustomer.this, android.R.layout.simple_list_item_1, nameCus);
Cusinfo.setAdapter(cus);
Cusinfo.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String det = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(SearchCustomer.this, det, Toast.LENGTH_LONG).show();
}
});
}else{
Toast.makeText(SearchCustomer.this, errormsg, Toast.LENGTH_LONG).show();
}
});
}
}
My code in Customer.java
public class Customer {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "cus_name";
public static final String KEY_PHONE = "cus_phone";
public static final String KEY_ADDRESS = "cus_address";
public static final String KEY_DATE = "cus_date";
public static final String KEY_DETAILS = "cus_details";
public static final String KEY_AMOUNT = "cus_amount";
public static final String KEY_SRI = "cus_sri";
private static final String DATABASE_NAME = "Customerdb";
private static final String DATABASE_TABLE = "customerTable";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private DbHelper ourHelper;
private SQLiteDatabase ourDatabase;
public String[] getDetails(String customerNam) {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_PHONE, KEY_ADDRESS, KEY_DATE, KEY_DETAILS, KEY_AMOUNT, KEY_SRI};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_PHONE + "=?",
new String[]{customerNam}, null, null, null, null);
String[] result = new String[100];
int i = 0;
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iPhone = c.getColumnIndex(KEY_PHONE);
int iAddress = c.getColumnIndex(KEY_ADDRESS);
int iDate = c.getColumnIndex(KEY_DATE);
int iDetails = c.getColumnIndex(KEY_DETAILS);
int iAmount = c.getColumnIndex(KEY_AMOUNT);
int iSri = c.getColumnIndex(KEY_SRI);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result[i] = c.getString(iRow) + "\n" + "Name: " + c.getString(iName) + "\n" +
"PhoneNo.: " + c.getString(iPhone) + "\n" + "Address: " + c.getString(iAddress) + "\n" +
"Date: " + c.getString(iDate) + "\n" + "Details: " + c.getString(iDetails) + "\n" +
"Amount: Rs." + c.getString(iAmount) + "\n" + "Type : " + c.getString(iSri) + "\n" + "____________________________________" + "\n";
i++;
}
return result;
}
}
My code in activity_search_customer.xml
<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="match_parent"
android:layout_margin="8dp"
android:orientation="vertical"
tools:context="com.innovation.fae.camerawork.SearchCustomer">
<TextView
android:id="#+id/textView"
style="#style/AlertDialog.AppCompat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:text="#string/enter_the_customer_name"
android:textSize="18dp" />
<AutoCompleteTextView
android:id="#+id/CustomerName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Customer Phone No."
android:inputType="phone"
android:paddingTop="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<Button
android:id="#+id/Bsearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/search"
android:textSize="18sp"
android:textStyle="italic" />
</LinearLayout>
<ListView
android:id="#+id/cusinfoList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#c3deff"
android:textColor="#001e71"
android:textSize="20sp" />
</LinearLayout>
My **Logcat**
07-15 22:38:19.825 29729-29729/com.innovation.fae.camerawork E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.innovation.fae.camerawork, PID: 29729
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsListView.obtainView(AbsListView.java:2349)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillGap(ListView.java:662)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5007)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3424)
at android.widget.AbsListView.startScrollIfNeeded(AbsListView.java:3352)
at android.widget.AbsListView.onTouchMove(AbsListView.java:3780)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3638)
at android.view.View.dispatchTouchEvent(View.java:8480)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2400)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2093)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2625)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1770)
at android.app.Activity.dispatchTouchEvent(Activity.java:2742)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2586)
at android.view.View.dispatchPointerEvent(View.java:8675)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4129)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3995)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3550)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3603)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3569)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3686)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3577)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3743)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3550)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3603)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3569)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3577)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3550)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5813)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5787)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5758)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5903)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)
at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:176)
at android.view.ViewRootImpl.doConsumeBatchedI
A list view should not be in a scrollview.
Post your logs lets see where the error is coming from.
Edit 1
I checked your getDetails method, you defined an array of 100 indexes, what if the result if more than 100, You should use an ArrayList for that or define the array with the count from your cursor
String[] result = new String[c.getCount()];
Edit 2
Error seems to be coming from
String CustomerNam = CustomerName.getText().toString().trim();
Check to see if CustomerName is not null
in my experience with ListView, I've never had it inside of a ScrollView.
it should scroll on it's own.
Related
I need help fixing a problem with my 3 buttons that don't work properly and I'm not sure how to fix it. The "Save" button is to keep my database save, the "Refresh" button is to clear, and the "Search" button is to find an existing database. My TextView shows the existing database after registered. These are my goals to accomplish.
Here are my code files:
XML File:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_verticsl_margin"
android:paddingBottom="#dimen/activity_verticsl_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dip"
android:gravity="center"
android:text="Registration"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtid"
android:hint="ID"
android:inputType="number"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtfirstname"
android:hint="#string/first_name"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtlastname"
android:hint="#string/last_name"
android:layout_marginTop="5dip"
/>
<EditText
android:id="#+id/txtmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="#string/e_mail" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtuser"
android:hint="#string/username"
android:layout_marginTop="5dip"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtpw"
android:hint="#string/password"
android:layout_marginTop="5dip"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsave"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
<Button
android:id="#+id/btnclear"
android:layout_width="212dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight=".30"
android:text="refresh"
android:textColor="#fff"
android:textSize="15dip"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="search"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsearch"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"/>
</TableLayout>
Java File StudentRegistration.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StudentRegistration {
public static final String KEY_ROWID ="_id";
public static final String KEY_FNAME = "fname";
public static final String KEY_LNAME = "lname";
public static final String KEY_EMAIL = "email";
public static final String KEY_USER ="user";
public static final String KEY_PASS ="pass";
private static final String DATABASE_NAME = "StudentDB";
private static final String DATABASE_TABLE = "StudentTbl";
private static final int DATABASE_VERSION = 1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME,
null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_FNAME + " TEXT NOT NULL, " +
KEY_LNAME + " TEXT NOT NULL, " +
KEY_EMAIL + " TEXT NOT NULL, " +
KEY_USER + " TEXT NOT NULL, " +
KEY_PASS + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
onCreate(db);
}
}
public StudentRegistration(Context c) {
ourContext = c;
}
public StudentRegistration open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long savedata(String fname, String lname, String email, String user, String pass) {
ContentValues cv = new ContentValues();
cv.put(KEY_FNAME, fname);
cv.put(KEY_LNAME, lname);
cv.put(KEY_EMAIL, email);
cv.put(KEY_USER, user);
cv.put(KEY_PASS, pass);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData(){
String[] refresh = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, refresh, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iFName = c.getColumnIndex(KEY_FNAME);
int iLName = c.getColumnIndex(KEY_LNAME);
int iEmail = c.getColumnIndex(KEY_EMAIL);
int iUser = c.getColumnIndex(KEY_USER);
int iPass = c.getColumnIndex(KEY_PASS);
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow)
+ " " + c.getString(iFName)
+ " " + c.getString(iLName)
+ " " + c.getString(iEmail)
+ " " + c.getString(iUser)
+ " " + c.getString(iPass)
+ "\n\n";
}
return result;
}
public String getFName(long l){
String[] getfname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getfname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String fname = c.getString(1);
return fname;
}
return null;
}
public String getLName(long l){
String[] getlname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getlname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String lname = c.getString(2);
return lname;
}
return null;
}
public String getEmail(long l){
String[] getemail = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getemail, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String email = c.getString(3);
return email;
}
return null;
}
public String getUser(long l){
String[] getuser = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getuser, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String user = c.getString(4);
return user;
}
return null;
}
public String getPass(long l){
String[] getpass = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getpass, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String pass = c.getString(5);
return pass;
}
return null;
}
}
and the java file MainActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText FirstName, LastName, Email, UserName, Password, ID;
Button Save, Clear, Search;
TextView TxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstName = (EditText)findViewById(R.id.txtfirstname);
LastName = (EditText)findViewById(R.id.txtlastname);
Email = (EditText)findViewById(R.id.txtmail);
UserName = (EditText)findViewById(R.id.txtuser);
Password = (EditText)findViewById(R.id.txtpw);
TxtData =(TextView)findViewById(R.id.textView);
Save =(Button)findViewById(R.id.btnsave);
Clear=(Button)findViewById(R.id.btnclear);
Search=(Button)findViewById(R.id.btnsearch);
Search.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String search = ID.getText().toString();
Long l= Long.parseLong(search);
StudentRegistration mysearch = new
StudentRegistration(MainActivity.this);
mysearch.open();
String returnedFname = mysearch.getFName(l);
String returnedLname = mysearch.getLName(l);
String returnedEmail = mysearch.getEmail(l);
String returnedUser = mysearch.getUser(l);
String returnedPass = mysearch.getPass(l);
mysearch.close();
FirstName.setText(returnedFname);
LastName.setText(returnedLname);
Email.setText(returnedEmail);
UserName.setText(returnedUser);
Password.setText(returnedPass);
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname = FirstName.getText().toString();
String lname = LastName.getText().toString();
String email = Email.getText().toString();
String user = UserName.getText().toString();
String pass = Password.getText().toString();
StudentRegistration save = new StudentRegistration(MainActivity.this);
save.open();
save.savedata(fname, lname, email, user, pass);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
Clear.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
StudentRegistration refresh = new StudentRegistration(MainActivity.this);
refresh.open();
String data = refresh.getData();
refresh.close();
TxtData.setText(data);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
}
}
My Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.classifiedinformation">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
How can I accomplish my goals?
First of all some hints about what went wrong would have been nice.
You need to initialize ID like you did with the other EditText's.
Add ID = findViewById(R.id.txtid); to your onCreate(Bundle savedInstanceState) method.
The first thing I got when clicking on 'Save' was the following:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.citiesapps.myapplication.MainActivity$2.onClick(MainActivity.java:76)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
As the stacktrace states you are trying to invoke a method on a null-object in this case 'ID'.
After analyzing your code, i saw your are executing setText on an editText that is not initialized in your java class.
Probable editText code is:
ID.setText(""); Here ID is not initialized with xml file.
Use ID = findViewById(R.id.txtid); for initializing the ID field
Check all editText initialization. Then use that editText.
Thanks :)
Hello everybody. I'm trying to make an application that works with the database. I have a retention window, but the data is not saved. How to save the value boolean from check-box into the database?
How to resole this problem?
This is code of Database
public class DataBase extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "DataOfSchedule.db";
public static final String TABLE_NAME = "DataOfSchedule_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "AGE";
public static final String COL_4 = "SEX_MALE";
public static final String COL_7 = "SEX_FEMALE";
public static final String COL_5 = "WEIGHT";
public static final String COL_6 = "HEIGHT";
public static final String COL_8 = "TRAUMA";
public DataBase(Context context){
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY," +
" NAME TEXT," +
" AGE INTEGER NOT NULL DEFAULT 0 , " +
"SEX_MALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\") ," +
"SEX_FEMALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"TRAUMA NOT NULL TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"WEIGHT INTEGER NOT NULL DEFAULT 0," +
"HEIGHT INTEGER NOT NULL DEFAULT 0)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
}
public boolean insertData(String name, Integer age, String sex_male, String sex_female, Integer weight, Integer height, String trauma){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,age);
contentValues.put(COL_4,sex_male);
contentValues.put(COL_5,weight);
contentValues.put(COL_6,height);
contentValues.put(COL_7,sex_female);
contentValues.put(COL_8,trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
//To Check Whether Data is Inserted in DataBase
if(result==-1){
return false;
}else{
return true;
}
}
public Cursor getALLData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
return res;
}
}
It is code of Activity which inserts data
public class InsertData extends AppCompatActivity {
DataBase myDb;
EditText txtName, txtAge , txtWeight, txtHeight;
CheckBox boxSex_male,boxSex_female,boxTrauma;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_data);
myDb = new DataBase(this);
txtName = (EditText) findViewById(R.id.name);
txtAge = (EditText) findViewById(R.id.age);
boxSex_male = (CheckBox) findViewById(R.id.sex_m);
boxTrauma = (CheckBox) findViewById(R.id.trauma);
boxSex_female = (CheckBox) findViewById(R.id.sex_f);
txtWeight = (EditText) findViewById(R.id.weight);
txtHeight = (EditText) findViewById(R.id.height);
btnClick = (Button) findViewById(R.id.InsertBtn);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ClickMe();
}
});
if(boxTrauma.isChecked()){
boxTrauma.setChecked(true);
}else {
boxTrauma.setChecked(false);
}
if(boxSex_female.isChecked()){
boxSex_female.setChecked(true);
}else {
boxSex_female.setChecked(false);
}
if(boxSex_male.isChecked()){
boxSex_male.setChecked(true);
}else {
boxSex_male.setChecked(false);
}
}
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
String sex_male = boxSex_male.getText().toString();
String trauma = boxTrauma.getText().toString();
String sex_female = boxSex_female.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData(name,age_int,sex_male,sex_female,weight_int,height_int,trauma);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}
}
It is my HTML
<ScrollView 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="16dp"
tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/insert_heading"
android:layout_gravity="center"
android:textSize="16dp"
android:textColor="#021aee"/>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_name"/>
<EditText
android:id="#+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_age"
android:numeric="integer"/>
<EditText
android:id="#+id/weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_weight"
android:numeric="integer"/>
<EditText
android:id="#+id/height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_height"
android:numeric="integer"/>
<TextView
android:padding="10dp"
android:text="#string/insert_sex"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/sex_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/male"/>
<CheckBox
android:id="#+id/sex_f"
android:text="#string/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:padding="10dp"
android:text="#string/insert_trauma"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/trauma"
android:text="#string/insert_trauma_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/InsertBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#string/insert_button"
android:textColor="#f2fde4"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
Lets break this problem down into a couple of Posts. First we can deal with the SQLite part of the code then you can post a new question about inserting values--there is just to much code to cover and make this understandable.
Change your code in your DataBase class (BTW: Not a good name!)
Give the variable names for the columns an understandable name. Who can remember what COL_6 is? Also consider that these probably do not need to be public.
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_AGE = "AGE";
public static final String COL_GENDER = "GENDER";
public static final String COL_WEIGHT = "WEIGHT";
public static final String COL_HEIGHT = "HEIGHT";
public static final String COL_TRAUMA = "TRAUMA";
You might not want to check if the table already exists, but I added the check anyway. I also made ID an AUTOINCREMENT column.
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT," +
COL_AGE + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER + " INTEGER NOT NULL DEFAULT 0, " +
COL_TRAUMA + " INTEGER NOT NULL DEFAULT 0, " +
COL_WEIGHT + " INTEGER NOT NULL DEFAULT 0, " +
COL_HEIGHT + " INTEGER NOT NULL DEFAULT 0);");
}
Change the insertData method to accommodate the changes to the static final variables for the columns and the type changes of the parameters:
public boolean insertData(String name, Integer age, Integer sex_male, Integer weight, Integer height, Integer trauma){
boolean success = false;
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_AGE, age);
contentValues.put(COL_GENDER, sex_male);
contentValues.put(COL_WEIGHT, weight);
contentValues.put(COL_HEIGHT, height);
contentValues.put(COL_TRAUMA, trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
if(result != -1) success = true;
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
return success;
}
Also note, no need to get a Writeable database in your getALLData() method:
public Cursor getALLData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME, null);
return res;
}
Now post a new question on how the populate the database from your Activity and we can go from there...
Why it doesn't work? I have a problem with Database. How boolean use as int?
Maybe I wrote bad code.Did I used boolean as Integer right? How to do insert in database.How to save the value boolean from check-box into the database?
My code of database in Android
public class DataBase extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "DataOfSchedule.db";
public static final String TABLE_NAME = "DataOfSchedule_table";
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_AGE = "AGE";
public static final String COL_GENDER_M = "GENDER_M";
public static final String COL_GENDER_F = "GENDER_F";
public static final String COL_WEIGHT = "WEIGHT";
public static final String COL_HEIGHT = "HEIGHT";
public static final String COL_TRAUMA = "TRAUMA";
public DataBase(Context context){
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE" + TABLE_NAME +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT," +
COL_AGE + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER_M + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER_F + " INTEGER NOT NULL DEFAULT 0, " +
COL_TRAUMA + " INTEGER NOT NULL DEFAULT 0, " +
COL_WEIGHT + " INTEGER NOT NULL DEFAULT 0, " +
COL_HEIGHT + " INTEGER NOT NULL DEFAULT 0);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
}
// public boolean insertData(String name, Integer age, Integer sex_male, Integer sex_female, Integer weight, Integer height, Integer trauma){
// SQLiteDatabase db = this.getWritableDatabase();
// ContentValues contentValues = new ContentValues();
public boolean insertData(String name, Integer age, Integer gender_m, Integer gender_f, Integer weight, Integer height, Integer trauma){
boolean success = false;
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_AGE, age);
contentValues.put(COL_GENDER_M, gender_m);
contentValues.put(COL_GENDER_F, gender_f);
contentValues.put(COL_WEIGHT, weight);
contentValues.put(COL_HEIGHT, height);
contentValues.put(COL_TRAUMA, trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
if(result != -1) success = true;
}
catch(Exception ex){
}
return success;
}
public Cursor getALLData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
return res;
}
}
My main_activity
public class InsertData extends AppCompatActivity {
DataBase myDb;
EditText txtName, txtAge , txtWeight, txtHeight;
CheckBox boxGender_m,boxGender_f,boxTrauma;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_data);
myDb = new DataBase(this);
txtName = (EditText) findViewById(R.id.name);
txtAge = (EditText) findViewById(R.id.age);
boxGender_m = (CheckBox) findViewById(R.id.gender_m);
boxGender_f = (CheckBox) findViewById(R.id.gender_f);
boxTrauma = (CheckBox) findViewById(R.id.trauma);
txtWeight = (EditText) findViewById(R.id.weight);
txtHeight = (EditText) findViewById(R.id.height);
btnClick = (Button) findViewById(R.id.InsertBtn);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ClickMe();
}
});
}
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
String gender_m = boxGender_m.getText().toString();
String gender_f = boxGender_f.getText().toString();
String trauma = boxTrauma.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
int gender_int_m = Integer.parseInt(gender_m);
int gender_int_f = Integer.parseInt(gender_f);
int trauma_int = Integer.parseInt(trauma);
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData( name, age_int, gender_int_m, gender_int_f, weight_int, height_int, trauma_int);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}
}
What the matter? My XML
<ScrollView 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="16dp"
tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/insert_heading"
android:layout_gravity="center"
android:textSize="16dp"
android:textColor="#021aee"/>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_name"/>
<EditText
android:id="#+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_age"
android:numeric="integer"/>
<EditText
android:id="#+id/weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_weight"
android:numeric="integer"/>
<EditText
android:id="#+id/height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_height"
android:numeric="integer"/>
<TextView
android:padding="10dp"
android:text="#string/insert_gender"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/gender_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/male"/>
<CheckBox
android:id="#+id/gender_f"
android:text="#string/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:padding="10dp"
android:text="#string/insert_trauma"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/trauma"
android:text="#string/insert_trauma_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/InsertBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#string/insert_button"
android:textColor="#f2fde4"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
What the matter? App is closing when I click btn "Okay" with id InsertBtn
In short you should use the isChecked method to get whether or not the checkBox is checked which will be a boolean.
I'm unsure exactly what getText() will return but it would very likely not be a string that could be parsed to an int, so when the parse is attempted you will get an exception. An analogy would be to say to you pay me $rumplestiltskin. How much would you give me?
As such your code could be along the lines of :-
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
//String gender_m = boxGender_m.getText().toString(); //<<<< WRONG
//String gender_f = boxGender_f.getText().toString(); //<<<< WRONG
String trauma = boxTrauma.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
//<<<<<<<<<< ADDED CODE >>>>>>>>>>
int gender_int_m = 0;
if (boxGender_m.isChecked()) {
gender_int_m = 1;
}
int gender_int_f = 0;
if (boxGender_f.isChecked()) {
gender_int_f = 1;
}
//int gender_int_m = Integer.parseInt(gender_m); //<<<< REDUNDANT
//int gender_int_f = Integer.parseInt(gender_f); //<<<< REDUNDANT
int trauma_int = Integer.parseInt(trauma);
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData( name, age_int, gender_int_m, gender_int_f, weight_int, height_int, trauma_int);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}}
You are setting these:
int gender_int_m = Integer.parseInt(gender_m);
int gender_int_f = Integer.parseInt(gender_f);
int trauma_int = Integer.parseInt(trauma);
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
...as the primitive int but you method insertData takes the Integer object as arguments:
public boolean insertData(String name, Integer age, Integer gender_m, Integer gender_f,
Integer weight, Integer height, Integer trauma){...
In Java, int and Integer are NOT the same thing. I suggest you
update insertData to take the primitive int as arguments:
public boolean insertData(String name, int age, int gender_m, int gender_f,
int weight, int height, int trauma){...
I want list view automatically update after deletion. I use adapter.notifyDataSetChanged() but it doesn't work for me
Here is my code
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public 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)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Delete from database
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
EditData
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private Button btnDelete;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
ActionBar actionBar=getSupportActionBar();
actionBar.hide();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.4),(int)(height*.2));
btnDelete = (Button) findViewById(R.id.btnDelete);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
toastMessage("removed from database");
adapter.notifyDataSetChanged();
}
});
}
/**
* customizable toast
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListData
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
static ArrayAdapter adapter;
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
public void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
EditText editField;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
editField = (EditText) findViewById(R.id.editText);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editField.getText().toString().length() == 0) {
Toast.makeText(MainActivity.this, "Please Enter!", Toast.LENGTH_SHORT).show();
return;
}
String editText = editField.getText().toString();
AddData(editText);
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
And Layout are
activity_main
<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:orientation="vertical"
tools:context="com.tabian.saveanddisplaysql.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Enter any Thing"
android:layout_marginBottom="47dp"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="197dp"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:text="Add" />
<Button
android:id="#+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/btnAdd"
android:text="View Data" />
</LinearLayout>
</RelativeLayout>
edit_data_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<Button
android:id="#+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="DELETE" />
</RelativeLayout>
list_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
After deletion instead of adapter.notifyDataSetChanged(); you can use the following code. It works fine for me:
adapter.remove(selectedName);
Records added to DB by calling DBAdapter insert method on another activity
No runtime errors, data seems to be added to db properly, however the listview object does not appear when app is being run
Main Activity
public class MainScreen extends ActionBarActivity implements View.OnClickListener
{
Button addNewButton;
Button sortByNameButton;
Button sortByBusinessButton;
Button sortByPhoneButton;
DBAdapter userDB;
ListView cardList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main_screen);
//declare buttons
addNewButton= (Button)findViewById(R.id.addNewButton);
sortByNameButton= (Button)findViewById(R.id.sortByNameButton);
sortByBusinessButton= (Button)findViewById(R.id.sortByBusinessButton);
sortByPhoneButton= (Button)findViewById(R.id.sortByPhoneButton);
//set onclick listeners
addNewButton.setOnClickListener(this);
//set button to font
addNewButton.setText("Add New");
sortByNameButton.setText("Sort by Name");
sortByBusinessButton.setText("Sort by Business");
sortByPhoneButton.setText("Sort by Phone #");
userDB = new DBAdapter(this);
userDB.open();
cardList=(ListView) findViewById(id.cardList);
populateListViewFromDB();
}
#Override
public void onDestroy(){
userDB.close();
}
private void populateListViewFromDB() {
Cursor cursor = userDB.getAllRows();
//allow activity to manage cursor lifetime (dont want memory leak)
startManagingCursor(cursor);
//map from cursor to view fields
String[] fromFieldNames = new String[]{DBAdapter.KEY_BUS_NAME};
int[] toViewIDs = new int[]{R.id.business_name};
//adapter to map out columns and rows of DB (deprecated, but it's okay)
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(
this, //context
R.layout.item_layout, //layout template
cursor, //cursor
fromFieldNames, //information
toViewIDs //where to put information
);
//String[] vals = {"me","you","he","she"};
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, layout.activity_main_screen, vals);
//set adapter to list view element
cardList.setAdapter(cursorAdapter);
}
}
DBAdapter class:
public class DBAdapter {
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_BUS_NAME = "BusinessName";
public static final String KEY_PERS_NAME = "PersonalName";
public static final String KEY_ADDRESS = "Address";
public static final String KEY_PHONE_NUM = "PhoneNum";
public static final String KEY_EMAIL = "Email";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_BUS_NAME = 1;
public static final int COL_PERS_NAME = 2;
public static final int COL_ADDRESS = 3;
public static final int COL_PHONE_NUM = 4;
public static final int COL_EMAIL = 5;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_BUS_NAME, KEY_PERS_NAME, KEY_ADDRESS, KEY_PHONE_NUM, KEY_EMAIL};
// DB info: its name, and the table we are using (just one).
public static final String DATABASE_NAME = "LocalCards";
public static final String DATABASE_TABLE = "CardInfo";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_BUS_NAME + " text, "
+ KEY_PERS_NAME + " text, "
+ KEY_ADDRESS + " text, "
+ KEY_PHONE_NUM + " text, "
+ KEY_EMAIL + " text"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
//Cursor x = db.rawQuery("SELECT "+KEY_BUS_NAME+" FROM " + DATABASE_TABLE,null);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
//db.execSQL(DATABASE_CREATE_SQL);
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public void insertRow(String bus_name, String pers_name, String address, String phone, String email) {
/*
* CHANGE 3:
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues values = new ContentValues();
values.put(KEY_BUS_NAME, bus_name);
values.put(KEY_PERS_NAME, pers_name);
values.put(KEY_ADDRESS, address);
values.put(KEY_PHONE_NUM, phone);
values.put(KEY_EMAIL, email);*/
// Insert it into the database.
//return db.insert(DATABASE_TABLE, null, values);
db.rawQuery("INSERT INTO " + DATABASE_TABLE + " (" + KEY_BUS_NAME + "," + KEY_PERS_NAME + "," +
KEY_ADDRESS + "," + KEY_PHONE_NUM + "," + KEY_EMAIL + ") VALUES (" + "'" + bus_name +
"','" + pers_name + "','" + address + "','" + phone + "','" + email + "');",null);
}
// Delete a row from the database, by rowId (primary key)
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();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
//Cursor c = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
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;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String bus_name, String pers_name, String address, String phone, String email) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_BUS_NAME, bus_name);
newValues.put(KEY_PERS_NAME, pers_name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_PHONE_NUM, phone);
newValues.put(KEY_EMAIL, email);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
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!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/business_name"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/personal_name"
android:layout_below="#+id/business_name"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/phone_number"
android:layout_below="#+id/business_name"
android:layout_alignParentRight="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/email"
android:layout_below="#+id/phone_number"
android:layout_alignParentRight="true" />
activity_main_screen.xml:
<?xml version="1.0" encoding="utf-8"?>
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Sort by Name"
android:id="#+id/sortByNameButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Sort by Business"
android:id="#+id/sortByBusinessButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/sortByNameButton" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Sort by Phone"
android:id="#+id/sortByPhoneButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/sortByBusinessButton" />
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Add New"
android:id="#+id/addNewButton"
android:layout_alignBottom="#+id/sortByPhoneButton"
android:layout_toRightOf="#+id/sortByPhoneButton" />
<SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchBox"
android:layout_below="#+id/sortByNameButton"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/addNewButton"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cardList"
android:layout_alignParentRight="true"
android:layout_below="#+id/searchBox" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_below="#+id/searchBox"
android:layout_alignBottom="#+id/cardList"
android:layout_alignRight="#+id/searchBox"
android:layout_alignParentLeft="true" />