How to retrieve data on button and move to Next button? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am working on an Android quiz . I have created my database with one question and four options along-with difficulty level. I have created a layout to display the question with four buttons . Now the problem is how will i connect my database with the question and four buttons.
so as to, when I click on right button it moves to the next question and when I click on wrong button it gives an error and exits.
Code In XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center_horizontal"
android:background="#drawable/background">
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="110dp"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="1dip"
android:paddingTop="1dip"
android:src="#drawable/logo2" />
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal">
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical"
android:background="#99CCFF"
android:id="#+id/group1">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#0000CC"
android:textStyle="bold" android:id="#+id/question"/>
<Button android:onClick="false" android:id="#+id/answer1"
android:layout_width="150dip" />
<Button android:onClick="false" android:id="#+id/answer2"
android:layout_width="150dip" />
<Button android:onClick="false" android:id="#+id/answer3"
android:layout_width="150dip"/>
<Button android:onClick="false" android:id="#+id/answer4"
android:layout_width="150dip" />
</RadioGroup>
</LinearLayout>
MY DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.starchazer.cyk/databases/";
private static String DB_NAME = "questionsDb";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(!dbExist)
{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
public List<Question> getQuestionSet(int difficulty, int numQ){
List<Question> questionSet = new ArrayList<Question>();
Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty +
" ORDER BY RANDOM() LIMIT " + numQ, null);
while (c.moveToNext()){
//Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
Question q = new Question();
q.setQuestion(c.getString(1));
q.setAnswer(c.getString(2));
q.setOption1(c.getString(3));
q.setOption2(c.getString(4));
q.setOption3(c.getString(5));
q.setRating(difficulty);
questionSet.add(q);
}
return questionSet;
}
}
MY QuestionActivity
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
/**
* Configure current game and get question
*/
currentGame = ((XYZ_Application)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button c1 = (Button) findViewById(R.id.answer1 );
c1.setOnClickListener(this);
Button c2 = (Button) findViewById(R.id.answer2 );
c2.setOnClickListener(this);
Button c3 = (Button) findViewById(R.id.answer3 );
c3.setOnClickListener(this);
Button c4 = (Button) findViewById(R.id.answer4 );
c4.setOnClickListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current games
* current question
*/
private void setQuestions() {
//set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion()) + "?";
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
//set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
}
#Override
public void onClick(View arg0) {
/**
* validate a buttonselected has been selected
*/
if (!checkAnswer()) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
Intent i = new Intent(this, Main.class);
startActivity(i);
finish();
}
else{
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it
* has then check if its correct and update gamescore
*/
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer==null){
return false;
}
else {
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
//Log.d("Questions", "Correct Answer!");
currentGame.incrementRightAnswers();
}
else{
//Log.d("Questions", "Incorrect Answer!");
currentGame.incrementWrongAnswers();
}
return true;
}
}
/**
*
*/
private String getSelectedAnswer() {
Button c1 = (Button)findViewById(R.id.answer1);
Button c2 = (Button)findViewById(R.id.answer2);
Button c3 = (Button)findViewById(R.id.answer3);
Button c4 = (Button)findViewById(R.id.answer4);
if (c1.callOnClick())
{
return c1.getText().toString();
}
if (c2.callOnClick())
{
return c2.getText().toString();
}
if (c3.callOnClick())
{
return c3.getText().toString();
}
if (c4.callOnClick())
{
return c4.getText().toString();
}
return null;
}
}

