I am currently working on an application for my company.
The App is working with a sqlite Database, stored on the external Storage.
Now I want to Display all Table Names of the Database in a ListView
The Part where I get the Table Names looks like this:
public ArrayList < String[] > getDBTables() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table'", null);
ArrayList < String[] > result = new ArrayList < String[] > ();
int i = 0;
result.add(c.getColumnNames());
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
String[] temp = new String[c.getColumnCount()];
for (i = 0; i < temp.length; i++) {
temp[i] = c.getString(i);
System.out.println("TABLE - " + temp[i]);
}
result.add(temp);
}
return result;
}
And it is working just fine.
But now I have to display it in a ListView and there the problems began.
I tried it like that:
dbTablesView = (ListView) findViewById(R.id.listView);
ArrayList<String[]> tables;
tables=datasource.getDBTables();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tables );
dbTablesView.setAdapter(arrayAdapter);
But it tells me, that I cant use java.util.ArrayList to create the Adapter.
I would really appreciate your help.
Related
i am building an quiz app i want to retrieve 10 questions randomly from 100 question in database.
here is the code from where i am retrieving question from database
QuizDbHelper dbHelper = new QuizDbHelper(this);
questionList = dbHelper.getQuestions(difficulty);
questionCountTotal = questionList.size();
Collections.shuffle(questionList);
QuizDbHelper class getQuestions method:
public ArrayList<Question> getQuestions(String difficulty) {
ArrayList<Question> questionList = new ArrayList<>();
db = getReadableDatabase();
String[] selectionArgs=new String[]{difficulty};
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME+ " WHERE " +QuestionsTable.COLUMN_DIFFICULTY+"= ?", selectionArgs);
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.setOption4(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION4)));
question.setAnswerNr(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER_NR)));
question.setDifficulty(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_DIFFICULTY)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();
return questionList;
}
when i run this all the 100 questions are appering
anyone to fix it better..
First Retrieve all questions from database in Arraylist of Question
then shuffle your arraylist.
Collections.shuffle(questionList);
and sublist to 10 like
questionList.subList(0,10)
you can change your function as
public ArrayList<Question> getQuestions(String difficulty,int size,boolean random) {
ArrayList<Question> questionList = new ArrayList<>();
db = getReadableDatabase();
String[] selectionArgs=new String[]{difficulty};
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME+ " WHERE " +QuestionsTable.COLUMN_DIFFICULTY+"= ?", selectionArgs);
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.setOption4(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION4)));
question.setAnswerNr(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER_NR)));
question.setDifficulty(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_DIFFICULTY)));
questionList.add(question);
} while (c.moveToNext());
}
c.close();
if(random)
Collections.shuffle(questionList);
if(size > 0 && size < questionList.size()){
Collection<Question> collection = questionList.subList(0, size)
ArrayList<Question> subList = new ArrayList<>();
subList.addAll(collection);
return subList;
}
return questionList;
}
I'm searching to get a little useful option to my app, the basics are simple, I have a list of questions (in listView) when we click in the question, we have another activity with details of questions and the answer that is setting ( true or false), if the answer is right, I want to color the question in the listview in green, red if false:
My code to generate questions:
public void showQuest(View view){
ModelHelper md = new ModelHelper(this);
db = openHelper.getWritableDatabase();
Spinner s = (Spinner) findViewById(R.id.spn_ques);
Integer para = 2;
para = Integer.parseInt( s.getSelectedItem().toString()) ;
ArrayList<String> lstQ = md.getOnlyQuestions(para);
ArrayAdapter lstad = new ArrayAdapter(this, android.R.layout.simple_list_item_1,lstQ);
lst.setAdapter(lstad);
The listView OnclickListener:
String quest = (String) parent.getAdapter().getItem(i);
int pos = lst.getCheckedItemPosition();
Intent inte = new Intent(view.getContext(),Reponse.class);
cursor = db.rawQuery("SELECT * FROM "+ ModelHelper.TABLE_QUESTION + " WHERE " + ModelHelper.KEY_QUESTION + " = ? ",new String[] {quest});
if (cursor != null)
if (cursor.getCount() > 0) {
cursor.moveToFirst();
final Intent intent = getIntent();
String matr= intent.getStringExtra("id");
String repA = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_WAITEDANSWER));
String cible = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFILE));
String plan = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PLAN));
int ID = cursor.getInt(cursor.getColumnIndex(ModelHelper.KEY_ID_QUESTION));
inte.putExtra("Question", quest);
inte.putExtra("answ", repA);
inte.putExtra("ID", ID);
inte.putExtra("pos", pos);
inte.putExtra("position", i);
inte.putExtra("matr", matr);
Toast.makeText(new.this, "" + ID, Toast.LENGTH_SHORT).show();
startActivity(inte);
}
}
});
The answer is selected in another activity, in the first one I have only the questions' list.
Thanks.
When you are rendering the item in the listview set the background color based on the logic you described.
Hi I have this code which retrieves data from the SQLite local database I have created.
the code below is a public cursor which retrieves all the data i require from the database
public Cursor RetriveAdvertData (DatabasOpperations DBOpp, String Username, String AdvertType){
SQLiteDatabase SQDB = DBOpp.getReadableDatabase();
String[] Coloumns = {TableData.TableInfo.USERNAME, TableData.TableInfo.ADVERT_NAME, TableData.TableInfo.ADVERT_EMAIL, TableData.TableInfo.ADVERT_ADDRESS, TableData.TableInfo.ADVERT_NUMBER, TableData.TableInfo.ADVERT_TYPE};
String Where = TableData.TableInfo.USERNAME + " LIKE ? AND " + TableData.TableInfo.ADVERT_TYPE + " LIKE ?";
String Argument[] = {Username, AdvertType};
Cursor Cur = SQDB.query(TableData.TableInfo.TABLE_NAME2, Coloumns, Where, Argument, null, null, null);
return Cur;
}
I then call that Cursor in another java page
Context Contx = this;
public DatabasOpperations DB = new DatabasOpperations(Contx);
public Cursor Cur;
Cur = DB.RetriveAdvertData(DB, DBUsername, "Restaurant");
String AdName = "";
String AdEmail = "";
String AdAddress = "";
String AdNumber = "";
String AdType = "";
if (Cur.moveToFirst()){
do {
AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));
final String[] Adverts = new String[]{
AdName, AdEmail, AdAddress, AdNumber, AdType
};
ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Adverts);
LV1.setAdapter(setListAdapter);
}while (Cur.moveToNext());
}
Cur.close();
the code does display only one row from the database, how do i amend the code to display all the rows in the database?
Try to put the setAdapter out of the while loop:
List<String[]> arr = new ArrayList<>();
if (Cur.moveToFirst()) {
do {
AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));
final String[] Adverts = new String[]{
AdName, AdEmail, AdAddress, AdNumber, AdType
};
arr.add(Adverts)
} while (Cur.moveToNext());
}
Cur.close();
ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arr);
LV1.setAdapter(setListAdapter);
I'm having one problem in show my ListView correctly
If I declare
String[] cod = {"cod1","cod2", "cod3"};
String[] desc = {"desc1","desc2", "desc3"};
String[] preco = {"1.00","2.00", "3.00"};
My adapter is:
lista = (ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
It works perfectly!
But if I get the data from a database, the ListView shows only one row.
results = DbHelper.getItemsDao().queryRaw(sqlGetItems);
/*GET ALL RESULTS FROM DATABASE*/
List<String[]> array = results.getResults();
int count = array.size();
String[] cod = null, desc = null, preco = new String[count];
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]};
}
lista = (ListView) findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
Try this solution:
for(int i = 0; i < count; i++) {
String[] res = array.get(i);
cod.add(res[0]) ;
desc.add(res[1]);
preco.add(res[3]);
}
Look at the code carefully:
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod = new String[]{res[0]} ;
desc = new String[]{res[1]};
preco = new String[]{res[3]} ;
}
lista=(ListView)findViewById(R.id.list);
lista.setAdapter(new dataListAdapter(cod, desc, preco));
Here, the varables cod, desc and preco are created every time in the loop. So they are the last one at the end.
You can try like as follows:
String[] cod = new String[count];
String[] desc = new String[count];
String[] preco = new String[count];
for(int i = 0; i<count; i++){
String[] res = array.get(i);
cod[i] = res[0] ;
desc[i] = res[1];
preco[i] = res[3] ;
}
Is it possible to transfer values from SimpleAdapter to array[]. I am getting values in SimpleAdapter from ArrayList<HashMap<String, String>> and want to pass these values from SimpleAdapter to array[].
static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter = new SimpleAdapter(this, contactList,R.layout.list_item,new String[] {android_H_NAME}, new int[] {R.id.name});
String[] hospFields = //want to get values here from adapter
Modify and use this:
ArrayList<String> listItems = new ArrayList<String>();
for (int i = 0; i < result.length(); i++) {
try {
listItems
.add(result.getJSONObject(i)
.getString(BsharpConstant.NAME_CONSTANT)
.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Inside oncreate method:
ListView list = (ListView) findViewById(R.id.idOfUrView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
ActivityName.this,
android.R.layout.simple_list_item_1, listItems);
list.setAdapter(adapter);
list.setOnItemClickListener(this);//if u need this until not required
Use this want to stores the value in item click:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String clickedItemName = (String) listOfProductsCategory
.getItemAtPosition(position);
int clickedItemId = (int) listOfProductsCategory
.getItemIdAtPosition(position);
// implement your login to store the value
//by using for loop listItems[i] ,i++
Toast.makeText(this.getActivity(),
"Custom text : " + clickedItemName,
Toast.LENGTH_SHORT).show();
//call your method if u want
}
There is no possibility to access the data directly, but you can use (in general):
Object[] o = new Object[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
o[i] = adapter.getItem(i);
}
to create a copy of your Adapter data. If you want just to extract specific values use:
String[] hospFields = new String[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, String> rowData = adapter.getItem(i); //gets HashMap of a specific row
String name = rowData.get("name"); //gets the field name of that row
hospFields[i] = name; // copies field into your array
}