I want to get the Data Email and Password from the Database for my Login Activity.
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
Button loginButton;
EditText password;
EditText email;
DBAdapter db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new DBAdapter(this);
db=db.open();
this.email = (EditText) findViewById(R.id.editText);
this.password = (EditText) findViewById(R.id.editText2);
this.loginButton = (Button) findViewById(R.id.button);
if (getIntent().getExtras() != null) {
Toast.makeText(this, getIntent().getExtras().getString("toastMessage"), Toast.LENGTH_LONG).show();
}
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s2 = password.getText().toString();
String StoredPassword=db.getContacts1(s2);
if (s2.equals(StoredPassword)) {
Intent intent = new Intent(LoginActivity.this, PatientActivity.class);
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
}
});
}
}
DBAdapter.java
public class DBAdapter {
public static final String KEY_NAME="Name";
public static final String KEY_EMAIL="Email";
public static final String KEY_PASSWORD="Password";
public static final String KEY_PHONE= "Phone";
public static final String KEY_ADDRESS="Address";
public static final String TAG="DBAdapter";
public static final String DATABASE_NAME="MyDB.db";
public static final String DATABASE_TABLE="Contacts";
public static final int DATABASE_VERSION=1;
public static final String SELECT_EMAIL = "SELECT Email FROM Contacts";
public static final String SELECT_PASSWORD = "SELECT Password FROM Contacts";
public static final String DATABASE_CREATE="CREATE TABLE Contacts(Name text primary key not null,Email text not null,Password text not null,Phone integer not null,Address text);";
public Context context;
public DatabaseHelper DBHelper;
public SQLiteDatabase db;
public DBAdapter(Context context)
{
this.context = context;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading Database from " + oldVersion + " to " + newVersion + " which will destroy all Old Data");
db.execSQL("DROP TABLE IF EXISTS Contacts");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getReadableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insertContacts(String Name, String Email, String Password, String Phone, String Address)
{
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME,Name);
contentValues.put(KEY_EMAIL,Email);
contentValues.put(KEY_PASSWORD,Password);
contentValues.put(KEY_PHONE,Phone);
contentValues.put(KEY_ADDRESS,Address);
return db.insert(DATABASE_TABLE,null,contentValues);
}
public boolean deleteContacts(String Name)
{
return db.delete(DATABASE_TABLE,KEY_NAME + " "+ Name,null)>0;
}
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE,new String[] {KEY_NAME,KEY_EMAIL,KEY_PASSWORD,KEY_PHONE,KEY_ADDRESS},null,null,null,null,null);
}
public String getContacts(String Email) {
Cursor cursor = db.query("DATABASE_TABLE", null, "KEY_EMAIL", new String[]{Email}, null, null, null, null);
if (cursor == null) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String Email1 = cursor.getString(cursor.getColumnIndex("KEY_EMAIL"));
return Email1;
}
public String getContacts1(String Password)
{
Cursor cursor = db.query("DATABASE_TABLE",null,"KEY_PASSWORD",new String[]{Password},null,null,null,null);
if(cursor == null) {
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String Password1 = cursor.getString(cursor.getColumnIndex("KEY_PASSWORD"));
return Password1;
}
public boolean updateContacts(String Name,String Email,String Password,String Phone,String Address) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, Name);
contentValues.put(KEY_EMAIL, Email);
contentValues.put(KEY_PASSWORD, Password);
contentValues.put(KEY_PHONE, Phone);
contentValues.put(KEY_ADDRESS, Address);
return db.update(DATABASE_TABLE, contentValues, KEY_NAME + " " + Name, null) > 0;
}
}
activity_login.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="mydoctor.code.in.mydoctor.LoginActivity">
<TextView
android:text="Email:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="62dp"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3"
android:layout_marginLeft="44dp"
android:layout_marginStart="44dp"
android:layout_marginTop="47dp"
android:id="#+id/editText" />
<TextView
android:text="Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText"
android:layout_alignLeft="#+id/textView3"
android:layout_alignStart="#+id/textView3"
android:layout_marginTop="78dp"
android:id="#+id/textView4" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:layout_below="#+id/editText"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText"
android:layout_marginTop="63dp"
android:id="#+id/editText2" />
<Button
android:text="Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="101dp"
android:id="#+id/button"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Please help with the Problem. I am getting error in the Code. My Database is created Successfully but it is not being able to fetch the data.
Related
I want to add element to a data in database. I'm using clickable listView to go to another activity using intent. I already can go to another activity but i can't get the data, it's null. Also i want to add some value to that data and i'm still don't find the way to do it.
This is my XML for intent activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ap"
android:textSize="30dp"
android:text=""
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<EditText
android:id="#+id/ap_x"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="x (decimal)"
android:inputType="numberDecimal"
android:lines="1"
android:maxLength="10" />
<EditText
android:id="#+id/ap_y"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="y (decimal)"
android:inputType="numberDecimal"
android:lines="1"
android:maxLength="10" />
</LinearLayout>
<Button
android:id="#+id/save"
android:enabled="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Calibrate" />
</LinearLayout>
This is part of my listview class
List<ScanResult> results;
ListView wifisList;
protected CharSequence[] options;
protected boolean[] selections;
ArrayAdapter<Router> arrayAdapter;
ArrayList<Router> wifis;
String building;
Button save;
public final static String ID="com.example.indoorpositioning._SSID";
DatabaseHelper db;
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.settings);
db = new DatabaseHelper(this);
addWifi = (Button) findViewById(R.id.button_add);
wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
addWifi.setOnClickListener(new ButtonClickHandler());
save=(Button) findViewById(R.id.save);
wifisList = (ListView) findViewById(R.id.friendly_wifis);
Intent intent=getIntent();
building = intent.getStringExtra("BUILDING_NAME");
wifis=db.getFriendlyWifis(building);
arrayAdapter = new ArrayAdapter<Router>(this,
android.R.layout.simple_list_item_1, wifis);
// Set The Adapter
wifisList.setAdapter(arrayAdapter);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(db.addFriendlyWifis(building,wifis))
{
Toast toast = Toast.makeText(getApplicationContext(),"Saved :)", Toast.LENGTH_SHORT);
toast.show();
}
}
});
wifisList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent appInfo = new Intent(FriendlyWifis.this, ApKoor.class);
appInfo.putExtra("SSID", String.valueOf(id));
startActivity(appInfo);
}
});
This is my DB class
private static final String DATABASE_PATH = "/data/data/com.example.indoorpositioning/databases/";
public static final String DATABASE_NAME = "u236344269_indor.db";
public static final String AP_TABLE = "access_points";
public static final String READINGS_TABLE = "readings";
public static final String AP_CREATE = "CREATE TABLE 'access_points' "
+ "('building_id' TEXT NOT NULL ,'ssid' TEXT NOT NULL,'mac_id' TEXT NOT NULL )";
public static final String READINGS_CREATE = "CREATE TABLE 'readings' ('building_id' TEXT NOT NULL , "
+ "'position_id' TEXT NOT NULL , 'x' FLOAT NOT NULL, 'y' FLOAT NOT NULL, "
+ " 'ssid' TEXT NOT NULL , 'mac_id' TEXT NOT NULL , 'rssi' INTEGER NOT NULL )";
---------------------------------------------------------------------------
---------------------------------------------------------------------------
public ArrayList<Router> getFriendlyWifis(String building_id) {
ArrayList<Router> result = new ArrayList<Router>();
System.out.println(building_id);
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("select ssid,mac_id from " + AP_TABLE
+ " where building_id=?", new String[] { building_id });
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
result.add(new Router(cursor.getString(0), cursor.getString(1)));
cursor.moveToNext();
}
return result;
}
---------------------------------------------------------------------------
---------------------------------------------------------------------------
public boolean addFriendlyWifis(String building_id, ArrayList<Router> wifis) {
deleteFriendlyWifis(building_id);
SQLiteDatabase db = getWritableDatabase();
for (int i = 0; i < wifis.size(); i++) {
ContentValues cv = new ContentValues();
cv.put("building_id", building_id);
cv.put("ssid", wifis.get(i).getSSID());
cv.put("mac_id", wifis.get(i).getBSSID());
db.insert(AP_TABLE, null, cv);
}
System.out.println("Adding done");
return true;
}
And this is my intent activity
String passedVar = null;
private TextView passedView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ap_koor);
passedVar = getIntent().getStringExtra(FriendlyWifis.ID);
passedView=(TextView)findViewById(R.id.ap);
passedView.setText("AP="+passedVar);
}
Also the BUILDING_PATH is saying it never used.
In wifisList.setOnItemClickListener,your passing the intent name SSID.
Intent appInfo = new Intent(FriendlyWifis.this, ApKoor.class);
appInfo.putExtra("SSID", String.valueOf(id));
But in receive intent activity,you intent with the wrong name.
passedVar = getIntent().getStringExtra(FriendlyWifis.ID);
You should replace this line
public final static String ID="com.example.indoorpositioning._SSID";
to SSID.
public final static String ID="SSID";
Below there is complete code of creating and inserting values in database, but it is not working, database is not being created.
MainActivity.java
package com.dbtrial1.leenaharani.dbtrial1;
public class MainActivity extends AppCompatActivity {
private Button btnCreateDatabase,button;
private MySqliteOpenHelper mySqliteOpenHelper;
private SQLiteDatabase mDatabase ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCreateDatabase = (Button)findViewById(R.id.btnCreateDatabase);
btnCreateDatabase.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//create the database with table here
mySqliteOpenHelper = new
MySqliteOpenHelper(getApplicationContext());
mDatabase = mySqliteOpenHelper.getReadableDatabase();
Cursor cursor = mDatabase.rawQuery("select * from Restaurant Menu;", null);
System.out.println("Main Activity.onClick:" + cursor.getColumnCount());
}
} );
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
insertData();
}
} );
}
private void insertData () {
String BBQ="BBQ";
String Shakes="Chocolate_Shake";
String Deserts="Cake";
String table_name="Restaurant_Menu";
ContentValues values=new ContentValues();
values.put("BBQ" , BBQ);
values.put("Shakes",Shakes);
values.put("Deserts",Deserts);
long rowId =0;
if(mDatabase!=null) {
rowId = mDatabase.insert(table_name, null, values);
if (rowId != -1) {
Toast.makeText(MainActivity.this, "Inserted Successfully!", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "Error Inserting!", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(MainActivity.this,"Database is
null",Toast.LENGTH_SHORT).show();
}
}
MySqliteOpenHelper.java
package com.dbtrial1.leenaharani.dbtrial1;
public class MySqliteOpenHelper extends SQLiteOpenHelper {
private static final String database_name="Menu ";
private String table_name="Restaurant Menu";
private static final int database_version=1;
private String column_1="BBQ";
private String column_2="Shakes";
private String column_3="Deserts";
private String create_table_statement="Create Table "+ table_name+ " ( " + column_1 + " text not null, " + column_2 +
" TEXT, " + column_3 + " text not null ) ";
public MySqliteOpenHelper(Context context) {
super(context, database_name, null, database_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(create_table_statement);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//changes in the database
} }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dbtrial1.leenaharani.dbtrial1.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create DAtabase"
android:id="#+id/btnCreateDatabase"
tools:layout_editor_absoluteX="147dp"
tools:layout_editor_absoluteY="160dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="INSERT Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.153"
app:layout_constraintRight_toLeftOf="#+id/textView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="1.0" />
</android.support.constraint.ConstraintLayout>
I am a beginner Android programmer, so I know that my code is not commented/well designed.
Your table name contains a space
The command this results in
Create table restaurant name (bbq text not null, shakes TEXT, deserts text not null)
This is obviously a syntax error according to sql standard. Now sqlite will not throw an exception but will not create the table due to this.
So just replace the table name as Retaurant_Name and you'll be golden
I'm new to sqlite, but I did try to solve this problem on my own: I tried various tutorials and answers here at stackoverflow, but without success. You may recognise the code. I couldn't find an example of code that I understood or could use for my case.
I have an app where users can create characters by entering: their first name, their last name, their age.
The user can press plus 1 year in which case I want all integers in the column age to increment by 1 and show this to the user. All the characters should obviously age by one year. This I can't accomplish in my app.
Could you please tell me how I should modify the code to accomplish what I want and could you maybe please explain how your code works?
MainActivity.java:
public class MainActivity extends Activity {
ListView lv;
EditText firstnameTxt,familynameTxt,ageTxt;
Button savebtn,retrieveBtn,yearBtn;
ArrayList<String> characters=new ArrayList<String>();
ArrayAdapter<String> adapter;
String updatedAge;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstnameTxt=(EditText) findViewById(R.id.firstnameTxt);
familynameTxt=(EditText) findViewById(R.id.familynameTxt);
ageTxt=(EditText) findViewById(R.id.ageTxt);
savebtn=(Button) findViewById(R.id.saveBtn);
retrieveBtn=(Button) findViewById(R.id.retrievebtn);
yearBtn=(Button) findViewById(R.id.yearBtn);
lv=(ListView) findViewById(R.id.listView1);
lv.setBackgroundColor(Color.LTGRAY);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_selectable_list_item,characters);
final DatabaseHelper db=new DatabaseHelper(this);
//EVENTS
savebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//OPEN
db.openDB();
//INSERT
long result=db.add(firstnameTxt.getText().toString(),familynameTxt.getText().toString(),ageTxt.getText().toString());
if(result > 0)
{
firstnameTxt.setText("");
familynameTxt.setText("");
ageTxt.setText("");
}else
{
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
//CLOSE DB
db.close();
}
});
yearBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
characters.clear();
db.openDB();
Cursor c=db.getAllNames();
c.moveToFirst();
while(!c.isAfterLast()) {
//while(c.moveToFirst()) {
int age = c.getInt(3);
updatedAge = String.valueOf(age);
boolean isUpdate = db.updateAgeInDatabase(updatedAge);
if (isUpdate == true)
Toast.makeText(MainActivity.this, "Data successfully updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data updated FAILED", Toast.LENGTH_LONG).show();
c.moveToNext();
}
lv.setAdapter(adapter);
db.close();
}
});
//RETRIEVE
retrieveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
characters.clear();
//OPEN
db.openDB();
//RETRIEVE
Cursor c=db.getAllNames();
while(c.moveToNext())
{
String firstname=c.getString(1);
String familyname=c.getString(2);
int age=c.getInt(3);
characters.add(firstname + " " + familyname + ": " + age);
}
lv.setAdapter(adapter);
db.close();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int age,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), characters.get(age), Toast.LENGTH_SHORT).show();
}
});
}
}
DatabaseHelper.java:
public class DatabaseHelper {
//COLUMNS
static final String ROWID="id";
static final String FIRSTNAME = "firstname";
static final String FAMILYNAME = "familyname";
static final String AGE = "age";
//DB PROPERTIES
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "firstname TEXT NOT NULL,familyname TEXT NOT NULL,age INTEGER NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DatabaseHelper(Context ctx) {
// TODO Auto-generated constructor stub
this.c=ctx;
helper=new DBHelper(c);
}
// INNER HELPER DB CLASS
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context ) {
super(context, DBNAME, null, DBVERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(CREATE_TB);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("DBAdapter","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
// OPEN THE DB
public DatabaseHelper openDB()
{
try
{
db=helper.getWritableDatabase();
}catch(SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
//CLOSE THE DB
public void close()
{
helper.close();
}
//INSERT INTO TABLE
public long add(String firstname,String familyname,String age)
{
try
{
ContentValues cv=new ContentValues();
cv.put(FIRSTNAME, firstname);
cv.put(FAMILYNAME, familyname);
cv.put(AGE, age);
return db.insert(TBNAME, ROWID, cv);
}catch(SQLException e)
{
e.printStackTrace();
}
return 0;
}
public boolean updateAgeInDatabase(String age) { //or the problem is here
//SQLiteDatabase db = this.getWritableDatabase(); //"getWritableDatabase" stays red
ContentValues cv = new ContentValues();
cv.put(AGE, age);
//db.update(TBNAME, cv, "ID = ?", new String[] { age }); this is the line I replaced with MikeT's code right down here
db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " = 1 + ? ", new String[] { age } );
return true;
}
//GET ALL VALUES
public Cursor getAllNames()
{
String[] columns={ROWID,FIRSTNAME,FAMILYNAME,AGE};
return db.query(TBNAME, columns, null, null, null, null, null);
//return db.rawQuery("select * from "+TBNAME,null);
}
}
activity_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ageTxt"
android:layout_marginTop="34dp"
android:text="Save" />
<EditText
android:id="#+id/firstnameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:layout_toRightOf="#+id/saveBtn"
android:ems="10" />
<EditText
android:id="#+id/familynameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/firstnameTxt"
android:layout_below="#+id/firstnameTxt"
android:ems="10" />
<EditText
android:id="#+id/ageTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/firstnameTxt"
android:layout_below="#+id/familynameTxt"
android:ems="10" >
</EditText>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/familynameTxt"
android:layout_alignParentLeft="true"
android:text="Firstname"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ageTxt"
android:layout_alignParentLeft="true"
android:text="Familyname"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ageTxt"
android:layout_alignParentLeft="true"
android:text="Age"
android:textAppearance="?android:attr/textAppearanceSmall" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/saveBtn"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
<Button
android:text="+1 year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/retrievebtn"
android:layout_centerHorizontal="true"
android:id="#+id/yearBtn" />
<Button
android:id="#+id/retrievebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retrieve"
android:layout_above="#+id/linearLayout1"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Assuming your issues are with the updateAgeInDatabase method.
I believe your issue is with "ID = ?". basically it is saying change the rows that have the ID column that equals the respective value in the where arguments string array (that's what the ? does). You are then passing the age, which may or may not match an ID.
If you want to update ALL ages with a single value then use db.update(TBNAME,cv,null,null).
My guess is that you want to ADD 1 to ALL ages rather than set ages to a specific value. If so then you could run a query using SET e.g.
db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " = " + AGE + " + 1", null);
MainActivity.java:
yearBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
characters.clear();
db.openDB();
Cursor c=db.getAllNames();
c.moveToFirst();
while(!c.isAfterLast()) {
c.moveToLast();
int age = c.getInt(3);
updatedAge = String.valueOf(age);
boolean isUpdate = db.updateAgeInDatabase(updatedAge);
if (isUpdate == true)
Toast.makeText(MainActivity.this, "Data successfully updated", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data updated FAILED", Toast.LENGTH_LONG).show();
c.moveToNext();
}
lv.setAdapter(adapter);
db.close();
}
});
DatabaseHelper.java:
public boolean updateAgeInDatabase(String age) {
db.execSQL("UPDATE " + TBNAME + " SET " + AGE + " = " + AGE + " + 1");
return true;
}
So I'm trying to add items to ListView every time users presses SAVE button on Dialog. I think I did everything right except coding the onClickListener for that SAVE Button.
I would really appreciate if someone could help me out.
Here's my row layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#cccccc"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ime predmeta"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:textSize="20sp"
android:textColor="#424242"
android:id="#+id/textViewRowListaPredmetiImePredmeta"/>
</LinearLayout>
Database Helper class:
public class PredmetiDodajDBHelper extends SQLiteOpenHelper{
public static final int DATABASSE_VERSION = 3;
public static final String DATABASE_NAME = "dodaj_predmet.db";
public static final String TABLE_NAME = "predmeti";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_IMEPREDMETA = "imepredmeta";
public PredmetiDodajDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASSE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_IMEPREDMETA + " TEXT NOT NULL " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
dataoperation class
public class dataoperation {
SQLiteDatabase database_ob;
PredmetiDodajDBHelper openHelper_ob;
Context context;
public dataoperation(Context c) {
// TODO Auto-generated constructor stub
context=c;
}
public dataoperation opnToRead() {
openHelper_ob = new PredmetiDodajDBHelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.DATABASSE_VERSION);
database_ob = openHelper_ob.getReadableDatabase();
return this;
}
public dataoperation opnToWrite() {
openHelper_ob = new PredmetiDodajDBHelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.DATABASSE_VERSION);
database_ob = openHelper_ob.getWritableDatabase();
return this;
}
public void Close() {
database_ob.close();
}
public long insertData(String fname) {
ContentValues contentValues = new ContentValues();
contentValues.put(openHelper_ob.COLUMN_IMEPREDMETA, fname);
opnToWrite();
long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
contentValues);
Close();
return val;
}
public Cursor readdata() {
String[] cols = { openHelper_ob.COLUMN_ID, openHelper_ob.COLUMN_IMEPREDMETA };
opnToWrite();
#SuppressWarnings("static-access")
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols, null,
null, null, null, null);
return c;
}
public Cursor queryAll(int nameId) {
String[] cols = { openHelper_ob.COLUMN_ID, openHelper_ob.COLUMN_IMEPREDMETA};
opnToWrite();
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols,
openHelper_ob.COLUMN_ID + "=" + nameId, null, null, null, null);
return c;
}
}
And the part of code from activity that contains the Dialog and ListView:
editTextDodajPredmetImePredmeta = (EditText)dialog. findViewById(R.id.editTextDodajPredmetImePredmeta);
buttonSpremiPredmet = (Button)dialog. findViewById(R.id.buttonSpremiPredmet);
imePredmeta = editTextDodajPredmetImePredmeta.getText().toString();
lv=(ListView)findViewById(R.id.lista_predmeti);
//bt=(Button)findViewById(R.id.buttonSpremiPredmet);
adapter_ob = new dataoperation(Ocijene.this);
String[] from = { PredmetiDodajDBHelper.COLUMN_IMEPREDMETA };
int[] to = { R.id.editTextDodajPredmetImePredmeta };
cursor = adapter_ob.readdata();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(Ocijene.this,
R.layout.row_lista_predmeti, cursor, from, to);
lv.setAdapter(cursorAdapter);
buttonSpremiPredmet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lv.addView(editTextDodajPredmetImePredmeta);
}
});
That EditText and all that stuff are from this xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="26dp"
android:paddingRight="26dp"
android:paddingTop="15dp"
android:paddingBottom="25dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/dialog_predmeti_ime_predmeta"
android:layout_marginBottom="5dp"
android:id="#+id/textView5" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextDodajPredmetImePredmeta"
android:layout_marginBottom="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/dialog_predmeti_vrsta_ispita"
android:layout_marginBottom="5dp"
android:id="#+id/textView6" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinnerPredmetiLayoutDialogDodajVrsteIspita"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/buttonSpremiPredmet" />
</LinearLayout>
I think that lv.addView(editTextDodajPredmetImePredmeta); is causing the problem, but with what should I replace it?
Thanks and sorry for the whole bunch of code!
So your goal is to save data to database and add the same to Listview,you can call the insert method you have written and call notify dataset changed method after it
I keep getting a Null Pointer Exception when i'm trying to get data from my SQLite database and I'm not sure how to fix this. The code:
The activity:
public class Draft_Budget extends Activity {
String[] budget;
DBHelper budDb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.draft_budget);
ActionBar actionBar = getActionBar();
actionBar.show();
populateListViewFromDB();
registerListClickCallback();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
budget =
getResources().getStringArray(R.array.Budget_freq);
Spinner s1 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, budget);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "you have selected item: " + budget[index], Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
protected void onDestroy(){
super.onDestroy();
closeDB();
}
private void openDB(){
budDb = new DBHelper(this);
budDb.open();
}
private void closeDB() {
budDb.close();
}
public void add_expense(View view){
Intent intent = new Intent(this, Setup_expenses.class);
intent.putExtra("expense_Id",0);
startActivity(intent);
populateListViewFromDB();
}
public void clearexp(View v){
budDb.deleteAll();
populateListViewFromDB();
}
private void populateListViewFromDB(){
Cursor cursor = budDb.getAllRows();
startManagingCursor(cursor);
String[] fromFeildNames = new String[]
{DBHelper.KEY_label, DBHelper.KEY_cost, DBHelper.KEY_cost};
int[] toViewIDs = new int[]
{R.id.expense_name, R.id.expense_Id, R.id.expense_cost};
SimpleCursorAdapter exCursorAdapter = new SimpleCursorAdapter(
this,
R.layout.view_expense_entry,
cursor,
fromFeildNames,
toViewIDs);
ListView expenselist = (ListView) findViewById(R.id.list_expense);
expenselist.setAdapter(exCursorAdapter);
}
private void registerListClickCallback(){
ListView budlist = (ListView) findViewById(R.id.list_expense);
budlist.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long idInDB){
updateItemForId(idInDB);
displayToastForId(idInDB);
}
});
}
private void updateItemForId(long idInDB){
Cursor cursor = budDb.getRow(idInDB);
if (cursor.moveToFirst()){
long idDB = cursor.getLong(DBHelper.COL_ROWID);
String name = cursor.getString(DBHelper.COL_label);
int cost = cursor.getInt(DBHelper.COL_cost);
budDb.updateRow(idDB, name, cost);
}
cursor.close();
populateListViewFromDB();
}
private void displayToastForId(long idInDB){
Cursor cursor = budDb.getRow(idInDB);
if (cursor.moveToFirst()){
long idDB = cursor.getLong(DBHelper.COL_ROWID);
String label = cursor.getString(DBHelper.COL_label);
int cost = cursor.getInt(DBHelper.COL_cost);
String message = "ID: " + idDB + "\n" + "Category: " + label + "\n" + "Cost: " + cost;
Toast.makeText(Draft_Budget.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return MenuChoice(item);
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
{
mnu1.setIcon(R.drawable.ic_action_overflow);
mnu1.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0:
Toast.makeText(this, "You clicked on Item 1", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
public void done(View view) {
Intent done = new Intent(this, Home_page.class);
done.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(done);
}
The database provider:
public class DBHelper {
private static final String TAG = "DBHelper";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_label = "Label";
public static final String KEY_cost = "Cost";
public static final int COL_label = 1;
public static final int COL_cost = 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_label, KEY_cost};
public static final int DATABASE_VERSION = 5;
public static final String DATABASE_NAME = "Expense.db";
public static final String DATABASE_TABLE = "expenseTable";
public static final String DATABASE_CREATE_SQL = "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_label + " text not null, " + KEY_cost + " integer not null" + ");";
final Context context;
DatabaseHelper myDBHelper;
SQLiteDatabase db;
public DBHelper(Context ctx){
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db){
try {
_db.execSQL(DATABASE_CREATE_SQL);
} catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldversion, int newversion) {
Log.w(TAG, "Upgarding application's database from version " + oldversion + " to " + newversion + " , which will destroy all old data!");
//Destroy
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
//Recreate database
onCreate(_db);
}
}
public DBHelper open(){
db = myDBHelper.getWritableDatabase();
return this;
}
public void close(){
myDBHelper.close();
}
//Add set of values to database
public long insertRow(int Cost, String Label) {
db = myDBHelper.getWritableDatabase();
ContentValues intialvalues = new ContentValues();
intialvalues.put(KEY_label, Label);
intialvalues.put(KEY_cost, Cost);
return db.insert(DATABASE_TABLE, null, intialvalues);
}
//Delete
public boolean deleteRow(long rowId){
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, 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 data
public Cursor getAllRows() throws SQLException{
db = myDBHelper.getReadableDatabase();
return db.query(DATABASE_TABLE, ALL_KEYS , null, null, null, null, null);
}
//Get specific row
public Cursor getRow(long rowId) throws SQLException{
Cursor c = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_label, KEY_cost}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (c != null){
c.moveToFirst();
}
return c;
}
//Change row to equal new data
public boolean updateRow(long rowId, String Label, int Cost){
db = myDBHelper.getWritableDatabase();
ContentValues newvalues = new ContentValues();
newvalues.put(KEY_label, Label);
newvalues.put(KEY_cost, Cost);
return db.update(DATABASE_TABLE, newvalues, KEY_ROWID + "=" + rowId, null) > 0;
}
The layout file for the activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/Expense"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#939393"
android:textColor="#ffffff" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+Add Expense"
android:id="#+id/button2"
android:onClick="add_expense"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:nestedScrollingEnabled="false" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/Income"
android:id="#+id/textView2"
android:textColor="#ffffff"
android:background="#939393"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+Add Income"
android:textSize="6pt"
android:id="#+id/button3"
android:onClick="Set_income"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner2"
android:drawSelectorOnTop="true"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Done"
android:id="#+id/button"
android:onClick="done"
android:layout_alignParentBottom="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_expense"
android:layout_below="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/textView2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear expenses:"
android:id="#+id/clearexp"
android:onClick="clearexp"
android:layout_below="#+id/textView"
android:layout_toRightOf="#+id/button2"
android:layout_toEndOf="#+id/button2"
android:layout_marginLeft="92dp"
android:layout_marginStart="92dp" />
</RelativeLayout>
and for the listview:
<LinearLayout 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/expense_Id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/expense_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingTop="6dip"
android:textSize="14pt"/>
<TextView
android:id="#+id/expense_cost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="14pt"/>
</LinearLayout>
Any ideas how to fix this?
*Edit, the log:
06-10 14:56:51.098 2110-2110/com.example.thomaseleutheriades.personalwallet E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.thomaseleutheriades.personalwallet, PID: 2110
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thomaseleutheriades.personalwallet/com.example.thomaseleutheriades.personalwallet.Draft_Budget}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.thomaseleutheriades.personalwallet.Draft_Budget.populateListViewFromDB(Draft_Budget.java:89)
at com.example.thomaseleutheriades.personalwallet.Draft_Budget.onCreate(Draft_Budget.java:37)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at
It seems you didn't initialize budDb before calling populateListViewFromDB(); here budDb is null?