I am sorry I will not be giving code here.
Here is what I would have done
When Actvity Starts
Load Question from Db with Options
I ll prefer option as array/arraylist
Assign Text Option to each button
Add a common onclick listener like this
public void onClick(View v){
int id=v.getId();
String answer=v.getText();
if(answer.equals('ANSWER FROM DB'){
// If right then next question
// Else to MainActivity
}
/**switch(id){
case R.id.answer1:
processAnswer(1);
break;
case R.id.answer2:
processAnswer(2);
break;
// So on
}
**/
}
And processAnswer would look like
void processAnswer(int option){
// Since I have the option here
// I will check it with Database
// If its correct then next question else exit
}

Related

I need to hide a radio button in a quiz app android

I would like to ask for some help with my android code. I am trying to develop a quiz app using SQLite.Number of possible answers differs so i need to hide radio buttons from the main screen if answers e.g. are 3 and not 4 (4 is by default the number of the radio buttons). Tried to use:
if (DataContract.QuestionTable.COLUMN_ANSWER4.isEmpty ()){ radioButton4.setVisibility (View.INVISIBLE); }
but does not seem to work.I'm new in android programming and this is my first project so every comment will be very helpful. Thank you.
Here's a demo with a suggested technique, considering the limited amount of code posted with the question.
This utilises two tables to conform with a normalised approach. A table for the questions and a table for answers. Each answer (the Children) has a link/map/relationship/association with a single Question (the Parent). To prevent referential integrity issues a Foreign Key constraint has been used.
First a few POJO's for the Questions, the Answers and QuestionWithAnswers (i.e. it's answers)
QuestionPOJO
class QuestionPOJO {
long questionId;
String questionText;
public QuestionPOJO(long questionId, String questionText) {
this.questionId = questionId;
this.questionText = questionText;
}
public long getQuestionId() {
return questionId;
}
public void setQuestionId(long questionId) {
this.questionId = questionId;
}
public String getQuestionText() {
return questionText;
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
}
AnswerPOJO
class AnswerPOJO {
long answerId;
long questionMap;
String answerText;
boolean correct = false;
public AnswerPOJO(long answerid, long questionMap, String answerText, boolean correct) {
this.answerId = answerid;
this.questionMap = questionMap;
this.answerText = answerText;
this.correct = correct;
}
public long getAnswerId() {
return answerId;
}
public void setAnswerId(long answerId) {
this.answerId = answerId;
}
public long getQuestionMap() {
return questionMap;
}
public void setQuestionMap(long questionMap) {
this.questionMap = questionMap;
}
public boolean isCorrect() {
return correct;
}
public void setCorrect(boolean correct) {
this.correct = correct;
}
public String getAnswerText() {
return answerText;
}
public void setAnswerText(String answerText) {
this.answerText = answerText;
}
}
and QuestionWithAnswerPOJO
class QuestionWithAnswersPOJO {
QuestionPOJO question;
ArrayList<AnswerPOJO> answers = new ArrayList<>();
public QuestionWithAnswersPOJO(QuestionPOJO question, List<AnswerPOJO> answers) {
this.question = question;
this.answers.clear();
this.answers.addAll(answers);
}
public QuestionPOJO getQuestion() {
return question;
}
public void setQuestion(QuestionPOJO question) {
this.question = question;
}
public ArrayList<AnswerPOJO> getAnswers() {
return answers;
}
public void setAnswers(ArrayList<AnswerPOJO> answers) {
this.answers = answers;
}
}
Now the DatabaseHelper, that handles all the database activity. Including methods to add and get Questions and the Answers and notably to get the Answers that belong to a question.
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "questions.db";
public static final int DATABASE_VERSION = 1;
public static final String QUESTION_TABLE = "question";
public static final String QUESTION_ID_COLUMN = BaseColumns._ID;
public static final String QUESTION_TEXT_COLUMN = "question_text";
public static final String ANSWER_TABLE = "answer";
public static final String ANSWER_ID_COLUMN = BaseColumns._ID;
public static final String ANSWER_TEXT_COLUMN = "answer_text";
public static final String ANSWER_QUESTION_MAP_COLUMN = "question_map";
public static final String ANSWER_CORRECT_COLUMN = "correct";
private static volatile DatabaseHelper instance = null;
private DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
private static SQLiteDatabase db = null;
public static DatabaseHelper getInstance(Context context, boolean forceOpen) {
if (instance == null) {
instance = new DatabaseHelper(context);
}
if (forceOpen) {
db = instance.getWritableDatabase();
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + QUESTION_TABLE + "(" +
QUESTION_ID_COLUMN + " INTEGER PRIMARY KEY," +
QUESTION_TEXT_COLUMN + " TEXT" +
");");
db.execSQL("CREATE TABLE IF NOT EXISTS " + ANSWER_TABLE + "(" +
ANSWER_ID_COLUMN + " INTEGER PRIMARY KEY," +
ANSWER_TEXT_COLUMN + " TEXT," +
ANSWER_QUESTION_MAP_COLUMN + " INTEGER REFERENCES " + QUESTION_TABLE + "(" + QUESTION_ID_COLUMN + ") ON DELETE CASCADE ON UPDATE CASCADE," +
ANSWER_CORRECT_COLUMN + " INTEGER DEFAULT 0 /* false */" +
");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
// Fully comprehensive Question insert
public long insertQuestion(Long questionId, String questionText) {
init_db_AsWriteableDatabase();
long rv = -2;
ContentValues cv = new ContentValues();
if (questionId != null && questionId > 0) {
cv.put(QUESTION_ID_COLUMN,questionId);
}
if (questionText != null && questionText.length() > 0) {
cv.put(QUESTION_TEXT_COLUMN,questionText);
}
if (cv.size() > 0) {
rv = db.insert(QUESTION_TABLE,null,cv);
}
return rv;
}
// Concise Question insert
public long insertQuestion(String questionText) {
return insertQuestion(null,questionText);
}
// Fully comprehensive Answer insert
public long insertAnswer(Long answerId, long questionMap, String answerText, boolean correct) {
init_db_AsWriteableDatabase();
long rv = -2;
ContentValues cv = new ContentValues();
if (answerId != null && answerId > 0) {
cv.put(ANSWER_ID_COLUMN,answerId);
}
if (answerText != null && answerText.length() > 0) {
cv.put(ANSWER_CORRECT_COLUMN,correct);
cv.put(ANSWER_TEXT_COLUMN,answerText);
cv.put(ANSWER_QUESTION_MAP_COLUMN,questionMap);
rv = db.insert(ANSWER_TABLE,null,cv);
}
return rv;
}
// long concise Answer insert
public long insertAnswer(long questionMap, String answerText, boolean correct) {
return insertAnswer(null,questionMap,answerText,correct);
}
public long insertAnswer(long questionMap, String answerText) {
return insertAnswer(questionMap,answerText,false);
}
// short concise Answer insert
private void init_db_AsWriteableDatabase() {
if (db == null) {
db = this.getWritableDatabase();
}
}
#SuppressLint("Range")
public QuestionPOJO getQuestionById(long questionId) {
QuestionPOJO rv = null;
init_db_AsWriteableDatabase();
Cursor csr = db.query(QUESTION_TABLE,null,QUESTION_ID_COLUMN+"=?",new String[]{String.valueOf(questionId)},null,null,null);
if (csr.moveToNext()) {
rv = new QuestionPOJO(csr.getLong(csr.getColumnIndex(QUESTION_ID_COLUMN)),csr.getString(csr.getColumnIndex(QUESTION_TEXT_COLUMN)));
}
csr.close();
return rv;
}
#SuppressLint("Range")
public List<AnswerPOJO> getAnswersForQuestion(long questionId, boolean onlyCorrect) {
init_db_AsWriteableDatabase();
ArrayList<AnswerPOJO> rv = new ArrayList<>();
StringBuilder whereClause = new StringBuilder();
whereClause.append(ANSWER_QUESTION_MAP_COLUMN + "=?");
if (onlyCorrect) {
whereClause.append(" AND ").append(ANSWER_CORRECT_COLUMN);
}
Cursor csr = db.query(ANSWER_TABLE,null,whereClause.toString(),new String[]{String.valueOf(questionId)},null,null,null);
while (csr.moveToNext()) {
rv.add(
new AnswerPOJO(
csr.getLong(csr.getColumnIndex(ANSWER_ID_COLUMN)),
questionId,
csr.getString(csr.getColumnIndex(ANSWER_TEXT_COLUMN)),
csr.getInt(csr.getColumnIndex(ANSWER_CORRECT_COLUMN)) > 0
)
);
}
csr.close();
return rv;
}
}
Finally to put it all together and activity that has a layout for 4 radio buttons along with the associated answer as a TextView.
So the layout is:-
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!">
</TextView>
<RadioGroup
android:id="#+id/question_radiogroup"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/answer1_radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="DuplicateSpeakableTextCheck"></RadioButton>
<TextView
android:id="#+id/answer1_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<RadioButton
android:id="#+id/answer2_radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioButton>
<TextView
android:id="#+id/answer2_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<RadioButton
android:id="#+id/answer3_radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioButton>
<TextView
android:id="#+id/answer3_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<RadioButton
android:id="#+id/answer4_radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RadioButton>
<TextView
android:id="#+id/answer4_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</RadioGroup>
</LinearLayout>
simple enough to show how hiding the buttons depending upon the number of answers (or a limit according to the number of Buttons/Textviews)
And the activity to demonstrate:-
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbHelper;
RadioButton[] radiobuttons = new RadioButton[4];
TextView[] answerTexts = new TextView[4];
QuestionWithAnswersPOJO currentQuestionWithAnswers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
prepare Radion Buttons and associated TextViews
*/
radiobuttons[0] = this.findViewById(R.id.answer1_radioButton);
radiobuttons[1] = this.findViewById(R.id.answer2_radioButton);
radiobuttons[2] = this.findViewById(R.id.answer3_radioButton);
radiobuttons[3] = this.findViewById(R.id.answer4_radioButton);
answerTexts[0] = this.findViewById(R.id.answer1_textview);
answerTexts[1] = this.findViewById(R.id.answer2_textview);
answerTexts[2] = this.findViewById(R.id.answer3_textview);
answerTexts[3] = this.findViewById(R.id.answer4_textview);
/*
Prepare to use Database
*/
dbHelper = DatabaseHelper.getInstance(this,true);
SQLiteDatabase db = dbHelper.getWritableDatabase();
/* Clear any existing data for consistent results */
db.delete(DatabaseHelper.ANSWER_TABLE,null,null);
db.delete(DatabaseHelper.QUESTION_TABLE,null,null);
/* Add some demo data 1 question with 5 answers (comment out to reduce number of answers)*/
long q1id = dbHelper.insertQuestion("What is 1 + 1");
dbHelper.insertAnswer(q1id,"It is 1");
dbHelper.insertAnswer(q1id,"it is 2", true);
dbHelper.insertAnswer(q1id,"It is 3");
dbHelper.insertAnswer(q1id,"It is 4");
dbHelper.insertAnswer(q1id,"It is something Else"); // will be ignored because only 4 radio buttons
/* Get the question with the answers, however many ot has */
currentQuestionWithAnswers = new QuestionWithAnswersPOJO(dbHelper.getQuestionById(q1id),dbHelper.getAnswersForQuestion(q1id,false));
/* setup (refresh) the radio buttons and textviews */
getAndSetRadioButtons(currentQuestionWithAnswers);
}
/*
Does as it says
*/
private void getAndSetRadioButtons(QuestionWithAnswersPOJO qwa) {
// Clear All
for (int i=0;i < radiobuttons.length; i++) {
radiobuttons[i].setVisibility(View.GONE);
answerTexts[i].setText("");
answerTexts[i].setVisibility(View.GONE);
}
/* show only the least of answers/radio buttons */
int numberToShow = radiobuttons.length;
if (qwa.answers.size() < radiobuttons.length) {
numberToShow = qwa.answers.size();
}
int i = 0;
for(AnswerPOJO a: qwa.answers) {
if (i < numberToShow) {
radiobuttons[i].setVisibility(View.VISIBLE);
answerTexts[i].setVisibility(View.VISIBLE);
answerTexts[i++].setText(a.answerText);
} else {
/* nothing more to do so early break out of the loop */
break;
}
}
}
}
Results
Result 1 - run with the 5 answers (see comments re 5th answer)
Result 2 - All bar 1 answer comment out so the question has just the 1 answer
The code used:-
long q1id = dbHelper.insertQuestion("What is 1 + 1");
dbHelper.insertAnswer(q1id,"It is 1");
//dbHelper.insertAnswer(q1id,"it is 2", true);
//dbHelper.insertAnswer(q1id,"It is 3");
//dbHelper.insertAnswer(q1id,"It is 4");
//dbHelper.insertAnswer(q1id,"It is something Else"); // will be ignored because only 4 radio buttons
The display :-
Result 3 - first and 5th answers only inserted
and so on.
Additional after code has been posted.
Additional Answer as code has now been added.
You say:-
Tried to use:
if (DataContract.QuestionTable.COLUMN_ANSWER4.isEmpty ()){ radioButton4.setVisibility (View.INVISIBLE); }
but does not seem to work.
If DataContract.QuestionTable.COLUMN_ANSWER4 were empty then would be facing more serious issues as it is the column name.
You should be checking for the contents of the column which has been retrieved from DB and placed into currentQuestion, for the question being inspected.
I believe that using (old code commented out):-
radioButton1.setText(currentQuestion.getAnswer1 ());
radioButton2.setText(currentQuestion.getAnswer2 ());
radioButton3.setText(currentQuestion.getAnswer3 ());
radioButton4.setText(currentQuestion.getAnswer4 ());
if(currentQuestion.getAnswer4() == null || currentQuestion.getAnswer4().isEmpty()) {
radioButton4.setVisibility(View.INVISIBLE);
} else {
radioButton4.setVisibility(View.VISIBLE); // just in case it is INVISIBLE
radioButton4.setText(currentQuestion.getAnswer4());
}
/*
if (DataContract.QuestionTable.COLUMN_ANSWER4.isEmpty ()){
radioButton4.setVisibility (View.INVISIBLE);
} else {
radioButton4.setText(currentQuestion.getAnswer4 ());
}
*/
Will resolve this issue. e.g. at Q3:-

