ArrayList<HashMap<String, String>> to SQLite database android - java

I have a database that has a table with 4 columns : ID, Contact(name), Phone, Message.
ID is auto incremented.
Contact name and number comes from an ArrayList>
Message comes from an EditText.
I am have problems trying to create the part to bring in the ArrayList> to the Database.
I have the part for the message but later I will need to either put that message in every slot? Or maybe not save it in the database but somewhere else.
Also, should I keep the contact name? or just the number since the number is what will be used to send the SMS message?
Thanks in advance!
Below is my code.
Contacts.java - gets the contacts from the contact list and saves them in an ArrayList>
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.deptofpharmacology.test.R;
import java.util.ArrayList;
import java.util.HashMap;
public class Contacts extends ActionBarActivity {
private static final int PICK_CONTACT = 1;
private static final String TAG = "The Goods: ";
DatabHelper myDb;
private static ArrayList<HashMap<String, String>> getContacts = new ArrayList<HashMap<String, String>>();
private static ArrayList<HashMap<String, String>> data1 = new ArrayList<HashMap<String, String>>();
private static HashMap<String, String> contacts = new HashMap<String,String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
myDb = new DatabHelper(this);
// ArrayList<HashMap<String, String>> getD = myDb.insertRecord();
}
/**
this is what's going to be used to transfer the Arraylist<HashMap> to the database
public void AddConPhon(){
boolean isInserted = myDb.insertData(Contacts.this, );
}
**/
public void btnAddContacts_Click(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
public void btnDone_Click(View view){
Intent i = new Intent(Contacts.this, Message.class);
startActivity(i);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id =
c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =
c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
null, null);
phones.moveToFirst();
String phn_no = phones.getString(phones.getColumnIndex("data1"));
String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DISPLAY_NAME));
contacts.put(name, phn_no);
HashMap<String, String> h = new HashMap<String, String>();
h.put("name", name);
h.put("phone", phn_no);
data1.add(h);
Toast.makeText(this, "contact info : " + phn_no + "\n" + name, Toast.LENGTH_LONG).show();
Log.d(TAG," " + data1.size());
Log.d(TAG, data1.toString());
}
}
}
}
}
Contacts 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.deptofpharmacology.test.Contacts">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="82dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact2"
android:layout_below="#+id/contact1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact3"
android:layout_below="#+id/contact2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="49dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:id="#+id/contact4"
android:layout_below="#+id/contact3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="52dp"
android:clickable="true"
android:onClick="btnAddContacts_Click" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/Next1"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="true"
android:onClick="btnDone_Click" />
</RelativeLayout>
the Database
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.HashMap;
public class DatabHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "PostalE.db";
public static final String TABLE_NAME = "emergency_table";
public static final String COL_1= "ID";
public static final String COL_2 = "CONTACTS";
public static final String COL_3 = "NUMBERS";
public static final String COL_4 = "MESSAGE";
public DatabHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, CONTACTS TEXT ,NUMBERS INTEGER, MESSAGE TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertRecord(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", queryValues.get("name"));
values.put("phone", queryValues.get("phone"));
database.insert(COL_2, null, values);
database.insert(COL_3, null, values);
long result = database.insert(TABLE_NAME,null,values);
if(result == -1){
return false;
}else{
return true;
}
}
/**
public boolean insertData(String name, String phone){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,phone);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
**/
public boolean insertData(String message){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_4,message);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}else{
return true;
}
}
}

This how you add it to the database from Contacts.class
DatabHelper databasecontroller = new DatabHelper(Contacts.this);
//or context
HashMap<String, String> values = new HashMap<String, String>();
values .put("somecolumnname1", sometextbuttonorwhateverview1.getText().toString());
values .put("somecolumnname2", sometextbuttonorwhateverview2.getText().toString());
values .put("somecolumnname13", sometextbuttonorwhateverview3.getText().toString());
databasecontroller.enterdata(values);
Put in Database
public void enterdata(HashMap<String, String> Vi) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("somecolumnname1", Vi.get("somecolumnname1"));
values.put("somecolumnname2", Vi.get("somecolumnname2"));
//etc
database.insert("DatabHelper", null, values);
database.close();
}
Where you do this
HashMap<String, String> h = new HashMap<String, String>();
h.put("name", name);
h.put("phone", phn_no);
data1.add(h);
You can simplify by doing
HashMap<String, String> values = new HashMap<String, String>();
values .put("name", name);
values .put("phone", phn_no);
databasecontroller.enterdata(values);

