How to get List View? - java

How to get List View android studio.this is my code
public class StockSearchActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabase;
DbHelper dbHelper;
Cursor cursor;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stock_search);
listView = findViewById(R.id.display_listview);
dbHelper = new DbHelper(this);
Cursor result = dbHelper.getAllData();
final ArrayList<String> theList = new ArrayList<>();
//get the data to the list view
if(result.getCount() == 0 ){
Toast.makeText(StockSearchActivity.this,"Databse is empty",Toast.LENGTH_LONG).show();
}else{
while (result.moveToNext()){
theList.add(result.getString(0));
theList.add(result.getString(1));
theList.add(result.getString(2));
theList.add(result.getString(3));
theList.add(result.getString(4));
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_expandable_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
}
following code is my activity code for list view.is this correct.code is not working
//getAllData
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + tbName ,null);
return result;
}
Above code has been implemented in the database class.

Set your Adapter outside while loop
//get the data to the list view
if(result.getCount() == 0 ){
Toast.makeText(StockSearchActivity.this,"Databse is empty",Toast.LENGTH_LONG).show();
}else{
while (result.moveToNext()){
theList.add(result.getString(0));
theList.add(result.getString(1));
theList.add(result.getString(2));
theList.add(result.getString(3));
theList.add(result.getString(4));
}
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_expandable_list_item_1,theList);
listView.setAdapter(listAdapter);
}

Your problem is in the below line
SQLiteDatabase db = this.getWritableDatabase();
When you are trying to fetch data from database, it should be opened in readable mode like below.
SQLiteDatabase db = this.getReadableDatabase();

Related

How to read data from SQLiteOpenHelper to textview?

I want to set Textview from SQL database, but the app crashes when I launch this activity. Where is the problem?
DatabaseHelper.java
Cursor readAllData(){
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
if(db != null){
cursor = db.rawQuery(query, null);
}
return cursor;
}
MainActivity.java
myDB = new DatabaseHelper(MainActivity2.this);
Cursor cursor = myDB.readAllData();
btn.setText(cursor.getString(5));
You should provide the stacktrace to better understand the crash. However, you probably get the crash because you're querying your database from the UI thread, when you should query it in a separate and secure one.
Here's an example, using the code that you provided:
public class YourActivity extends AppCompactActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
Button btn = (Button) findViewById(R.id.yourButtonId);
new Thread(() -> {
SQLiteDatabase myDB = new DatabaseHelper(YourActivity.this);
Cursor cursor = myDB.readAllData();
String textToShow = cursor.getString(5);
//Now that you've done all the work needed, you can go to the UiThread
runOnUiThread(() -> {
btn.setText(textToShow);
}
}
}

Android cannot resolve constructor ArrayAdapter

I am aware that this question has been asked multiple times before but none of the solutions have worked for me. This is my code:
public class reminderDAO extends dbManager{
public reminderDAO(Context context) {
super(context);
}
// Adding new reminder
public void addReminder(Reminder reminder) {
//dbm.gettingWritable(values);
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(getKEY_DATE(), reminder.getReminderDate());
values.put(getKEY_TITLE(), reminder.getReminderTitle());
values.put(getKEY_DESC(), reminder.getReminderDescription());
values.put(getKEY_TIME(), reminder.getReminderTime());
// Inserting Row
db.insert(getDATABASE_TABLE(), null, values);
db.close(); // Closing database connection
}
public List<Reminder> getAllReminders(ListView lv) {
ArrayList<Reminder> reminderList = new ArrayList<Reminder>();
// Select All Query
String selectQuery = "SELECT * FROM " + getDATABASE_TABLE();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
MainActivity ma = new MainActivity();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Reminder r = new Reminder();
r.setReminderDate(cursor.getString(0));
r.setReminderTitle(cursor.getString(1));
r.setReminderDescription(cursor.getString(2));
r.setReminderTime(cursor.getString(3));
// Adding reminder to list
reminderList.add(r);
} while (cursor.moveToNext());
}
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this,
android.R.layout.simple_list_item_1,
reminderList );
lv.setAdapter(arrayAdapter);
// return reminder list
return reminderList;
}
}
I've got a feeling it is to do with 'this' inside the arrayAdapter. I have tried getActivity(), this.getActivity(), reminderDAO.this.getActivity(), MainActivity.this and reminderDAO.this.
Anyone have a solution?
Create a Context variable in your class. and assign it from the constructor parameter.
private Context context;
public reminderDAO(Context context) {
this.context = context;
super(context);
}
Then use this variable to pass to the ArrayAdapter
ArrayAdapter<Reminder> arrayAdapter = new ArrayAdapter<Reminder>(
this.context,
android.R.layout.simple_list_item_1,
reminderList );

Adding SQLite database value to ListView