Updating a certain value and saving it in offline database

I'm developing a tiny app that has a value in a textview set to 150,000 by default. Each month I reset the value back to the default. Every time I spend some of that amount, I open my app and enter the amount I spent and the details of what it was spent on.
What I did was create an offline database to store all the times I spent some of that amount, along with it's id and details. Each time I press the "spend" button, the total amount is reduced by the amount I have entered in the EditText.
I haven't implemented how I'll update the total amount yet, I believe I have to use something called sharedpreference number.
This is the main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button spendMoney = (Button)this.findViewById(R.id.spendMoney);
Button test = (Button)this.findViewById(R.id.test);
TextView totalTxt = (TextView) this.findViewById(R.id.totalTxt);
final EditText spendAmount = (EditText)this.findViewById(R.id.spendAmount);
// int totalAmount = Integer.parseInt(totalTxt.getText().toString());
final Paid_DB db = new Paid_DB(this);
spendMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.addPayment(new Payment(0, (Integer.parseInt(spendAmount.getText().toString())), "Test Details"));
}
});
//totalAmount = totalAmount - Integer.parseInt(spendAmount.getText().toString());
// totalTxt.setText(totalAmount);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(null, DetailsActivity.class);
startActivity(i);
}
});
XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.paid.MainActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="13dp"
android:layout_marginStart="13dp"
android:layout_marginTop="53dp"
android:fontFamily="sans-serif"
android:text="Total:"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<EditText
android:id="#+id/spendAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="72dp"
tools:layout_editor_absoluteY="143dp"
android:layout_marginBottom="38dp"
android:layout_above="#+id/spendMoney"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/spendMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spend Money"
tools:layout_editor_absoluteX="115dp"
tools:layout_editor_absoluteY="215dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/totalTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView3"
android:layout_alignBottom="#+id/textView3"
android:layout_alignEnd="#+id/spendMoney"
android:layout_alignRight="#+id/spendMoney"
android:fontFamily="sans-serif"
android:text="150,000"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<Button
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
tools:layout_editor_absoluteX="134dp"
tools:layout_editor_absoluteY="358dp"
android:layout_marginBottom="90dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/spendMoney"
android:layout_alignStart="#+id/spendMoney" />
This is the object I enter into the offline database, containing the id, the amount spent, and details of the payment:
public class Payment {
private int id;
private int amount;
private String details;
public Payment(){}
public Payment(int id, int amount, String details) {
this.id = id;
this.amount = amount;
this.details = details;
}
public Payment(int id, int amount) {
this.id = id;
this.amount = amount;
}
public Payment(int amount, String details) {
this.amount = amount;
this.details = details;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
} }
This is the offline database:
ublic class Paid_DB extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Payments_DB";
// Contacts table name
private static final String PAYMENT_TABLE = "PaymentTable";
// Contacts Table Columns names
private static final String PAY_ID = "id";
private static final String PAY_AMOUNT = "amount";
private static final String PAY_DETAILS = "details";
Paid_DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + PAYMENT_TABLE + "("
+ PAY_ID + " INTEGER PRIMARY KEY," + PAY_AMOUNT + " INTEGER,"
+ PAY_DETAILS + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + PAYMENT_TABLE);
onCreate(db);
}
public void addPayment(Payment payment){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PAY_AMOUNT, payment.getAmount());
values.put(PAY_DETAILS, payment.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(PAYMENT_TABLE, null, values);
db.close();
}
void addListItem(ArrayList<String> listItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < listItem.size(); i++) {
Log.e("vlaue inserting==", "" + listItem.get(i));
values.put(PAY_AMOUNT, listItem.get(i));
db.insert(PAYMENT_TABLE, null, values);
}
db.close(); // Closing database connection
}
Cursor getListItem() {
String selectQuery = "SELECT * FROM " + PAYMENT_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}}
And finally, this is the details activity, it contains a list view that stores and displays all the payments that have been made:
public class DetailsActivity extends AppCompatActivity {
ArrayList<String> detailsListArrayList;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
lv = (ListView) findViewById(R.id.listView);
detailsListArrayList = new ArrayList<>();
detailsListArrayList.add("Item1");
detailsListArrayList.add("Item2");
detailsListArrayList.add("Item3");
detailsListArrayList.add("Item4");
detailsListArrayList.add("Item5");
Paid_DB db = new Paid_DB(this);
db.addListItem(detailsListArrayList);
Cursor cursor = db.getListItem();
Log.e("count", " " + cursor.getCount());
if (cursor != null) {
cursor.moveToNext();
do {
Log.e("value==", "" + cursor.getString(1));
} while (cursor.moveToNext());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
detailsListArrayList );
lv.setAdapter(arrayAdapter);
}
}
XML file:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.paid.DetailsActivity">
<ListView
android:id="#+id/listView"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
Every time I click on the "test" button, the app crashes. And every time I try to add a new entry using the "spend" button, the app also crashes. What did I do wrong?
What I can tell from here (without the error log) is:
1) your app crashes when pressing the test-button because you are starting an activity there without passing a contextobject. Try this:
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
startActivity(i);
}
2) The spend button tries to add a new payment entry to your database. But in your database schema , you declare the PAY_ID as a primary key. Later in your addPayment() you are just passing the PAY_AMOUNT and PAY_DETAILS, so you are missing the PAY_ID which seems to lead to a crash.
EDIT: something like this should return all the payments as an ArrayList (may Contain bugs, just wrote it in this editor).
public ArrayList<Payment> getAllPayments() {
ArrayList<Payment> result = new ArrayList<>();
Cursor c = db.query("PAYMENTS",new String[]{"PAY_ID","PAY_AMOUNT","PAY_DETAIL"},null,null,null,null,null); ;
c.moveToFirst();
while(! c.isAfterLast())
{
int s1=c.getInt(0);
int s2=c.getInt(1);
String s3=c.getString(2);
results.add(new Payment(s1,s2,s3));
c.moveToNext();
}
return results;
}
To update your ListView, you should have a closer look a this link, that explains how to work with ListViews and a custom ListView adapter Custom Adapter for List View