put in databaseclass
public void inserI(ArrayList<HashMap<String, String>> list1) {
// TODO Auto-generated method stub
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues1 = new ContentValues();
for(int i=0;i<list1.size();i++){
newValues1.put(ITEM, list1.get(i).get("names").toString());
newValues1.put(QUA, list1.get(i).get("phone").toString());
//newValues1.put(RATE,list1.get(i).get(THIRD_COLUMN).toString());
db.insert(QUANTITY, null, newValues1);
}

Related

How to fix 'null object reference' error in Android Studio / SQLite? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm writing a simple social media app, and I'm having trouble registering new users to my database. After I click the "Submit" button on the activity_register.xml page, I receive this error: "Attempt to invoke virtual method 'void com.example.kame3531.tuuner.DatabaseHandler.createUser(java.lang.String, java.lang.String)' on a null object reference". How would I go about fixing this?
activity_register.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_register"
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"
android:background="#drawable/grad"
tools:context="com.example.kame3531.tuuner.RegisterActivity">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Register"
android:fontFamily="sans-serif-condensed"
android:textColor="#ffffff"
android:textSize="90sp"
android:layout_marginTop="85dp"/>\
<EditText
android:id="#+id/username_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/title"
android:layout_marginTop="70dp"
android:width="200dp"
android:textAlignment="center"
android:fontFamily="sans-serif-condensed"
android:background="#5BC0EB"
/>
<EditText
android:id="#+id/password_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/username_register"
android:layout_marginTop="15dp"
android:width="180dp"
android:textAlignment="center"
android:fontFamily="sans-serif-condensed"
android:background="#5BC0EB"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/password_register"
android:layout_marginTop="40dp"
android:width="180dp"
android:text="Submit"
android:textSize="20dp"
android:fontFamily="sans-serif-condensed"
android:background="#9BC53D"
android:onClick="registerUser"
/>
</RelativeLayout>
RegisterActivity.java:
package com.example.kame3531.tuuner;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
protected void registerUser(View view) {
// validate the form
EditText usernameField = (EditText) findViewById(R.id.username_register);
EditText passwordField = (EditText) findViewById(R.id.password_register);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
try {
UserHelper.CreateUser(username, password);
setResult(Activity.RESULT_OK, getIntent());
// close intent, if not, Toast error
this.finish();
} catch (Exception e) {
// Toast the exception
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
UserHelper.java:
package com.example.kame3531.tuuner;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
import static com.example.kame3531.tuuner.LoginActivity.logged_username;
public class UserHelper {
public static List<String> usernames = new ArrayList<String>();
public static List<String> passwords = new ArrayList<String>();
public static DatabaseHandler db;
public static void openDB(Context context) {
if(db == null) {
db = new DatabaseHandler(context);
}
}
// Creates a user with some logic, or throws the error
public static void CreateUser(String username, String password) throws Exception {
if(username.length() <5) {
throw new Exception("Username needs to be 5 chars long");
} else if(password.length() < 4) {
throw new Exception("Password needs to be 4 chars long");
} else if(password.equals(username)) {
throw new Exception("Password cannot be the username");
}
db.createUser(username, password);
}
public static boolean AuthenticateUser(String username, String password) {
User user = db.getUserByName(username);
if(user != null && user.password.equals(password)) {
// set username as static
logged_username = user.username;
return true;
}
return false;
}
}
DatabaseHandler.java:
package com.example.kame3531.tuuner;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
import static com.example.kame3531.tuuner.LoginActivity.user_id_static;
/**
* Created by Deakyu on 11/4/2016.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, "Tuuner", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// users table
db.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"username TEXT, password TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public User getUserByName(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM users WHERE username = '"
+ name + "'", null);
if(cursor.moveToFirst()) {
User user = new User(cursor.getString(1), cursor.getString(2));
user_id_static = cursor.getInt(0);
return user; // Found user
}
return null; // No user found
}
public void createUser(String username, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("username", username);
cv.put("password", password);
// Write to database
db.insert("users", null, cv);
db.close();
}
}
I am not sure it will work or not ,
In your RegisterActivity call UserHelper.openDB(this) before calling UserHelper.CreateUser(username, password);
Hence the code will be:-
try { UserHelper.openDB(this)
UserHelper.CreateUser(username, password);
setResult(Activity.RESULT_OK, getIntent());
// close intent, if not, Toast error
this.finish();
} catch (Exception e) {
// Toast the exception
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}

Getting error in the on create method for sqlite database

I am creating a trivia game for a class assignment. I initially wanted to store the questions with categories in a sqlite database. I'm strating with one table, though I want to add others for category, level, and users, but first wanted to get it working with just questions. The program compiles and installs into the emulator and the first part works fine. It's not until the app goes to create the database that I get an error. The error reads:
Caused by:
android.database.sqlite.SQLiteException: near "TABLEquestion": syntax error (code 1): , while compiling: CREATE TABLEquestion(questionIDINTEGER PRIMARY KEY,questionNameTEXT,optionATEXT,optionBTEXT,optionCTEXT,answerTEXT,questionLevelIDINTEGER,categoryIDINTEGER)
at android.database.sqlite
My code for the main activity, trivia question activity, question class, DBHelper class and the xml layout for the Trivia Question activity. Please note, the error occurs when the radio button is selected for a category, which launches the Trivia Question activity. (before adding the database, the launch worked without error). Also, I know I need to create methods for Updating and Deleting records, but wanted to get the database creation working first. I've looked at this for 2 days and cannot find the issue. Any assistance would be greatly appreciated.
CLASS QUESTION:
public class Question {
private Integer questionID;
private String questionName;
private String optionA;
private String optionB;
private String optionC;
private String answer;
private Integer questionLevelID;
private Integer categoryID;
public Question(){
//// TODO: 11/5/2016
}
public Question (Integer questionID, String questionName, String optionA,
String optionB, String optionC, String answer, Integer questionLevelID,
Integer catID){
this.questionID=questionID;
this.questionName=questionName;
this.optionA=optionA;
this.optionB=optionB;
this.optionC=optionC;
this.answer=answer;
this.questionLevelID=questionLevelID;
this.categoryID = catID;
}
public void setqID(Integer questionId){
this.questionID = questionId;
}
public void setqName(String questionName){
this.questionName=questionName;
}
public void setqOptA(String optionA){
this.optionA = optionA;
}
public void setqOptB(String optionB){
this.optionB = optionB;
}
public void setqOptC(String optionC){
this.optionC=optionC;
}
public void setqAns(String answer){
this.answer = answer;
}
public void setQLevel(Integer questionLevelID){
this.questionLevelID = questionLevelID;
}
public void setqcatID(Integer categoryID){
this.categoryID= categoryID;
}
public int getqID(){
return questionID;
}
public String getqName(){
return questionName;
}
public String getqOptA(){
return optionA;
}
public String getqOptB(){
return optionB;
}
public String getqOptC(){
return optionC;
}
public String getqAns(){
return answer;
}
public Integer getqLevel(){
return questionLevelID;
}
public Integer getqCatID(){
return categoryID;
}
}
MAIN ACTIVITY:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.util.Log;
import java.util.List;
import static android.R.attr.id;
public class EduTriviaMain extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_trivia_main);
}
public String onCheckedChanged(View view) {
boolean checked = ((RadioButton) view).isChecked();
String category = "";
switch (view.getId()) {
case R.id.englishRadioButton:
if (checked) {
category = "english";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.historyRadioButton:
if (checked) {
category = "history";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
case R.id.mathRadioButton:
if (checked) {
category = "math";
Intent intent = new Intent(this,TriviaQuestion.class);
startActivity(intent);
return category;
}
break;
default:
break;
}
return category;
}
}
DBHelper Class:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DBHandler extends SQLiteOpenHelper{
//Database Version
private static final int DATABASE_VERSION=1;
//Database Name
private static final String DATABASE_NAME ="eduTrivia";
//table names
private static final String TABLE_QUESTION="question";
//question table column names
private static final String KEY_QUESTIONID = "questionID";
private static final String KEY_QUESTION="questionName";
private static final String KEY_OPTIONA="optionA";
private static final String KEY_OPTIONB="optionB";
private static final String KEY_OPTIONC="optionC";
private static final String KEY_ANSWER="answer";
private static final String KEY_LEVEL = "questionLevelID";
private static final String KEY_CATEGORYID="categoryID";
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE"
+ TABLE_QUESTION +"("
+ KEY_QUESTIONID +"INTEGER PRIMARY KEY,"
+ KEY_QUESTION + "TEXT,"
+ KEY_OPTIONA + "TEXT,"
+ KEY_OPTIONB + "TEXT,"
+ KEY_OPTIONC + "TEXT,"
+ KEY_ANSWER + "TEXT,"
+ KEY_LEVEL + "INTEGER,"
+ KEY_CATEGORYID + "INTEGER"+")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUESTION);
addQuestions();
}
private void addQuestions(){
Question q1 = new Question(1,"How do you write this number using words? 752",
"five hudnred sixty-two","seven hundred sixty-two", "seven hundred fifty-two",
"C",1,1);
Question q2 = new Question(2,"Round 5,764,438 to the nearest hundred thousand",
"6,200,000","5,800,000","5,700,000","B",1,1);
Question q3= new Question(3,"Which equation shows the associative property of addition",
"5+4=3+6","7+(4+3)=(7+4)+3", "0+8=8","B",1,1);
Question q4 = new Question(4,"Select the adjective in this sentence: Nina is a strong worker",
"Nina","strong","worker","B",1,2);
Question q5 = new Question (5,"Select the adjective in this sentence: The twon has three banks",
"The","town","three","C",1,2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists"+TABLE_QUESTION);
onCreate(db);
}
//constructor and getInstance() method
private static DBHandler mDBHANDLER;
public static synchronized DBHandler getInstance(Context context) {
if (mDBHANDLER==null){
mDBHANDLER=new DBHandler(context.getApplicationContext());
}
return mDBHANDLER;
}
public DBHandler(Context context){
super(context, DATABASE_NAME,null,DATABASE_VERSION);
}
public void addQuestion(Question question){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUESTIONID,question.getqID());
values.put(KEY_QUESTION,question.getqName());
values.put(KEY_OPTIONA,question.getqOptA());
values.put(KEY_OPTIONB,question.getqOptB());
values.put(KEY_OPTIONC,question.getqOptC());
values.put(KEY_ANSWER,question.getqAns());
values.put(KEY_LEVEL,question.getqLevel());
values.put(KEY_CATEGORYID,question.getqCatID());
db.insert(TABLE_QUESTION,null,values);
db.close();
}
//reading records
public Question getQuestion(int id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_QUESTION, new String[]{
KEY_QUESTIONID, KEY_QUESTION
},KEY_QUESTIONID + "=?",
new String[]{
String.valueOf(id)},null,null,null,null);
if (cursor !=null)
cursor.moveToFirst();
Question question = new Question(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),cursor.getString(2), cursor.getString(3),
cursor.getString(4),cursor.getString(5),Integer.parseInt(cursor.getString(6)),
Integer.parseInt(cursor.getString(7)));
return question;
}
public List<Question> getAllQuestions(){
//Select all questions query
List questionList = new ArrayList<Question>();
String selectAll = "SELECT * FROM "+TABLE_QUESTION;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectAll,null);
//loop through all rows and add to the list
if (cursor.moveToFirst()){
do{
Question question = new Question ();
question.setqID(Integer.parseInt(cursor.getString(0)));
question.setqName(cursor.getString(1));
question.setqOptA(cursor.getString(2));
question.setqOptB(cursor.getString(3));
question.setqOptC(cursor.getString(4));
question.setqAns(cursor.getString(5));
//adding to list
questionList.add(question);
}while (cursor.moveToNext());
}
return questionList;
}
}
TRIVIA QUESTION ACTIVITY:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.List;
import static android.R.id.list;
public class TriviaQuestion extends AppCompatActivity {
List<Question> questionList;
int score=0;
int questionID = 0;
Question currentQ;
TextView txtQuestion;
RadioButton rda,rdb,rdc;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trivia_question);
DBHandler db = new DBHandler(this);
questionList = db.getAllQuestions();
currentQ = questionList.get(questionID);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
setQuestionView();
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getqName());
rda.setText(currentQ.getqOptA());
rdb.setText(currentQ.getqOptB());
rdc.setText(currentQ.getqOptC());
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getqAns().equals(answer.getText())) {
score++;
}
currentQ = questionList.get(questionID);
setQuestionView();
}
});
}
}
TRIVIA QUESTION LAYOUT XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_trivia_question"
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="com.rasmussenandroid.sandra.edutrivia.TriviaQuestion">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.04" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="next" />
</LinearLayout>
</RelativeLayout>
The error tells you what the issue is - the SQL query is not constructed properly. There should be spaces between the individual terms - for example, CREATE TABLEquestion should be CREATE TABLE question.
Try the following line for CREATE_TABLE_QUESTION :
private static final String CREATE_TABLE_QUESTION ="CREATE TABLE "
+ TABLE_QUESTION +" ( "
+ KEY_QUESTIONID +" INTEGER PRIMARY KEY, "
+ KEY_QUESTION + " TEXT , "
+ KEY_OPTIONA + " TEXT, "
+ KEY_OPTIONB + " TEXT, "
+ KEY_OPTIONC + " TEXT, "
+ KEY_ANSWER + " TEXT, "
+ KEY_LEVEL + " INTEGER, "
+ KEY_CATEGORYID + " INTEGER "+")";

saving image in sqlite db using a save button

I'm a newbie in developing an android app and I am currently developing cooking application. I want to add a new recipe to my db with recipe name, ingredients, procedures, category, notes and photo. But the problem is when I add photo from camera or gallery, it stop working and I want to view the image taken to an imageview and save it to db using a save button. But please help me. I don't know what to do with my project.
MY DBAdapter
package com.elasandesu.quickeasykitchenv3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class 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_RNAME = "rname";
public static final String KEY_RCAT = "rcat";
public static final String KEY_RING = "ring";
public static final String KEY_RSTEPS = "rsteps";
public static final String KEY_RNOTE = "rnote";
public static final String KEY_RPHOTO = "rphoto";
//public static final String KEY_RPHOTONME = "rphotornme";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_RNAME = 1;
public static final int COL_RCAT = 2;
public static final int COL_RING = 3;
public static final int COL_RSTEPS = 4;
public static final int COL_RNOTE = 5;
public static final int COL_RPHOTO = 6;
//public static final int COL_RPHOTONME =7;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_RNAME, KEY_RCAT, KEY_RING, KEY_RSTEPS, KEY_RNOTE, KEY_RPHOTO};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Quick.sqlite";
public static final String DATABASE_TABLE = "recipe";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 5;
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_RNAME + " TEXT,"
+ KEY_RCAT + " TEXT," + KEY_RING+ " TEXT," + KEY_RSTEPS + " TEXT,"
+ KEY_RNOTE + " TEXT," + KEY_RPHOTO + " BLOB" + ")";
db.execSQL(CREATE_RECIPE_TABLE);
}
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
/*
* 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 initialValues = new ContentValues();
initialValues.put(KEY_RNAME, rName);
initialValues.put(KEY_RCAT, rCat);
initialValues.put(KEY_RING, rIng);
initialValues.put(KEY_RSTEPS, rSteps);
initialValues.put(KEY_RNOTE, rNote);
//initialValues.put(KEY_RPHOTO, rPhoto);
//initialValues.put(KEY_RPHOTONME, rPhotonme);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// 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);
if (c != null) {
c.moveToFirst();
}
return c;
}
//Get specific row by category
public Cursor getCateg (String categ) throws SQLException {
String where = "SELECT * FROM recipe where rcat=\""+categ+"\"";
Cursor c = db.rawQuery(where, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//KEY_RCAT + " = \'" + categ + " \'";
//"select * from contacts where id="+id+"", null
// 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 rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
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_RNAME, rName);
newValues.put(KEY_RCAT, rCat);
newValues.put(KEY_RING, rIng);
newValues.put(KEY_RSTEPS, rSteps);
newValues.put(KEY_RNOTE, rNote);
//newValues.put(KEY_RPHOTO, rPhoto);
// 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 SQLiteAssetHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
}
Activity Code
package com.elasandesu.quickeasykitchenv3;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Addrecipe extends Activity implements OnItemSelectedListener{
String[] cat = {"BEEF","CHICKEN",
"PORK", "FISH", "VEGETABLES"};
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
private String selectedImagePath;
String DB_NAME = Environment.getExternalStorageDirectory() + "/Quick.sqlite";
String TABLE_NAME = "recipe";
ImageView recphoto;
DBAdapter db;
EditText recname, recing, recsteps, recnote;
Spinner spinner1;
TextView category;
Button save, reset, upload;
public static String rcat = " ";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addrecipe);
category = (TextView) findViewById(R.id.categorytxtview);
spinner1 = (Spinner) findViewById(R.id.categorysp);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cat);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter_state);
spinner1.setOnItemSelectedListener(this);
save = (Button) findViewById(R.id.savebtn);
reset = (Button) findViewById(R.id.resetbtn);
recname = (EditText) findViewById(R.id.recipename);
recing = (EditText) findViewById(R.id.ingredient);
recnote = (EditText) findViewById(R.id.note);
recsteps = (EditText) findViewById(R.id.procedure);
recphoto= (ImageView) findViewById(R.id.image);
openDB();
final String[] option = new String[] { "Take from Camera", "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
Button addImage = (Button) findViewById(R.id.uploadbtn);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
//insert activity here :D
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras= data.getExtras();
if (extras != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage.compress(CompressFormat.PNG, 0, stream);
byte[] bytes = stream.toByteArray();
recphoto.setImageBitmap(selectedImage);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
recphoto.setImageURI(selectedImageUri);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("crop", "true");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
db = new DBAdapter(this);
db.open();
}
private void closeDB() {
db.close();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinner1.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void saveHasBeenClicked (View v) {
String rName = recname.getText().toString();
String rIng = recing.getText().toString();
String rSteps =recsteps.getText().toString();
String rNote = recnote.getText().toString();
String rCat = (String) spinner1.getSelectedItem();
long newId = db.insertRow(rName,"\n"+ rCat," \n "+ rIng," \n" + rSteps, rNote);
Cursor cursor = db.getRow(newId);
displayRecordSet(cursor);
Intent evilIntent = new Intent(Addrecipe.this, Selected.class);
startActivity(evilIntent);
}
public void onClick_ClearAll(View v) {
db.deleteAll();
Toast.makeText(getBaseContext(), "Cleared ", Toast.LENGTH_LONG).show();
}
// Display an entire record set to the screen.
private void displayRecordSet(Cursor cursor) {
String message = "";
// populate the message from the cursor
// Reset cursor to start, checking to see if there's data:
if (cursor.moveToFirst()) {
do {
// Process the data:
int id = cursor.getInt(DBAdapter.COL_ROWID);
String rName = cursor.getString(DBAdapter.COL_RNAME);
String rCat = cursor.getString(DBAdapter.COL_RCAT);
String rIng = cursor.getString(DBAdapter.COL_RING);
String rSteps = cursor.getString(DBAdapter.COL_RSTEPS);
String rNote = cursor.getString(DBAdapter.COL_RNOTE);
// Append data to the message:
message += "id=" + id
+", Recipe Name : " + rName
+", Category : " + rCat
+", Ingredients : " + rIng
+", Procedure: " + rSteps
+", Note: " + rNote
+"\n";
} while(cursor.moveToNext());
Toast.makeText(getBaseContext(), "Save Has Been Clicked "+ message, Toast.LENGTH_LONG).show();
}
// Close the cursor to avoid a resource leak.
cursor.close();
}
}
And the XML file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/clr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/nb"
android:onClick="displayClicked"
android:screenOrientation="landscape"
tools:ignore="HardcodedText" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1462dp" >
<EditText
android:id="#+id/recipename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/recipenametxtview"
android:layout_alignBottom="#+id/recipenametxtview"
android:layout_alignParentRight="true"
android:layout_marginRight="70dp"
android:ems="10"
android:hint="Type the Recipe Name"
tools:ignore="TextFields" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/categorytxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recipenametxtview"
android:layout_below="#+id/recipename"
android:layout_marginTop="50dp"
android:text="Category:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/ingtxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/categorytxtview"
android:layout_below="#+id/categorysp"
android:layout_marginTop="42dp"
android:text="Ingredients:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/categorysp"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignLeft="#+id/recipename"
android:layout_alignRight="#+id/recipename"
android:layout_alignTop="#+id/categorytxtview" />
<TextView
android:id="#+id/notetxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="253dp"
android:text="Note:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/ingredient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingtxtview"
android:layout_alignRight="#+id/categorysp"
android:layout_below="#+id/ingtxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type Here the Ingredients : e.g. 1 kilo of Flour"
android:inputType="text"
android:singleLine="false"
tools:ignore="TextFields" />
<EditText
android:id="#+id/procedure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_alignRight="#+id/ingredient"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type in this format 1.) procedure 1 [newline] 2.) procedure 2"
tools:ignore="TextFields" />
<EditText
android:id="#+id/note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/notetxtview"
android:layout_alignRight="#+id/procedure"
android:layout_below="#+id/notetxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Includes information, cautions and other health information"
tools:ignore="TextFields" />
<TextView
android:id="#+id/recipenametxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/itemRname"
android:layout_marginLeft="62dp"
android:layout_marginTop="67dp"
android:text="Recipe Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phototxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/note"
android:layout_below="#+id/note"
android:layout_marginTop="101dp"
android:text="Photo:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/proceduretxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingredient"
android:layout_below="#+id/ingredient"
android:layout_marginTop="172dp"
android:text="Procedure:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/uploadbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/phototxtview"
android:layout_alignBottom="#+id/phototxtview"
android:layout_toRightOf="#+id/ingtxtview"
android:text="Upload Photo" />
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_below="#+id/uploadbtn"
android:layout_marginTop="42dp"/>
<Button
android:id="#+id/resetbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/savebtn"
android:layout_alignBottom="#+id/savebtn"
android:layout_alignRight="#+id/note"
android:layout_marginRight="55dp"
android:onClick="onClick_ClearAll()"
android:text="Reset" />
<Button
android:id="#+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/uploadbtn"
android:layout_below="#+id/image"
android:layout_marginTop="56dp"
android:onClick="saveHasBeenClicked"
android:text="Save" />
</RelativeLayout>
</ScrollView>
please help me.. it will be a great help.

no such column: KEY_PUBNAME

Im making an app which stores data in an SQLite database. I want to be able to add, edit and delete data from this database. I can app to it no problem. I am currently working on trying to delete from the database but I keep getting the same error.
(1) no such column: KEY_PUBNAME
Here is my Java file:
package com.example.beer_budget3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
db.open();
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
Here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
And here is my database adapter:
package com.example.beer_budget3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not
null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;
// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
KEY_PUBNAME is clearly declared in the database adapter.
Any help would be great.
If you see your DatabaseHelper, you've defined following:
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
The keyname you've mentioned is KEY_PUBNAME. However where you've created the table, the keyname you've defined is Pub_Name. Over here:
public static final String KEY_PUBNAME = "Pub_Name";
That's why its not found. KEY_PUBNAME is the variable you've declared and not the name of the column. You may want to try to change it in db.delete statement.

How to get name from SQLite Database in android

I am developing an android application in when user enters in the app, the first activity asks his name to enter in textfield. By clicking on submit button, the name of the user stores in SQLite database and another activity opens and the name of the user will display in next activity. Now, I want something like that, if user closes the app and when he starts it again, then the name of the user should not be asked again and he should directly move to second activity with his name that he entered first time. This is my complete code below :
DatabaseHandler.java
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="Database1";// Database Name...
private static final String TABLE_NAME = "Name"; // Name of the Table...
private static final String KEY_ID = "id"; // Column1 of the table
private static final String KEY_NAME="UserName";// Column2 of the table
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "(" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null);";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHandler.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addName(Name name)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME, name.getUsername());
db.insert(TABLE_NAME, null, values);
db.close();
}
public Name getName(int id)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(TABLE_NAME, new String[]{ KEY_ID,KEY_NAME },KEY_ID +"=?",new String[] { String.valueOf(id) },null,null,null,null);
if(cursor!=null)
{
cursor.moveToFirst();
}
Name name = new Name(Integer.parseInt(cursor.getString(0)),cursor.getString(1));
return name;
}
public List<Name> getAllNames() {
List<Name> nameList = new ArrayList<Name>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Name name = new Name();
name.setId(Integer.parseInt(cursor.getString(0)));
name.setUsername(cursor.getString(1));
// Adding contact to list
nameList.add(name);
} while (cursor.moveToNext());
}
return nameList;
}
}
MainActivity.java
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class MainActivity extends Activity
{
Button submit;
EditText et1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit=(Button)findViewById(R.id.button1);
et1=(EditText)findViewById(R.id.editText1);
final DatabaseHandler db = new DatabaseHandler(this);
submit.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v1)
{
if(v1==submit)
{
String name1=et1.getText().toString();
Log.d("Insert: ", "Inserting ..");
db.addName(new Name(et1.getText().toString()));
Log.d("Reading: ", "Reading all contacts..");
List<Name> names = db.getAllNames();
for (Name n : names) {
String log = "Id: "+n.getId()+" ,Name: " + n.getUsername();
Log.d("Name: ", log);
}
Intent i1=new Intent(getApplicationContext(),NextPage.class);
i1.putExtra("name",name1);
startActivity(i1);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
}
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="com.example.database.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:ems="10"
android:hint="Please Enter Your Name"
android:inputType="textPersonName" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text=" Submit " />
</RelativeLayout>
I am not getting any idea about this how to do it.Please help me...
You could use Shared Preferences instead of a SQLte database. For just storing a name Shared Preferences are more than enough.
So when your application starts, you just check if the specific Shared Preferences are containing the users name and if not you ask the user about the name.
SharedPreferences settings = getSharedPreferences("PREFERENCES", MODE_PRIVATE);
if(settings.getString("USER_NAME", "").equals("")) {
//User has to enter the name
//Do the specific action
String user_name = ...
SharedPreferences.Editor editor = settings.edit();
editor.putString("USER_NAME", user_name);
editor.commit();
}
You will have to do a check to see if a name already exists in the database before you want to add. Change to:
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1) {
if(v1==submit) {
if( db.db.getAllNames() != null ) {
// Go directly to intent
} else {
// Ask a name
}
} );
}

Categories