I am creating a quiz with different question types. To call these types I would like to use Enum then a switch statement in my activity to make a specific type visible.
Here is what I have in my Question class
public class Question {
private String question;
private String option1;
private String option2;
private String option3;
private int answerNumber;
private enum type {RADIO, CHECKBOX, TEXTENTRY};
public Question(){}
public Question(String question, String option1, String option2, String option3, int answerNumber, int type) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.type = type; // expression expected, not sure how to approach this
}
}
I manually created my getters + setters as I receive this message if I try to generate them with Android Studio
'no fields without getter + setter where found'
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
This is what I have in my DBHelper.
private void fillQuestionsTable() {
Question q1 = new Question("1 is correct", "a", "b","c",1,0);
addQuestion(q1);
Question q2 = new Question("2 is correct", "a", "b","c",2,1);
addQuestion(q2);
Question q3 = new Question("3 is correct", "a", "b","c",3,2);
addQuestion(q3);
}
private void addQuestion(Question question){
ContentValues cv = new ContentValues();
cv.put(QuestionsTable.COLUMN_QUESTION, question.getQuestion());
cv.put(QuestionsTable.COLUMN_OPTION1, question.getOption1());
cv.put(QuestionsTable.COLUMN_OPTION2, question.getOption2());
cv.put(QuestionsTable.COLUMN_OPTION3, question.getOption3());
cv.put(QuestionsTable.COLUMN_ANSWERNUMBER, question.getAnswerNumber());
cv.put(QuestionsTable.COLUMN_TYPE, question.getType());
db.insert(QuestionsTable.TABLE_NAME,null, cv);
}
public List<Question> getAllQuestions(){
List<Question> questionList = new ArrayList <>();
db = getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME, null);
if (c.moveToFirst()){
do {
Question question = new Question();
question.setQuestion(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION2)));
question.setOption3(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION3)));
question.setAnswerNumber(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_ANSWERNUMBER)));
question.setType(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_TYPE)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();
return questionList;
}
And in my activity this is what I am using to try and switch the question types
-All views set to INVISIBLE to start then methods to make them VISIBLE-
private void showNextQuestion(){
if (questionCounter < getQuestionCounter){
currentQuestion = questionList.get(questionCounter);
question.setText(currentQuestion.getQuestion());
rb1.setText(currentQuestion.getOption1());
rb2.setText(currentQuestion.getOption2());
rb3.setText(currentQuestion.getOption3());
//switch question formats
int type = (int)
question.setText(currentQuestion.getQuestion()).questionList.get.questionType;
switch (questionType) {
// seems to like questionList better in here... still not sure how to bring up the enums
case Question.RADIO:
showRadioGroup();
break;
case Question.CHECKBOX:
showCheckboxes();
break;
case Question.TEXTENTRY:
showTypeAnswer();
break;
}
questionCounter++;
The idea is to bring everything from my Array - yes? -a bit confused here-
if I use questionList which is my array can't resolve
if I use getAllQuestions in case can't resolve getAllQuestions
if I use typeAnswer or questionList in case can't resolve RADIO nor TEXTENTRY
Sorry I was trying different approaches.
Also just realized I will have a hard time trying to verify a text entry with the code as is. Working on it.
Roughly speaking when you say private enum type {RADIO, CHECKBOX, TEXTENTRY}; you can (need to) then use type like as if it were a class.
So you need an additional line to declare an object of type for it to be a memeber ( enum ??? {...} is implicitly static and final (if my limited understanding is correct)) e.g. :-
private mytype = type;
Here's some code that may help you understand how to construct (in a few ways), get and set using enums :-
public class Question {
public enum qtype {RADIO,CHECKBOX,TEXTENTRY} //<<< accessible outside perhaps prefereable
private enum altqtype {RADIO, CHECKBOX, TEXTENTRY} //<<<< Alternative if you want private (restrictive)
private String question;
private String option1;
private String option2;
private String option3;
private int answerNumber;
private long Id;
// Define members of the enum's
private qtype mytype;
private altqtype alternative_qtype;
private qtype another;
public Question(){}
public Question(
String question,
String option1,
String option2,
String option3,
int answerNumber,
int type, //<<<< pass as an int
String stype, //<<<< pass as a String
long id, //<<<< likely needed
qtype questiontype //<<<< pass as an qtype (e.g. qtype.RADIO)
) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.Id = id; //<<<< You may well need this to reference DB from Arraylist
// Setting enum's
this.mytype = questiontype; // set to passed value
this.alternative_qtype = altqtype.CHECKBOX; // Sets to default
// Set it accoring to the string passed
if (isValidTypeString(stype)) {
this.alternative_qtype = altqtype.valueOf(stype);
}
this.another = convertIntToQtype(type);
}
public qtype getMytype() {
return mytype;
}
public void setMytype(qtype mytype) {
this.mytype = mytype;
}
//Given an int convert it to a qtype
private qtype convertIntToQtype(int type){
qtype rv = qtype.TEXTENTRY;
switch (type) {
case 1:
rv = qtype.RADIO;
break;
case 2:
rv = qtype.CHECKBOX;
break;
case 4:
rv = qtype.TEXTENTRY;
break;
default:
rv = qtype.TEXTENTRY;
}
return rv;
}
// Check if a given string is valid as a question type
// Note done for alternative
private boolean isValidTypeString(String pv) {
boolean rv = false;
altqtype[] typearray = altqtype.values();
for (altqtype aqt: typearray) {
if (pv.equals(aqt.toString())) {
rv = true;
break;
}
}
return rv;
}
}
Working Example
here's a working example that :-
utilises enum's
utilises both ArrayList and Cursor
ArrayList used for asking question and for List of questions (2nd)
Cursor used for List of questions (1st List)
traverses questions via PREVIOUS and NEXT buttons
Allows answer (no answer checking) to be one of Edit text, Radio Button or Checkbox according to to the question, displaying the appropriate View.
Question.java
public class Question {
public enum qtype {RADIO,CHECKBOX,TEXTENTRY} //<<< accessible outside perhaps prefereable
private enum altqtype {RADIO, CHECKBOX, TEXTENTRY} //<<<< Alternative if you want private (restrictive)
private String question;
private String option1;
private String option2;
private String option3;
private int answerNumber;
private long rowid;
// Define members of the enum's
private qtype mytype;
private altqtype alternative_qtype;
private qtype another;
public Question(){}
public Question(
String question, String option1, String option2, String option3,
int answerNumber, qtype type, long id) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.mytype = type;
this.rowid = id;
}
public Question(
String question, String option1, String option2, String option3,
int answerNumber, qtype type
){
this(question,option1,option2,option3,answerNumber,type,-1);
}
//<<<< Note constrcutor for demonstration of enums
public Question(
String question,
String option1,
String option2,
String option3,
int answerNumber,
int type, //<<<< pass as an int
String stype, //<<<< pass as a String
long id, //<<<< likely needed
qtype questiontype //<<<< pass as an qtype (e.g. qtype.RADIO)
) {
this.question = question;
this.option1 = option1;
this.option2 = option2;
this.option3 = option3;
this.answerNumber = answerNumber;
this.rowid = id; //<<<< You may well need this to reference DB from Arraylist
// Setting enum's
this.mytype = questiontype; // set to passed value
this.alternative_qtype = altqtype.CHECKBOX; // Sets to default
// Set it accoring to the string passed
if (isValidTypeString(stype)) {
this.alternative_qtype = altqtype.valueOf(stype);
}
this.another = convertIntToQtype(type);
}
public qtype getMytype() {
return mytype;
}
public void setMytype(qtype mytype) {
this.mytype = mytype;
}
//Given an int convert it to a qtype
private qtype convertIntToQtype(int type){
qtype rv = qtype.TEXTENTRY;
switch (type) {
case 1:
rv = qtype.RADIO;
break;
case 2:
rv = qtype.CHECKBOX;
break;
case 4:
rv = qtype.TEXTENTRY;
break;
default:
rv = qtype.TEXTENTRY;
}
return rv;
}
// Check if a given string is valid as a question type
// Note done for alternative
private static boolean isValidTypeString(String pv) {
boolean rv = false;
altqtype[] typearray = altqtype.values();
for (altqtype aqt: typearray) {
if (pv.equals(aqt.toString())) {
rv = true;
break;
}
}
return rv;
}
public static qtype convertStringToQtype(String s) {
qtype rv = qtype.TEXTENTRY; // <<<< Default
if (isValidTypeString(s)) {
rv = qtype.valueOf(s);
}
return rv;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getOption1() {
return option1;
}
public void setOption1(String option1) {
this.option1 = option1;
}
public String getOption2() {
return option2;
}
public void setOption2(String option2) {
this.option2 = option2;
}
public String getOption3() {
return option3;
}
public void setOption3(String option3) {
this.option3 = option3;
}
public int getAnswerNumber() {
return answerNumber;
}
public void setAnswerNumber(int answerNumber) {
this.answerNumber = answerNumber;
}
public long getRowid() {
return rowid;
}
public void setRowid(long rowid) {
this.rowid = rowid;
}
}
QuestionsTable.java :-
public class QuestionsTable {
public static final String TABLE_NAME = "myquestions";
public static final String COLUMN_ID = BaseColumns._ID;
public static final String COLUMN_QUESTION = "question";
public static final String COLUMN_OPTION1 = "option1";
public static final String COLUMN_OPTION2 = "option2";
public static final String COLUMN_OPTION3 = "option3";
public static final String COLUMN_ANSWERNUMBER = "answernumber";
public static final String COLUMN_TYPE = "type";
}
DBHelper.java :-
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "questions.sqlite";
public static final int DBVERSION = 1;
SQLiteDatabase db;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crtsql = "CREATE TABLE IF NOT EXISTS " +
QuestionsTable.TABLE_NAME +
"(" +
QuestionsTable.COLUMN_ID + " INTEGER PRIMARY KEY," +
QuestionsTable.COLUMN_QUESTION + " TEXT NOT NULL," +
QuestionsTable.COLUMN_OPTION1 + " TEXT NOT NULL," +
QuestionsTable.COLUMN_OPTION2 + " TEXT NOT NULL," +
QuestionsTable.COLUMN_OPTION3 + " TEXT NOT NULL," +
QuestionsTable.COLUMN_ANSWERNUMBER + " INTEGER NOT NULL," +
//<<<< NOTE will default to "TEXTENTRY"
QuestionsTable.COLUMN_TYPE + " TEXT NOT NULL DEFAULT '" +
Question.qtype.TEXTENTRY.toString() + "'" +
")";
db.execSQL(crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addQuestion(Question question){
ContentValues cv = new ContentValues();
cv.put(QuestionsTable.COLUMN_QUESTION, question.getQuestion());
cv.put(QuestionsTable.COLUMN_OPTION1, question.getOption1());
cv.put(QuestionsTable.COLUMN_OPTION2, question.getOption2());
cv.put(QuestionsTable.COLUMN_OPTION3, question.getOption3());
cv.put(QuestionsTable.COLUMN_ANSWERNUMBER, question.getAnswerNumber());
cv.put(QuestionsTable.COLUMN_TYPE, String.valueOf(question.getMytype()));
//<<<< alternative cv.put(QuestionsTable.COLUMN_TYPE,question.getMytype().toString());
db.insert(QuestionsTable.TABLE_NAME,null, cv);
}
public Cursor getQuestionsAsCursor() {
return db.query(QuestionsTable.TABLE_NAME,null,null,null,null,null,null);
}
public ArrayList<Question> getQuestionsAsArrayList() {
ArrayList<Question> rv = new ArrayList<>();
Cursor csr = db.query(QuestionsTable.TABLE_NAME,null,null,null,null,null,null);
while (csr.moveToNext()) {
rv.add(new Question(
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_QUESTION)),
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_OPTION1)),
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_OPTION2)),
csr.getString(csr.getColumnIndex(QuestionsTable.COLUMN_OPTION3)),
csr.getInt(csr.getColumnIndex(QuestionsTable.COLUMN_ANSWERNUMBER)),
//<<< get the String and convert to qtype
Question.convertStringToQtype(
csr.getString(
csr.getColumnIndex(QuestionsTable.COLUMN_TYPE)
)
),
csr.getLong(csr.getColumnIndex(QuestionsTable.COLUMN_ID))
));
}
csr.close();
return rv;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:text="Hello World!"/>
<Button
android:id="#+id/prevquestion"
android:layout_width="0dp"
android:layout_weight="4"
android:layout_height="wrap_content"
android:text="PREVIOUS"/>
<Button
android:id="#+id/nextquestion"
android:layout_width="0dp"
android:layout_weight="4"
android:layout_height="wrap_content"
android:text="NEXT"/>
</LinearLayout>
<ListView
android:id="#+id/questionlist_by_cursor"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="41">
</ListView>
<ListView
android:id="#+id/questionlist_by_arraylist"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="41"
android:background="#FFDDDDFF">
</ListView>
<LinearLayout
android:orientation="horizontal"
android:id="#+id/questiondisplay"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="14">
<TextView
android:id="#+id/questiontext"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content" />
<RadioButton
android:id="#+id/answerrb"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:visibility="gone"/>
<CheckBox
android:id="#+id/answercb"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:visibility="gone"/>
<EditText
android:id="#+id/answeret"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:visibility="gone"/>
</LinearLayout>
</LinearLayout>
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mQuestionText;
Button mNext, mPrev;
RadioButton mRadio;
CheckBox mCheckBox;
EditText mTextEntry;
ListView mQuestionListByCursor,mQuestionListByArrayList;
DBHelper mDBHlpr;
Cursor mCsr;
SimpleCursorAdapter mSCA;
ArrayList<Question> mQuestionArrayList;
ArrayAdapter<Question> mArrayAdapter;
int mQuestionPointer = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQuestionListByCursor = (ListView) this.findViewById(R.id.questionlist_by_cursor);
mQuestionListByArrayList = (ListView) this.findViewById(R.id.questionlist_by_arraylist);
mNext = (Button) this.findViewById(R.id.nextquestion);
mPrev = (Button) this.findViewById(R.id.prevquestion);
mRadio = (RadioButton) this.findViewById(R.id.answerrb);
mCheckBox = (CheckBox) this.findViewById(R.id.answercb);
mTextEntry = (EditText) this.findViewById(R.id.answeret);
mQuestionText = (TextView) this.findViewById(R.id.questiontext);
mDBHlpr = new DBHelper(this);
addSomeTestData(); //<<<< Add some test questions
mQuestionArrayList = mDBHlpr.getQuestionsAsArrayList(); //<<<< get the questions
refreshQuestion(); //<<<< Setup current (1st Question)
//Via Cursor
mCsr = mDBHlpr.getQuestionsAsCursor();
mSCA = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
mCsr,
new String[]{QuestionsTable.COLUMN_QUESTION,QuestionsTable.COLUMN_TYPE},new int[]{android.R.id.text1,android.R.id.text2},0);
mQuestionListByCursor.setAdapter(mSCA);
//Via ArrayList
mArrayAdapter = new ArrayAdapter<Question>(
this,
android.R.layout.simple_list_item_1,mQuestionArrayList
);
mQuestionListByArrayList.setAdapter(mArrayAdapter);
mPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mQuestionPointer > 0) {
mQuestionPointer--;
refreshQuestion();
}
}
});
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mQuestionPointer < (mQuestionArrayList.size() -1)) {
mQuestionPointer++;
refreshQuestion();
}
}
});
}
protected void onDestroy() {
super.onDestroy();
if (!mCsr.isClosed()) {
mCsr.close();
}
}
private void addSomeTestData() {
if (DatabaseUtils.queryNumEntries(
mDBHlpr.getWritableDatabase(),
QuestionsTable.TABLE_NAME
) < 1) {
mDBHlpr.addQuestion(new Question(
"What is 1 + 1?",
"0","1","2",
2,
Question.qtype.CHECKBOX //<<<< uses shorter signature
));
mDBHlpr.addQuestion(new Question(
"What is Tom's first name?",
"Fred","Tom","Bert",
1,
Question.qtype.TEXTENTRY //<<<< uses shorter signature
));
mDBHlpr.addQuestion(new Question(
"Where is Timbuktu?",
"Afirca","Russia","Australia",
1,
Question.qtype.RADIO //<<<< uses shorter signature
));
}
}
private void refreshQuestion() {
Question q = mQuestionArrayList.get(mQuestionPointer);
mQuestionText.setText(q.getQuestion());
switch (q.getMytype()) {
case TEXTENTRY:
mTextEntry.setVisibility(View.VISIBLE);
mRadio.setVisibility(View.GONE);
mCheckBox.setVisibility(View.GONE);
break;
case RADIO:
mRadio.setVisibility(View.VISIBLE);
mCheckBox.setVisibility(View.GONE);
mTextEntry.setVisibility(View.GONE);
break;
case CHECKBOX:
mCheckBox.setVisibility(View.VISIBLE);
mRadio.setVisibility(View.GONE);
mTextEntry.setVisibility(View.GONE);
break;
}
}
}
Screen Shots :-
When first started or restart :-
Notes
the List using a Cursor via SimpleCursorAdapter (1)
the List using an ArrayList<Question) (2)
Note the toString method hasn't been overridden hence the default toString method resulting in the funny values displayed.
the current (first) question, which as per the first list can be seen to be a checkbox question (3).
Next Question (question 2) after clicking the Next button :-
EditText i.e. TEXTENTRY question
Next Question (question 3 now)
This worked as well:
In
Question.java
enum QuestionType
{RADIO,CHECKBOX, TEXTENTRY}
public class Question {
...
private QuestionType type;
public Question(String question, String option1, String option2, String option3, int answerNumber,
QuestionType type) {
...
this.type = type;
}
//generate getters and setters using the generate tool in Android Studio
public QuestionType getType() {
return type;
}
public void setType(QuestionType type) {
this.type = type;
}
}
then in
QuizDnHelper.java
#Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
QuestionsTable.TABLE_NAME + " (" +
...
QuestionsTable.COLUMN_TYPE + " TEXT" + //not INTEGER!
")";
...
private void fillQuestionsTable(){
Question q1 = new Question("1 is correct", "a", "b","c",1,
QuestionType.RADIO);
private void addQuestion(Question question){
ContentValues cv = new ContentValues();
...
//set and get enum as string:
cv.put(QuestionsTable.COLUMN_TYPE, String.valueOf(question.getType()));
...
}
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME, null);
if (c.moveToFirst()){
do {
...
//set and get enum as string:
question.setType(QuestionType.valueOf(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_TYPE))));
...
} while (c.moveToNext());
And to call this into MainActivity:
QuestionType.RADIO
....
we use enums as a class.
Related
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:-
I am facing with a problem which happens only when I add new drawable.
I have a parsed xml to Fragment the icon is set like int.
If I add new drawable then it chooses random drawables to show the icons for the parsed xml.
I have an Adapter for the RecyclerListView.
A Pojo class and DB which extends SQLiteOpenHelper.
If I clear the cache and Storage then it back to normal,
or if I delete the new added drawable it returns back to normally.
Can someone help me to know why it is affecting to change the icons.
I have tried to clean project and rebuild the same.
Invalidate cache and restart but still the same.
Below you can find the code and below the code two pictures of the problem.
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM_TYPE_ONE = 0;
private static final int ITEM_TYPE_TWO = 1;
private final Handler handler = new Handler();
private final ArrayList<Bookmark> arrayList;
private final String BASE_URL = "https://besticon-demo.herokuapp.com/icon?url=";
private final Context context;
public MyAdapter(Context context, ArrayList<Bookmark> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = null;
if (viewType == ITEM_TYPE_ONE) {
view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false);
return new ViewHolder(view);
} else if (viewType == ITEM_TYPE_TWO) {
view = LayoutInflater.from(context).inflate(R.layout.add_bookmark, parent, false);
return new ButtonViewHolder(view);
} else {
return null;
}
}
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, final int position) {
final int itemType = getItemViewType(position);
final Bookmark bookmark = this.arrayList.get(position);
if (itemType == ITEM_TYPE_ONE) {
final ViewHolder viewHolder = (ViewHolder) holder;
RequestOptions requestOptions = new RequestOptions();
BookmarkDB bookmarkDB = new BookmarkDB(context);
String imageUrl = BASE_URL + arrayList.get(position).getSearchUrl() + "&size=32";
int resID = context.getResources().getIdentifier(String.valueOf(arrayList.get(position).getIcon()), "drawable", context.getPackageName());
if (resID == 0) {
Glide.with(context)
.load(imageUrl)
.apply(requestOptions
.placeholder(R.drawable.default_favicon)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.fitCenter())
.into(viewHolder.tvIcon);
} else {
viewHolder.tvIcon.setImageResource(resID);
String imageName = context.getResources().getResourceName(resID);
Log.d("getIcons", imageName); // This is the log.
} else if (itemType == ITEM_TYPE_TWO) {
ButtonViewHolder buttonViewHolder = (ButtonViewHolder) holder;
buttonViewHolder.imgButton.setImageResource(arrayList.get(position).getIcon());
}
}
class ViewHolder extends RecyclerView.ViewHolder {
final ImageView tvIcon;
ViewHolder(#NonNull final View itemView) {
super(itemView);
tvIcon = itemView.findViewById(R.id.image_view);
}
}
The Bookmark.db
public class BookmarkDB extends SQLiteOpenHelper {
private static final String DBNAME = "bookmarks.db"; // The name of the database file
private static final int DBVERSION = 1; // The Database version
public static final String TBL_BOOKMARK = "bookmark";
private static final String COL_ID = BaseColumns._ID; // equates to _id
private static final String COl_NAME = "name";
private static final String COl_HIDDEN = "hidden";
private static final String COL_ICON = "icon";
private static final String COL_NATIVEURL = "nativeurl";
private static final String COL_SEARCHURL = "searchurl";
private final SQLiteDatabase mDB;
Context mContext;
public BookmarkDB(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// The SQL to be used to create the table
String crt_bookmark_tbl_sql = "CREATE TABLE IF NOT EXISTS " + TBL_BOOKMARK + "(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COl_NAME + " TEXT, " +
COl_HIDDEN + " INTEGER, " +
COL_ICON + " TEXT, " +
COL_NATIVEURL + " TEXT," +
COL_SEARCHURL + " TEXT" +
")";
db.execSQL(crt_bookmark_tbl_sql); // CREATE THE TABLE
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS " + DBNAME);
onCreate(db);
}
public void updateName(String newName, int id, String oldName) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TBL_BOOKMARK + " SET " + COl_NAME +
" = '" + newName + "' WHERE " + COL_ID + " = '" + id + "'" +
" AND " + COl_NAME + " = '" + oldName + "'";
db.execSQL(query);
}
public void addBookmark(long id, String name, boolean hidden, String icon, String nativeurl, String searchurl) {
ContentValues cv = new ContentValues();
cv.put(COl_HIDDEN, hidden);
cv.put(COl_NAME, name);
cv.put(COL_ICON, icon);
cv.put(COL_NATIVEURL, nativeurl);
cv.put(COL_SEARCHURL, searchurl);
mDB.insert(TBL_BOOKMARK, null, cv);
// uses the convenience insert method that builds the SQL
}
public ArrayList<Bookmark> getAllBookmarks() {
ArrayList<Bookmark> rv = new ArrayList<>();
Cursor csr = mDB.query(TBL_BOOKMARK, null, null, null, null, null, null);
while (csr.moveToNext()) {
Bookmark b = new Bookmark();
b.setId(csr.getString(csr.getColumnIndex(COL_ID)));
int Icon = csr.getInt(csr.getColumnIndex(COL_ICON));
String name = csr.getString(csr.getColumnIndex(COl_NAME));
String searchUrl = csr.getString(csr.getColumnIndex(COL_SEARCHURL));
b.setIcon(Icon);
b.setName(name);
b.setSearchUrl(searchUrl);
b.setViewType(csr.getInt(csr.getColumnIndex(COl_NAME)));
b.setNativeUrl(csr.getString(csr.getColumnIndex(COL_NATIVEURL)));
rv.add(b);
}
return rv;
}
}
This is the .XML file.
<?xml version="1.0" encoding="utf-8"?>
<Bookmarks>
<Bookmark name="Bing"
hidden="true"
icon="bing"
id="0"
nativeUrl=""
searchUrl="https://www.bing.com" />
<Bookmark
name="Google"
hidden="true"
icon="google"
id="1"
nativeUrl=""
searchUrl="https://www.google.com" />
<Bookmark
name="Youtube"
hidden="false"
icon="youtube"
id="2"
nativeUrl="youtube://"
searchUrl="https://m.youtube.com" />
<Bookmark
name="Facebook"
hidden="false"
icon="facebook"
id="3"
nativeUrl="facebook://"
searchUrl="https://m.facebook.com" />
<Bookmark
name="Twitter"
hidden="false"
icon="twitter"
id="4"
nativeUrl=""
searchUrl="https://mobile.twitter.com/" />
</Bookmarks>
Fragment of RecyclerView
public class FragmentBookmark extends Fragment {
private final ArrayList<Bookmark> arrayList = new ArrayList<>();
private MyAdapter myAdapter;
private View paramView;
private RecyclerView myRecyclerView;
private BookmarkDB mDB;
private Context mContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
mDB = new BookmarkDB(mContext);
mDB.getAllBookmarks();
buildBookmarkArrayListfromDB();
loadBookMarksFromXML();
}
#Nullable
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
paramView = inflater.inflate(R.layout.bookmark, container, false);
myRecyclerView = paramView.findViewById(R.id.myRecyclerView);
// myRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
myRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
myRecyclerView.setHasFixedSize(true);
myAdapter = new MyAdapter(mContext, arrayList);
myRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
Bookmark bookmark = new Bookmark();
bookmark.setViewType(1);
bookmark.setIcon(R.drawable.add_new_bookmark_icon);
arrayList.add(bookmark);
((MainActivity) getActivity()).setFragmentBookmarkListener(new MainActivity.FragmentBookmarkListener() {
#Override
public void onRefresh() {
assert getFragmentManager() != null;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(FragmentBookmark.this).attach(FragmentBookmark.this).commit();
}
});
return paramView;
}
private void loadBookMarksFromXML() {
// MAY WISH TO ONLY DO THIS ONCE as bookmarks would be loaded OTHERWISE DELETE LINE BELOW
if (DatabaseUtils.queryNumEntries(mDB.getWritableDatabase(), BookmarkDB.TBL_BOOKMARK) > 0)
return;
try {
XmlResourceParser xpp = getResources().getXml(R.xml.bookmarks);
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("Bookmark")) {
Bookmark bookmark = new Bookmark();
bookmark.setName(xpp.getAttributeValue(null, "name"));
bookmark.setSearchUrl(xpp.getAttributeValue(null, "searchUrl"));
bookmark.setNativeUrl(xpp.getAttributeValue(null, "nativeUrl"));
bookmark.setId(xpp.getAttributeValue(null, "id"));
int drawableResourceId = getResources().getIdentifier(xpp.getAttributeValue(null, "icon"), "drawable", mContext.getPackageName());
bookmark.setIcon(drawableResourceId);
bookmark.setViewType(0);
if (bookmark.getId() == null) {
bookmark.setId("1");
}
mDB.addBookmark(
Long.valueOf(bookmark.getId()),
bookmark.getName(),
bookmark.getViewType() > 0,
String.valueOf(bookmark.getIcon()),
bookmark.getNativeUrl(),
bookmark.getSearchUrl()
);
}
}
xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void buildBookmarkArrayListfromDB() {
arrayList.clear();
arrayList.addAll(mDB.getAllBookmarks());
Bookmark bookmark = new Bookmark();
bookmark.setViewType(1);
bookmark.setIcon(R.drawable.add_new_bookmark_icon);
arrayList.add(bookmark);
}
This is the Pojo.class
public class Bookmark implements Parcelable, Comparable, Comparator<Bookmark> {
public static final Creator<Bookmark> CREATOR = new Creator<Bookmark>() {
#Override
public Bookmark createFromParcel(Parcel in) {
return new Bookmark(in);
}
#Override
public Bookmark[] newArray(int size) {
return new Bookmark[size];
}
};
private String name;
private String id;
private String nativeUrl;
private String searchUrl;
private String hidden;
private long db_id;
private int icon;
private int viewType;
private Bookmark(Parcel in) {
name = in.readString();
id = in.readString();
nativeUrl = in.readString();
searchUrl = in.readString();
db_id = in.readLong();
icon = in.readInt();
viewType = in.readInt();
hidden = in.readString();
}
public Bookmark() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
this.db_id = Integer.parseInt(id);
}
public String getNativeUrl() {
return nativeUrl;
}
public void setNativeUrl(String nativeUrl) {
this.nativeUrl = nativeUrl;
}
public String getSearchUrl() {
return searchUrl;
}
public void setSearchUrl(String searchUrl) {
this.searchUrl = searchUrl;
}
public int getViewType() {
return viewType;
}
public void setViewType(int viewType) {
this.viewType = viewType;
}
public String getHidden() {
return hidden;
}
public void setHidden(String hidden) {
this.hidden = hidden;
}
#Override
public String toString() {
return "Bookmark{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", nativeUrl='" + nativeUrl + '\'' +
", searchUrl='" + searchUrl + '\'' +
", hidden='" + hidden + '\'' +
", db_id=" + db_id +
", icon=" + icon +
", viewType=" + viewType +
'}';
}
#Override
public int compareTo(Object o) {
return 0;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(id);
dest.writeString(nativeUrl);
dest.writeString(searchUrl);
dest.writeLong(db_id);
dest.writeInt(icon);
dest.writeInt(viewType);
dest.writeString(hidden);
}
#Override
public int compare(Bookmark o1, Bookmark o2) {
return 0;
}
}
This is layout of Fragment.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:overScrollMode="never">
<android.support.v7.widget.RecyclerView
android:id="#+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="false"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.NestedScrollView>
I have created a LogCat to show what it takes this is the result.
Right way
drawable/youtube
drawable/facebook
drawable/twitter
After add drawable or vector asset or image
drawable/wiki
drawable/facebook
drawable/trash
You're calling String.valueOf(bookmark.getIcon()) to store the icon in your database. As the icon is an int representing the resource, this stores the resource id as a string. The issue now is that resource ids are not stable and might change any time you create a new APK. Therefore it works while you don't update the app, but starts failing after.
Instead you should store the name of the res and keep these stable. You're already using the name with your XML data, so I'd assume that's your goal anyhow.
mDB.addBookmark(
Long.valueOf(bookmark.getId()),
bookmark.getName(),
bookmark.getViewType() > 0,
iconName(bookmark.getIcon()),
bookmark.getNativeUrl(),
bookmark.getSearchUrl()
);
String Icon = csr.getString(csr.getColumnIndex(COL_ICON));
b.setIcon(iconRes(Icon));
Now you only need to implement the mapping from name to id.
String iconName(int icon) {
return getResources().getResourceEntryName(icon);
}
int iconRes(String icon) {
return getResources().getIdentifier(icon, "drawable", mContext.getPackageName())
}
Also you need to unset mContext on detach or don't store it and use getContext() or requireContext() instead. Of course you'd have to check for null if you use it in some background operation.
#Override
public void onDetach() {
mContext = null;
super.onDetach();
}
Try to do myAdapter.notifyDataSetChanged(); after your arrayList adding work in the FragmentBookmark:
Bookmark bookmark = new Bookmark();
bookmark.setViewType(1);
bookmark.setIcon(R.drawable.add_new_bookmark_icon);
arrayList.add(bookmark);
myAdapter.notifyDataSetChanged();
BTW:The xml parse work and database operations should generally be handled asynchronously.
Updated:Change your the type icon field in Bookmark from int to String,and modify some code in loadBookMarksFromXML,from
int drawableResourceId =
getResources().getIdentifier(
xpp.getAttributeValue(null, "icon"), "drawable",mContext.getPackageName());
bookmark.setIcon(drawableResourceId);
to
bookmark.setIcon(xpp.getAttributeValue(null, "icon"));
change some code in onBindViewHolder in class MyAdapter,from:
int resID = context.getResources().getIdentifier(String.valueOf(arrayList.get(position).getIcon()), "drawable", context.getPackageName());
to
int resID = context.getResources().getIdentifier(arrayList.get(position).getIcon()), "drawable", context.getPackageName());
You can easily fix other errors caused by changing the icon field's type and run again,let me know the result.Thx.
For storing image to sqlite or any other local database you must store name of variable(i do this when use local database maybe there is better way)
So when you want to store drawable
Use this code
bookmark.setIcon("add_new_bookmark_icon");//don't forget to change icon to String in bookmark
Instead of this
bookmark.setIcon(R.drawable.add_new_bookmark_icon);//you use this in onViewCreate and buildBookmarkArrayListfromDB
Now when you want show drawable from database use this code
int resourceId = getResources().getIdentifier("", "drawable", getPackageName());
Drawable yourImage = ContextCompat.getDrawable(this,resourceId);
imageView.setImageDrawable(yourImage);
Note
You must change all place use setIcon or getIcon and all code you use icon as int like in getAllBookmarks -> csr.getInt(csr.getColumnIndex(COL_ICON) and others
I do this several years ago and i don't check it still works. try it and tell me what happens
As the Resource id will be kept on changing at every install or apk generation, it is wise to store the name of the icon resource and fetch it during display time. To do this you can store a string value of the name of the icon(you can also use the same name as of the bookmark, but make sure the drawable of the same name).
Change icon field to String in Database (Bookmark.db) & Pojo.
Remove this line in your Fragment of RecyclerView
int drawableResourceId = getResources().getIdentifier(xpp.getAttributeValue(null, "icon"), "drawable", mContext.getPackageName());
Change next line
bookmark.setIcon(xpp.getAttributeValue(null, "name"));
In onBindViewHolder in MyAdapter class get icon resource using
int iresourceid = getResources().getIdentifier(arrayList.get(position).getIcon(),"drawable",getPackageName());
Maybe you should move icons from res folder to assets, then load it with Glide.
if (getResources().getAssets().list("").contains("icon.png")) {
Glide.with(fragment)
.load(Uri.parse("file:///android_asset/icon.png"))
.into(imageView);
} else {
// load from web
}
I am creating an android app (still the basic structure, without any design) from an Job site through XML feed using REST api.
Till now, I could managed to parse the XML data, displaying the List View with an POP UP menu item on each row. I am passing Data from PostBaseAdapter to MarkAsFav class. Could You please tell me if I am doing right or not? coz, I am getting no any data saved in database
Now, I have a problems:
I have 3 pop up menu item:
1. Set as Favourite
2. Share on Fb
3. email to Your friend
I am working on point number-1.
For now,I would be saving the data in SQLite Database itself. so, I am passing all the data (all the details about the job with all rows) to another activity, more over I am accepting a user given name to save the details through insertDB() in my Database.
But, unfortunately , nothing is getting saved in the database .
Can you tell me, if the data is getting passed or not and if the datas are being saved in database or not?
Please help me out. Please tell me where and how to modify the code?
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
MarkAsFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
Intent extras = getIntent();
if (extras != null) {
int Value = extras.getIntExtra("id",0);
if (Value > 0) {
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.JOBS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText((CharSequence) nam);
header.setFocusable(false);
header.setClickable(false);
}
}
}
public void run(View view) {
Intent extras = getIntent();
if (extras != null) {
int val = extras.getIntExtra("id",0);
String value1 = extras.getStringExtra("title");
String value2= extras.getStringExtra("company");
String value3= extras.getStringExtra("city");
String value4= extras.getStringExtra("state");
String value5= extras.getStringExtra("country");
String value6= extras.getStringExtra("formattedLocation");
String value7= extras.getStringExtra("source");
String value8= extras.getStringExtra("date");
String value9= extras.getStringExtra("snippet");
String value10= extras.getStringExtra("url");
String value11= extras.getStringExtra("onmousedown");
String value12= extras.getStringExtra("lattitude");
String value13= extras.getStringExtra("longitude");
String value14= extras.getStringExtra("jobkey");
String value15= extras.getStringExtra("sponsored");
String value16= extras.getStringExtra("expired");
String value17= extras.getStringExtra("formattedLocationFull");
String value18= extras.getStringExtra("formattedRelativeTime");
String headerValue = header.getText().toString();
Log.e("ERROR", "Inside run and checking Value and val");
if (val > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)) {
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
PostBaseAdapter.java
public class PostBaseAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ArrayList<Result> resultList;
private MainActivity mActivity;
private Context mContext;
String TAG="";
public PostBaseAdapter(Context context, ArrayList<Result> resultList) {
this.layoutInflater = LayoutInflater.from(context);
this.resultList = resultList;
this.mContext= context;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Result getItem(int i) {
return resultList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int j=i;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_post, null);
//viewHolder = new ViewHolder(convertView);
viewHolder= new ViewHolder();
//View overFlow = convertView.findViewById(R.id.id_overflow);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.imageClick= (ImageView) convertView.findViewById(R.id.id_overflow);
convertView.setTag(viewHolder);
//overFlow.setOnClickListener(new OverflowSelectedListener(mContext, mActivity));
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Result result = resultList.get(i);
viewHolder.tvTitle.setText(result.getJobtitle());
final String jobTitle=resultList.get(i).getJobtitle();
final String company= resultList.get(i).getCompany();
final String city= resultList.get(i).getCity();
final String state= resultList.get(i).getState();
final String country= resultList.get(i).getCountry();
final String formattedLocation= resultList.get(i).getFormattedLocation();
final String source=resultList.get(i).getSource();
final String date= resultList.get(i).getDate();
final String snippet= resultList.get(i).getSnippet();
final String url= resultList.get(i).getUrl();
final String onmousedown= resultList.get(i).getOnmousedown();
final String lattitude= resultList.get(i).getLattitude();
final String longitude= resultList.get(i).getLongitude();
final String jobkey= resultList.get(i).getJobkey();
final String sponsored= resultList.get(i).getSponsored();
final String expired= resultList.get(i).getExpired();
final String formattedLocaionfull= resultList.get(i).getFormattedLocation();
final String formattedRelativeTime= resultList.get(i).getFormattedRelativeTime();
try {
viewHolder.imageClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.id_overflow:
final PopupMenu popup = new PopupMenu(mContext, v);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
// Force icons to show
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int id_To_Search = j + 1;
/*Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtras(dataBundle);
mContext.startActivity(intent);*/
switch (item.getItemId()) {
case R.id.email_whatsapp:
doEmailOrWhatsapp(mActivity);
return true;
case R.id.share_on_fb:
shareOnFb(mActivity);
return true;
case R.id.mark_as_fav:
//viewHolder.
//dataBundle.putString("name", result.getJobtitle());
Intent intent = new Intent(mContext,MarkAsFav.class);
intent.putExtra("id",0);
intent.putExtra("title", jobTitle );
intent.putExtra("company",company );
intent.putExtra("city", city);
intent.putExtra("state",state );
intent.putExtra("country",country );
intent.putExtra("formattedLocation",formattedLocation );
intent.putExtra("source",source );
intent.putExtra("date", date);
intent.putExtra("snippet", snippet);
intent.putExtra("url", url);
intent.putExtra("onmousedown",onmousedown );
intent.putExtra("lattitude", lattitude);
intent.putExtra("longitude",longitude );
intent.putExtra("jobkey", jobkey);
intent.putExtra("sponsored",sponsored );
intent.putExtra("expired", expired);
intent.putExtra("formattedLocationFull",formattedLocaionfull );
intent.putExtra("formattedRelativeTime",formattedRelativeTime );
//intent.putExtras(dataBundle);
mContext.startActivity(intent);
return true;
default:
break;
}
return true;
}
});
//popup.show();
break;
default:
break;
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
TextView tvTitle;//, tvPublishDate;
ImageView imageClick;
/* public ViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);*/
// imageClick=(ImageView)item.findViewById(R.id.id_overflow);
// tvPublishDate = (TextView) item.findViewById(R.id.tvPublishDate);
}
}
mark-fav-layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<EditText
android:id="#+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:inputType="text" >
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="#string/save" />
</LinearLayout>
Result.java
public class Result {
public String jobtitle;
public String company;
public String city;
public String state;
public String country;
public String formattedLocation;
public String source;
public String date;
public String snippet;
public String url;
public String onmousedown;
public String lattitude;
public String longitude;
public String jobkey;
public String sponsored;
public String expired;
public String formattedLocationFull;
public String formattedRelativeTime;
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getFormattedLocation() {
return formattedLocation;
}
public void setFormattedLocation(String formattedLocation) {
this.formattedLocation = formattedLocation;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getJobkey() {
return jobkey;
}
public void setJobkey(String jobkey) {
this.jobkey = jobkey;
}
public String getSponsored() {
return sponsored;
}
public void setSponsored(String sponsored) {
this.sponsored = sponsored;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getFormattedLocationFull() {
return formattedLocationFull;
}
public void setFormattedLocationFull(String formattedLocationFull) {
this.formattedLocationFull = formattedLocationFull;
}
public String getFormattedRelativeTime() {
return formattedRelativeTime;
}
public void setFormattedRelativeTime(String formattedRelativeTime) {
this.formattedRelativeTime = formattedRelativeTime;
}
public String getDetails() {
String result = jobtitle + ": " + company + "\n" + city + "-" + state
+ "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
"\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
+jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
return result;
}
}
I have just updated my code and its working fine for me. I am posting it here ,so that anyone can use if needed.
MarkFav.java
public class MarkAsFav extends Activity {
private DBHelper mydb;
TextView header;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mark_fav_layout);
header = (TextView) findViewById(R.id.editTextName);
mydb = new DBHelper(this);
mydb.getWritableDatabase();
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
if (value > 0) {
//means this is the view part not the add contact part.
/* Cursor rs = mydb.getData(value);
id_To_Update = value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
header.setText( nam);
header.setFocusable(false);
header.setClickable(false);*/
}
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("id");
String headerValue = header.getText().toString();
String value1 = extras.getString("title");
String value2 = extras.getString("company");
String value3 = extras.getString("city");
String value4 = extras.getString("state");
String value5 = extras.getString("country");
String value6 = extras.getString("formattedLocation");
String value7 = extras.getString("source");
String value8 = extras.getString("date");
String value9 = extras.getString("snippet");
String value10= extras.getString("url");
String value11= extras.getString("onmousedown");
String value12= extras.getString("lattitude");
String value13= extras.getString("longitude");
String value14= extras.getString("jobkey");
String value15= extras.getString("sponsored");
String value16= extras.getString("expired");
String value17= extras.getString("formattedLocationFull");
String value18= extras.getString("formattedRelativeTime");
Log.e("ERROR", "Inside run and checking Value and val");
if (value > 0) {
/*if (mydb.updateContact(id_To_Update, header.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Log.e("ERROR", "update error");
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else {*/
if (mydb.insertContact(headerValue, value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12,value13,value14,value15,value16,value17,value18)){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
Log.e("ERROR", "insert contact errors");
} else {
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDB.db";
public static final String JOBS_TABLE_NAME = "favourites";
public static final String JOBS_COLUMN_ID = "id";
public static final String JOBS_COLUMN_NAME = "name";
public static final String JOBS_COLUMN_HEADER="header";
public static final String JOBS_COLUMN_COMPANY="company";
public static final String JOBS_COLUMN_CITY="city";
public static final String JOBS_COLUMN_STATE="state";
public static final String JOBS_COLUMN_COUNTRY="country";
public static final String JOBS_COLUMN_FORMATEDLOCATION="formatedLocation";
public static final String JOBS_COLUMN_SOURCE="source";
public static final String JOBS_COLUMN_DATE="date";
public static final String JOBS_COLUMN_SNIPPET="snippet";
public static final String JOBS_COLUMN_URL="url";
public static final String JOBS_COLUMN_ONMOUSEDOWN="onmousedown";
public static final String JOBS_COLUMN_LATTITUDE="lattitude";
public static final String JOBS_COLUMN_LONGITUDE="longitude";
public static final String JOBS_COLUMN_JOBKEY="jobkey";
public static final String JOBS_COLUMN_SPONSORED="sponsored";
public static final String JOBS_COLUMN_EXPIRED="expired";
public static final String JOBS_COLUMN_FORMATTEDLOCATIONFULL="formattedLocationFull";
public static final String JOBS_COLUMN_FORMATTEDRELATIVETIME="formattedRelativeTime";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
/* public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" text, "+JOBS_COLUMN_NAME+" text,"+JOBS_COLUMN_COMPANY+" text, "+JOBS_COLUMN_CITY+" text, "+JOBS_COLUMN_STATE+" text, "+JOBS_COLUMN_COUNTRY+" text,"+JOBS_COLUMN_FORMATEDLOCATION+" text,"+JOBS_COLUMN_SOURCE+" text,"+JOBS_COLUMN_DATE+" text,"+JOBS_COLUMN_SNIPPET+" text,"+JOBS_COLUMN_COMPANY+" text,"+JOBS_COLUMN_URL+"text,"+JOBS_COLUMN_ONMOUSEDOWN+" text,"+JOBS_COLUMN_LATTITUDE+" text,"+JOBS_COLUMN_LONGITUDE+"text,"+JOBS_COLUMN_JOBKEY+" text,"+JOBS_COLUMN_SPONSORED+" text,"+JOBS_COLUMN_EXPIRED+" text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" text)"
);*/
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + JOBS_TABLE_NAME +
"("+JOBS_COLUMN_ID+" integer primary key autoincrement, "+JOBS_COLUMN_HEADER+" Text, "+JOBS_COLUMN_NAME+" Text,"+JOBS_COLUMN_COMPANY+" Text, "+JOBS_COLUMN_CITY+" Text, "+JOBS_COLUMN_STATE+" Text, "+JOBS_COLUMN_COUNTRY+" Text,"+JOBS_COLUMN_FORMATEDLOCATION+" Text,"+JOBS_COLUMN_SOURCE+" Text,"+JOBS_COLUMN_DATE+" Text,"+JOBS_COLUMN_SNIPPET+" Text,"+JOBS_COLUMN_COMPANY+" Text,"+JOBS_COLUMN_URL+"Text,"+JOBS_COLUMN_ONMOUSEDOWN+" Text,"+JOBS_COLUMN_LATTITUDE+" Text,"+JOBS_COLUMN_LONGITUDE+"Text,"+JOBS_COLUMN_JOBKEY+" Text,"+JOBS_COLUMN_SPONSORED+" Text,"+JOBS_COLUMN_EXPIRED+" Text,"+JOBS_COLUMN_FORMATTEDLOCATIONFULL+" Text,"+JOBS_COLUMN_FORMATTEDRELATIVETIME+" Text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS favourites");
onCreate(db);
}
public boolean insertContact(String header, String name,String company,String city,String state,String country,String formattedLocation,String source,String date,String snippet,String url,String onmousedown,String lattitude,String longitude,String jobkey,String sponsored,String expired, String formattedLocationFull,String formattedRelativeTime)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
//contentValues.put("id",id);
contentValues.put(JOBS_COLUMN_HEADER,header);
contentValues.put(JOBS_COLUMN_NAME, name);
contentValues.put(JOBS_COLUMN_COMPANY, company);
contentValues.put(JOBS_COLUMN_CITY, city);
contentValues.put(JOBS_COLUMN_STATE, state);
contentValues.put(JOBS_COLUMN_COUNTRY, country);
contentValues.put(JOBS_COLUMN_FORMATEDLOCATION, formattedLocation);
contentValues.put(JOBS_COLUMN_SOURCE, source);
contentValues.put(JOBS_COLUMN_DATE, date);
contentValues.put(JOBS_COLUMN_SNIPPET, snippet);
contentValues.put(JOBS_COLUMN_URL, url);
contentValues.put(JOBS_COLUMN_ONMOUSEDOWN, onmousedown);
contentValues.put(JOBS_COLUMN_LATTITUDE, lattitude);
contentValues.put(JOBS_COLUMN_LONGITUDE, longitude);
contentValues.put(JOBS_COLUMN_JOBKEY, jobkey);
contentValues.put(JOBS_COLUMN_SPONSORED, sponsored);
contentValues.put(JOBS_COLUMN_EXPIRED, expired);
contentValues.put(JOBS_COLUMN_FORMATTEDLOCATIONFULL, formattedLocationFull);
contentValues.put(JOBS_COLUMN_FORMATTEDRELATIVETIME, formattedRelativeTime);
db.insert("favourites", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites where id="+id+"", null );
return res;
}
/* public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, JOBS_TABLE_NAME);
return numRows;
}*/
public boolean updateContact (Integer id, String name)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
db.update("favourites", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("favourites",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from favourites", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(JOBS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
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 8 years ago.
Improve this question
I am new to SQLite. I have an activity in which I have different fields like Name,Email,Date of Birth etc. When user fill the information and clicks the save button I want it to get saved to the database. But I am stuck in mid way and don't know what to do.How to save the data from Edit Text Views to the database on Save Button click.Please help me.
I am sharing my code.
DataBaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "NewUserDb.db";
private static final String TABLE_INFO = "info";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_GOAL = "userGOAL";
public static final String COLUMN_NAME = "userName";
public static final String COLUMN_EMAIL = "userEmail";
public static final String COLUMN_DOB = "userDOB";
public static final String COLUMN_HEIGHT = "userHeight";
public static final String COLUMN_WEIGHT = "userWeight";
public static final String COLUMN_GENGER = "userGender";;
public static final String COLUMN_ZIP = "userZIP";
private static final String[] COLUMNS = { COLUMN_ID, COLUMN_GOAL,
COLUMN_NAME, COLUMN_EMAIL, COLUMN_DOB, COLUMN_HEIGHT,
COLUMN_WEIGHT, COLUMN_GENGER, COLUMN_ZIP };
// http://www.techotopia.com/index.php/An_Android_SQLite_Database_Tutorial
/*
* public DatabaseHelper(Context context, String name, CursorFactory
* factory, int version) { super(context, name, factory, version); // TODO
* Auto-generated constructor stub
*
* }
*/
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_USER_TABLE = "CREATE TABLE User ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "gaol TEXT, "
+ "name TEXT )";
db.execSQL(CREATE_USER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS users");
// create fresh books table
this.onCreate(db);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void addUser(NewUserDb newuserdb) {
// for logging
// Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(COLUMN_GOAL, newuserdb.getGoal()); // get title
values.put(COLUMN_NAME, newuserdb.getName()); // get author
values.put(COLUMN_EMAIL, newuserdb.getEmail());
values.put(COLUMN_DOB, newuserdb.getDob());
values.put(COLUMN_HEIGHT, newuserdb.getHeight());
values.put(COLUMN_WEIGHT, newuserdb.getWeight());
values.put(COLUMN_GENGER, newuserdb.getGender());
values.put(COLUMN_ZIP, newuserdb.getZip());
// 3. insert
db.insert(TABLE_INFO, // table
null, // nullColumnHack
values); // key/value -> keys = column names/ values = column
// values
// 4. close
db.close();
}
public NewUserDb getNewUserDb(int id) {
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor = db.query(TABLE_INFO, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
NewUserDb newUserdb = new NewUserDb();
newUserdb.setId(Integer.parseInt(cursor.getString(0)));
newUserdb.setGoal(cursor.getString(1));
newUserdb.setName(cursor.getString(2));
newUserdb.setEmail(cursor.getString(3));
newUserdb.setDob(cursor.getString(4));
newUserdb.setHeight(cursor.getString(5));
newUserdb.setWeight(cursor.getString(6));
newUserdb.setGender(cursor.getString(7));
newUserdb.setZip(cursor.getString(8));
// Log.d("getBook("+id+")", book.toString());
// 5. return book
return newUserdb;
}
// Deleting single book
public void deleteUser(NewUserDb newuserDB) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_INFO, COLUMN_ID + " = ?",
new String[] { String.valueOf(newuserDB.getId()) });
// 3. close
db.close();
Log.d("deleteBook", newuserDB.toString());
}
}
NewUserDb.java
public class NewUserDb {
private int id;
private String goal;
private String name;
private String email;
private String dob;
private String height;
private String weight;
private String gender;
private String zip;
public NewUserDb() {
}
public NewUserDb(int id, String goal, String name, String email,
String dob, String height, String weight, String gender, String zip) {
super();
this.id = id;
this.goal = goal;
this.name = name;
this.email = email;
this.dob = dob;
this.height = height;
this.weight = weight;
this.gender = gender;
this.zip = zip;
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGoal() {
return goal;
}
public void setGoal(String goal) {
this.goal = goal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String toString() {
return "User [id=" + id + ", goal=" + goal + ", name=" + name
+ ", email=" + email + ", dob=" + dob + ", height=" + height
+ ", weight=" + weight + ", gender=" + gender + ", zip =" + zip
+ "]";
}
}
AccountActivity.java
public class AccountActivity extends Activity {
private EditText et_weight, et_height, et_email, et_dob, et_name;
private Button btn_uploadPhoto, btn_shootPhoto, btn_del, btn_save;
private Switch genderSwitch;
private DatePickerDialog datePickerDialog;
private String year;
private String month;
private String day;
DatabaseHelper dbh = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accounts);
btn_shootPhoto = (Button) findViewById(R.id.button1);
btn_uploadPhoto = (Button) findViewById(R.id.button2);
btn_del = (Button) findViewById(R.id.btn_del);
btn_save = (Button) findViewById(R.id.btn_save);
et_dob = (EditText) findViewById(R.id.et_dob);
genderSwitch = (Switch) findViewById(R.id.mySwitch);
et_name = (EditText) findViewById(R.id.et_name);
et_email = (EditText) findViewById(R.id.et_email);
et_height = (EditText) findViewById(R.id.et_height);
et_height.setInputType(InputType.TYPE_CLASS_NUMBER);
et_weight = (EditText) findViewById(R.id.et_weight);
et_weight.setInputType(InputType.TYPE_CLASS_NUMBER);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//what to do here ??
}
});
}
try .getText() on your EditText
like yourEditText.getText(); and set it into your NewUserDb and pass the NewUserDb object into addUser method of your DatabaseHelper class
First you declare database create table query string in your DatabaseHelper class like this:
private static final String DATABASE_CREATE_USER = "create table UserInfo("
+ "_id VARCHAR(20)," + "userGOAL VARCHAR(20),"
+ "userName VARCHAR(20)," + "userEmail VARCHAR(20),"
+ "userDOB VARCHAR(20)," + "userHeight VARCHAR(10),"
+ "userWeight VARCHAR(10)," + "userGender VARCHAR(10),"
+ "userZIP VARCHAR(10) "+ ")";
Then write inside onCreate method of DatabaseHelper
db.execSQL(DATABASE_CREATE_USER);
Then declare object of SqliteDatabase and DatabseHelper in your AcountActivity like this:
DatabaseHelper dbHelper;
SQLiteDatabase db;
Afer this write following code inside your button onClick method:
dbHelper= new DatabaseHelper(ActountActivity.this);
db = dbHelper.getWritableDatabase();
ContentValues insertValues = new ContentValues();
insertValues.put("_id", "User_Id");
insertValues.put("userGOAL", "User_Goal");
insertValues.put("userName", "User_Name");
insertValues.put("userEmail", "User_Email");
insertValues.put("userDOB", "User_DOB");
insertValues.put("userHeight", "User_Height");
insertValues.put("userWeight", "User_Weight");
insertValues.put("userGender", "User_Gender");
insertValues.put("userZIP", "User_Zip");
db.insert("UserInfo", null, insertValues);
db.close();
May this help you.
I am learning android development through video tutorials.
using the idea in the tutorial. I have created my own class, the database handler (Dbhandler.java) file and the (kovil.java) file. these files are working perfectly.
i want to catch the all the values from the database and display it in the list view. in my mainactivity.xml
can any one help me to do this. Thank you..
here are my codes..
Dbhandler.java file
package lk.adspace.jaffnadb;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Dbhandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "jaffnatempletest";
// Temple table name
private static final String TABLE_TEMPLE = "templ";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TMPNAME = "temple_name";
private static final String KEY_TMPTYPE = "temple_type";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String KEY_IMGNAME = "image_name";
private static final String KEY_YEARBUILD = "year_build";
private static final String KEY_ADDRESS = "address";
private static final String KEY_CITY = "city";
private static final String KEY_EMAIL = "email";
private static final String KEY_WEB = "website";
private static final String KEY_TEL1 = "telephone1";
private static final String KEY_TEL2 = "telephone2";
private static final String KEY_DESCRI = "Description";
private final ArrayList<kovil> temple_list = new ArrayList<kovil>();
public Dbhandler (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TEMPLE_TABLE = "CREATE TABLE " + TABLE_TEMPLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + KEY_TMPNAME + " TEXT," + KEY_TMPTYPE + " TEXT," + KEY_LATITUDE + " TEXT," + KEY_LONGITUDE + " TEXT," + KEY_IMGNAME + " TEXT,"
+ KEY_YEARBUILD + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_CITY + " TEXT," + KEY_EMAIL + " TEXT," + KEY_WEB + " TEXT," + KEY_TEL1 + " TEXT," + KEY_TEL2 + " TEXT,"
+ KEY_DESCRI + " TEXT" + ")";
db.execSQL(CREATE_TEMPLE_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEMPLE);
// Create tables again
onCreate(db);
}
// Adding new temple
public void Add_Temple(kovil Kovil) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TMPNAME, Kovil.gettemplename());
values.put(KEY_TMPTYPE, Kovil.gettempletype());
values.put(KEY_LATITUDE, Kovil.getlatitude());
values.put(KEY_LONGITUDE, Kovil.getlongitude());
values.put(KEY_IMGNAME, Kovil.getimage_name());
values.put(KEY_YEARBUILD, Kovil.getyear_build());
values.put(KEY_ADDRESS, Kovil.getaddress());
values.put(KEY_CITY, Kovil.getcity());
values.put(KEY_EMAIL, Kovil.getemail());
values.put(KEY_WEB, Kovil.getwebsite());
values.put(KEY_TEL1, Kovil.gettelephone1());
values.put(KEY_TEL2, Kovil.gettelephone2());
values.put(KEY_DESCRI, Kovil.getDescription());
// Inserting Row
db.insert(TABLE_TEMPLE, null, values);
db.close(); // Closing database connection
}
// Getting single contact
kovil Get_Temple(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_TEMPLE, new String[] { KEY_ID,
KEY_TMPNAME, KEY_TMPTYPE, KEY_LATITUDE, KEY_LONGITUDE, KEY_IMGNAME, KEY_YEARBUILD, KEY_ADDRESS, KEY_CITY, KEY_EMAIL, KEY_EMAIL, KEY_WEB, KEY_TEL1, KEY_TEL2, KEY_DESCRI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
kovil Kovil = new kovil(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13));
// return contact
cursor.close();
db.close();
return Kovil;
}
// Getting All Contacts
public ArrayList<kovil> Get_Temple() {
try {
temple_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TEMPLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
kovil Kovil = new kovil();
Kovil.setID(Integer.parseInt(cursor.getString(0)));
Kovil.settemplename(cursor.getString(1));
Kovil.settempletype(cursor.getString(2));
Kovil.setlatitude(cursor.getString(3));
Kovil.setlongitude(cursor.getString(4));
Kovil.setimage_name(cursor.getString(5));
Kovil.setyear_build(cursor.getString(6));
Kovil.setaddress(cursor.getString(7));
Kovil.setcity(cursor.getString(8));
Kovil.setemail(cursor.getString(9));
Kovil.setwebsite(cursor.getString(10));
Kovil.settelephone1(cursor.getString(11));
Kovil.settelephone2(cursor.getString(12));
Kovil.setDescription(cursor.getString(13));
// Adding contact to list
temple_list.add(Kovil);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return temple_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_temples", "" + e);
}
return temple_list;
}
}
Kovil.java File
package lk.adspace.jaffnadb;
public class kovil {
//public variables
public int _id;
public String _temple_name;
public String _temple_type;
public String _latitude;
public String _longitude;
public String _image_name;
public String _year_build;
public String _address;
public String _city;
public String _email;
public String _website;
public String _telephone1;
public String _telephone2;
public String _Description;
//empty constructor
public kovil (){
}
// int id, String temple_name, String temple_type, String latitude, String longitude, String image_name, String year_build, String address, String city, String email, String website, String telephone1, String telephone2, String Description
public kovil(int id, String temple_name, String temple_type, String latitude, String longitude, String image_name, String year_build, String address,
String city, String email, String website, String telephone1, String telephone2, String Description) {
// TODO Auto-generated constructor stub
this._id= id;
this._temple_name=temple_name;
this._temple_type=temple_type;
this._latitude=latitude;
this._longitude=longitude;
this._image_name=image_name;
this._year_build=year_build;
this._address=address;
this._city=city;
this._email=email;
this._website=website;
this._telephone1=telephone1;
this._telephone2=telephone2;
this._Description=Description;
}
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String gettemplename() {
return this._temple_name;
}
public void settemplename(String temple_name) {
this._temple_name=temple_name;
}
public String gettempletype() {
return this._temple_type;
}
public void settempletype(String temple_type) {
this._temple_type=temple_type;
}
public String getlatitude() {
return this._latitude;
}
public void setlatitude(String latitude) {
this._latitude=latitude;
}
public String getlongitude() {
return this._longitude;
}
public void setlongitude(String longitude) {
this._longitude=longitude;
}
public String getimage_name() {
return this._image_name;
}
public void setimage_name(String image_name) {
this._image_name=image_name;
}
public String getyear_build() {
return this._year_build;
}
public void setyear_build(String year_build) {
this._year_build=year_build;
}
public String getaddress() {
return this._address;
}
public void setaddress(String address) {
this._address=address;
}
public String getcity() {
return this._city;
}
public void setcity(String city) {
this._city=city;
}
public String getemail() {
return this._email;
}
public void setemail(String email) {
this._email=email;
}
public String getwebsite() {
return this._website;
}
public void setwebsite(String website) {
this._website=website;
}
public String gettelephone1() {
return this._telephone1;
}
public void settelephone1(String telephone1) {
this._telephone1=telephone1;
}
public String gettelephone2() {
return this._telephone2;
}
public void settelephone2(String telephone2) {
this._telephone2=telephone2;
}
public String getDescription() {
return this._Description;
}
public void setDescription(String Description) {
this._Description=Description;
}
}
MainActivity.java file
package lk.adspace.jaffnadb;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ArrayList<kovil> temple_data = new ArrayList<kovil>();
ListView temple_listview;
Dbhandler dbhand = new Dbhandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kovil insertData = new kovil("temple_name", "temple_type", "latitude", "longitude", "image_name", "year_build", "address",
"city", "email", "website", "telephone1", "telephone2", "Description");
Dbhandler dbhand = new Dbhandler(this);
dbhand .Add_Temple(insertData );
kovil insertData2 = new kovil("temple_name", "temple_type", "latitude", "longitude", "image_name", "year_build", "address",
"city", "email", "website", "telephone1", "telephone2", "Description");
dbhand .Add_Temple(insertData2 );
int count =dbhand .Get_Total_Temple();
TextView textView = (TextView) findViewById(R.id.count);
textView.setText(Integer.toString(count));
// i want to display all the values in a list over here.
}
#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;
}
}
Main Activity .xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="50dp" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/count"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/count" >
</ListView>
</RelativeLayout>
First you'll need to create a layout file that will represent how you want to display each list item.
Then you'll need to extend the BaseAdapter class so that you can decide how you want to display each Kovil class.
Once that is constructed, you can call setAdapter on your ListView.
refer these links, it might be useful to you,
1) http://www.edumobile.org/android/android-programming-tutorials/learn-how-to-create-listview-from-sqlite-database-in-android-development/
2) http://androidtuts4u.blogspot.in/2013/02/android-list-view-using-custom-adapter.html