Android - Change SQLite value based on ToggleButton Image

I want to make an quote app which display the quote, the author, and a fav button.
I have a custom ListView which has 2 textViews, and 1 Toggle Button
I'm using SQLite with pre-populated data (So i already have all of the data)
I can populate my 2 textViews with my quote (from quote table) and author (from author table) using SimpleCursorAdapter
The Problem is, i have 1 ToggleButton which has:
Grey Heart image when its not selected (value 0)
Red Heart image when its selected (value 1)
What i want is
When the user click on the grey heart image (fav button), the image change to the red heart image and also updates the fav table in SQLite from 0 to 1.
When the user click on the red heart image (fav button), the image change to the grey heart image and also updates the fav table in SQLite from 1 to 0.
And when the user exit, and goes to my application again. i want the quotes that the user has already favorited before (value 1) still have red heart image.
Here is the code:
DatabaseOpenHelper.java
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";
public static final String COLUMN_GENRE = "genre";
private SQLiteDatabase database;
private final Context context;
// database path
private static String DATABASE_PATH;
/** constructor (Menambil PATH ke file database) */
public DatabaseOpenHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
this.context = ctx;
DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
+ "/databases/";
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void create() throws IOException {
boolean check = checkDataBase();
SQLiteDatabase db_Read = null;
// Creates empty database default system path
db_Read = this.getWritableDatabase();
db_Read.close();
try {
if (!check) {
copyDataBase();
}
} catch (IOException e) {
throw new Error("Error copying database");
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/** Start DB from here */
/** open the database */
public void open() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
database = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
/** close the database */
#Override
public synchronized void close() {
if (database != null)
database.close();
super.close();
}
// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_QUOTES, quotesText );
initialValues.put(COLUMN_AUTHOR, author);
initialValues.put(COLUMN_FAV, fav);
return database.insert(TABLE_NAME, null, initialValues);
}
// updates a user
public boolean updateUser(long rowId, String fav) {
ContentValues args = new ContentValues();
args.put(COLUMN_FAV, fav);
return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
COLUMN_ID + " = " + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// delete a particular user
public boolean deleteContact(long rowId) {
return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}
// retrieves all users
public Cursor getAllUsers() {
return database.query(TABLE_NAME, new String[] { COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
null, null, null);
}
public Cursor getCertain(String valueGenre) {
String WHERE = "genre = ?";
String[] VALUE = new String[] {valueGenre};
return database.query(TABLE_NAME, new String[]{COLUMN_ID,
COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV}, WHERE, VALUE,
null, null, null);
}
quotes_listview (Custom ListView)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/txtQuote"
style="#style/QuotesFont"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_rowWeight="1"
android:layout_weight="1"
android:layout_margin="15dp" />
<ToggleButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/heartImage"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="30dp"
android:background="#drawable/fav"
android:textOff=""
android:textOn=""
android:layout_rowWeight="1"
android:layout_weight="3"
android:descendantFocusability="blocksDescendants"
android:layout_marginLeft="30dp"
android:layout_marginRight="15dp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/txtAuthor"
style="#style/AuthorFont"
android:layout_below="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp"
android:layout_marginBottom="5dp" />
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="New Text"-->
<!--android:id="#+id/text2"-->
<!--android:layout_below="#+id/text1"-->
<!--android:layout_alignParentRight="true"-->
<!--android:layout_alignParentEnd="true"-->
<!--style="#style/AuthorFont"-->
<!--android:layout_marginBottom="10dp"-->
<!--android:layout_rowWeight="1"-->
<!--android:layout_weight="1" />-->
QuotesActivity.java
public class QuotesActivity extends AppCompatActivity {
ListView quotesList;
DatabaseOpenHelper myDbHelper;
ArrayList<ListOfQuotes> arrQuotes;
QuotesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.open();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
quotesList = (ListView) findViewById(R.id.quotesList);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.genre_array, R.layout.spinner_item);
// Specify the layout to use when the list of choices appears
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//ALL
if (id == 0) {
populateListView();
}
//Entrepreneur
else if (id == 1) {
populateListViewEntrepreneur();
}
//Love
else if (id == 2) {
populateListViewLove();
}
//Work
else if (id == 3) {
populateListViewWork();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Call Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
//Custom Image Back Button
toolbar.setNavigationIcon(R.drawable.back_button);
setSupportActionBar(toolbar);
//To make the title from Android Manifest appear, comment the code below
getSupportActionBar().setDisplayShowTitleEnabled(false);
//Make the app only portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void populateListView() {
Cursor cursor = myDbHelper.getAllUsers();
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewEntrepreneur() {
String testing = "Entrepreneur";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewLove() {
String testing = "Love";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}
private void populateListViewWork() {
String testing = "Work";
Cursor cursor = myDbHelper.getCertain(testing);
String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
int[] to = new int[] {R.id.txtQuote, R.id.txtAuthor};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
quotesList.setAdapter(myCursorAdapter);
}

Android - Import database get nullpointerexception on rawquery

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

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.

Categories