I want to add SQLite database value to ListView if record exists, but I'm only getting text from EditText.
Here's what I'm doing
Code from databaseHelper Class
public String ifExistIn(String stationName) {
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
try {
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null));
return stationName;
}
}
Code from activity class
public View.OnClickListener searchStation = new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
String searchString= searchText.getText().toString();
dbHelper.ifExistIn(searchString);
list.add(searchString);
arrayAdapter= new ArrayAdapter<String>(SearchAndReview.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
};
Probably a few mistakes here but from what I can see you can try this:
public String ifExistIn(String stationName) {
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null);
c.moveToFirst();
return c.getString(c.getColumnIndex("stationName"));
}
You have to get the result of the Cursor and interpret it then return it AS String stationName.
And this:
public View.OnClickListener searchStation = new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
String searchString= searchText.getText().toString();
String usethis = dbHelper.ifExistIn(searchString);
list.add(usethis);
arrayAdapter= new ArrayAdapter<String>(SearchAndReview.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
};
You're getting searchString and putting it into your list and not doing anything with the result of your query. You need to assign the result of your query somewhere then use it. Or actually just directly use it in the insert like:
list.add(dbHelper.ifExistsIn(searchString);
Change your method like this:
public String ifExistIn(String stationName){
String query = "SELECT stationName FROM review WHERE stationId='" + stationName + "' LIMIT 1";
try{
SQLiteDatabase database = getReadableDatabase();
Cursor c = database.rawQuery(query, null))
return c.getString(c.getColumnIndex("columnName"));
}
}
You need to extract data from cursor object. Now you are returning a same value which you are passing.

Android app terminates when calling data to a ListView

I'm trying to call data to a Listview, but app terminates.
in the databasehelper.java i have this function:
public List<Presentation> getAllPresentations() {
List<Presentation> presentations = new ArrayList<Presentation>();
String selectQuery = "SELECT * FROM " + TABLE_PRESENTATION;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Presentation p = new Presentation();
p.setId(c.getInt((c.getColumnIndex(KEY_ID))));
p.setTitle(c.getString(c.getColumnIndex(KEY_TITLE)));
p.setDescription(c.getString(c.getColumnIndex(KEY_DESCRIPTION)));
p.setPatient_name(c.getString(c.getColumnIndex(KEY_PATIENT_NAME)));
presentations.add(p);
} while (c.moveToNext());
}
return presentations;
}
in the xml file (view_presentation) i have a ListView with the id list
in the view_presentations.java i have this code:
public class view_presentations extends Activity
{
// Database Helper
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_presentation);
if (db.getPresentationsCount() != 0)
{
List<Presentation> list = db.getAllPresentations();
ListView l = (ListView)findViewById(R.id.list);
l.setAdapter(new ArrayAdapter<Presentation>(this, R.layout.view_presentation, list));
}
}
}
in this point should display the list with all presentations, but the app terminates. Any help?

Display data from SQLite database into ListView in Android

Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.
Here's my code getClientNames in DatabaseHelper class:
public Cursor getSitesByClientname(String id) {
String[] args={id};
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
String results = "";
/*int count = myCursor.getCount();
String[] results = new String[count + 1];
int i = 0;*/
if (myCursor != null) {
if(myCursor.getCount() > 0)
{
for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
{
results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename"));
}
}
}
return results;
}
One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.
Here's the ClientSites class where I want to display the data:
public class ClientSites extends Activity {
//public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
private Cursor ourCursor = null;
private Adapter adapter=null;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
//dbHelper.createDatabase();
dbHelper.openDataBase();
ourCursor = dbHelper.getSitesByClientname(uID);
Log.e("ALERT", uID.toString());
startManagingCursor(ourCursor);
Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
{
Intent i=new Intent(ClientSites.this, InspectionPoints.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class Adapter extends CursorAdapter {
#SuppressWarnings("deprecation")
Adapter(Cursor c) {
super(ClientSites.this, c);
}
//#Override
public void bindView(View row, Context ctxt,
Cursor c) {
Holder holder=(Holder)row.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Holder holder=new Holder(row);
row.setTag(holder);
return(row);
}
}
static class Holder {
private TextView name=null;
Holder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, DBUserAdapter r) {
name.setText(r.getName(c));
}
}
}
Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
dbHelper.openDataBase();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//ourCursor = dbHelper.getSitesByClientname(uID);
//Log.e("ALERT", uID.toString());
//startManagingCursor(ourCursor);
//Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!!
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
I Created a Listview from a database. Here is the code I used for my app
Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.
public List<Category> getAllCategorys() {
ArrayList<Category> categoryList = new ArrayList<Category>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
try{
if (cursor.moveToFirst()) {
do {
Category category = new Category();
category.setID(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
// Adding category to list
categoryList.add(category);
} while (cursor.moveToNext());
}
}finally{
cursor.close();
}
db.close();
// return category list
return categoryList;
Here is how I fill the ListView by calling the database.
int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();
category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{
category_data[i] = cn.getCategory(); // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);
EDIT: Here is something that should work for you
public List<String> getSitesByClientname(String id) {
String[] args={id};
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
try{
if (myCursor.moveToFirst()){
do{
result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
}while(myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
return result;
}
Use it like this
List<String> sites_data = dbHelper.getSitesByClientname(uID);
result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{
result_data[i] = s; // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);
If you want to return the Cursor from dbHelper you can do something like this...
public Cursor getSitesByClientname(String id) {
String[] args={id};
return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}
I'd also take some time to read the listview tutorial

Categories

Resources