How to read data from SQLiteOpenHelper to textview? - java

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);
}
}
}

Related

How to get List View?

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();

Returning all rows of a column from my content provider

I'm trying to access a Content Provider I already made (which I made by very closely following a tutorial, I've tested it with the code the tutorial walked me through and it works fine) and read the email addresses that I've added into a SQLite database. In the database is the ID, a COLUMN_NAME, and a COLUMN_EMAIL. I want to get all the rows for the email column and have that be an ArrayList of strings that's returned into this activity.
So far my best guess is that somewhere somehow I'll query the database using the query method from the content provider, return the cursor to the activity, and then collect all the Strings from the rows and either manage to send a query with a projection for just that column or filter out all the #lorem.com's or second index of the cursor or some kind of post data retrieval filter.
Basically I'm just pretty stuck.
Okay so here's my code:
public class EmailScheduler extends AppCompatActivity implements LoaderManager
.LoaderCallbacks<Cursor> {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_scheduler);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView emailText = (TextView) findViewById(R.id.emailText);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor cursor = getContacts();
Log.i("TAG", cursor.getColumnName(2));
emailText.append(cursor.toString());
}
});
}
private static final int CONTACT_LOADER = 0;
public Uri contactUri;
ArrayList<String> addresses = new ArrayList<>();
Cursor cursor;
private Cursor getContacts() {
// Run query
Uri uri = Contact.CONTENT_URI;
String[] projection = new String[] { Contact._ID,
Contact.COLUMN_NAME };
String selection = Contact.COLUMN_EMAIL + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = Contact.COLUMN_NAME
+ " COLLATE LOCALIZED ASC";
return getContentResolver().query(uri, projection, selection, selectionArgs,
sortOrder);
}
// called by LoaderManager to create a Loader
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader;
switch (id) {
case CONTACT_LOADER:
cursorLoader = new CursorLoader(this,
contactUri, // Uri of contact to display
null, // null projection returns all columns
null, // null selection returns all rows
null, // no selection arguments
null); // sort order
break;
default:
cursorLoader = null;
break;
}
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.i("TAG", "got to the beginning of onloadfinish " + data);
if (data != null && data.moveToFirst()) {
int nameIndex = data.getColumnIndex(Contact.COLUMN_NAME);
int emailIndex = data.getColumnIndex(Contact.COLUMN_EMAIL);
String address = data.getString(emailIndex);
Log.i("TAG", address);
while (data.getString(emailIndex) != null){
addresses.add(cursor.getString(cursor.getColumnIndex(
Contact.COLUMN_EMAIL)));
Log.i("TAG", addresses.toString());}
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) { }
}
In the onCreate method it returns this data when I run it: android.content.ContentResolver$CursorWrapperInner#60c9bd2
How do I get the information I need from that? Everything I try turns into a dead end.
private void getContacts() {
List<String> addresses = new ArrayList<String>();
// Run query
Uri uri = Contact.CONTENT_URI;
String[] projection = new String[] { Contact.COLUMN_EMAIL };
String selection = null;
String[] selectionArgs = null;
String sortOrder = Contact.COLUMN_EMAIL
+ " COLLATE LOCALIZED ASC";
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs,
sortOrder);
TextView emailText = (TextView) findViewById(R.id.emailText);
if (cursor != null) {
cursor.moveToFirst();
String category;
for (int i = 0; i < cursor.getCount(); i++){
category = cursor.getString(cursor
.getColumnIndexOrThrow(Contact.COLUMN_EMAIL));
addresses.add(category);
cursor.moveToNext();
}
// always close the cursor
cursor.close();
}
}

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?

Android: How to display string on textview from console

I'm trying to display string on the textview. I'm succesfully able to print it on the console from database, but I'm not able to figure out how to print all the strings on different different textviews. Here is my code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText search;
Button insert;
TextView txt1, txt2, txt3, txt4, txt5;
DatabaseHandler db;
List<History> history;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
search = (EditText) findViewById(R.id.search_word);
insert = (Button) findViewById(R.id.insert);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
txt3 = (TextView) findViewById(R.id.txt3);
txt4 = (TextView) findViewById(R.id.txt4);
txt5 = (TextView) findViewById(R.id.txt5);
insert.setOnClickListener(this);
history = db.getAllHistory();
}
public void onClick(View v) {
db.addHistory(new History(search.getText().toString(), null));
Toast.makeText(getApplicationContext(),
"Inserted: " + search.getText().toString(), Toast.LENGTH_LONG)
.show();
}
#Override
protected void onStart() {
super.onStart();
List<History> history = db.getAllHistory();
for (History cn : history) {
String log = "Search Strings: " + cn.getName();
Log.d("Search Strings: ", log);
}
}
}
This is my activity in which I'm bringing my all database value on onStart() function. Now here I have to set all the data coming from database on the textview. Here is my DabaseHandler class in which I'm taking out each row.
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "historyManager";
private static final String TABLE_HISTORY = "histories";
private static final String KEY_NAME = "history";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_HISTORY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
void addHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
db.insert(TABLE_HISTORY, null, values);
db.close();
}
History getHistory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HISTORY, new String[] { KEY_NAME },
"=?", new String[] { String.valueOf(id) }, null, null, null,
null);
if (cursor != null)
cursor.moveToFirst();
History history = new History(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return history;
}
public List<History> getAllHistory() {
List<History> historyList = new ArrayList<History>();
String selectQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
History contact = new History();
contact.setName(cursor.getString(0));
historyList.add(contact);
} while (cursor.moveToNext());
}
return historyList;
}
public int updateHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
return db.update(TABLE_HISTORY, values, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
}
public void deleteHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HISTORY, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
db.close();
}
public int getHistoryCount() {
String countQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Please help in getting data printed on the textview. On the Log.d I can see all my data coming, one after another. But I'm not able to print all the data.
It's answer for "Thank You for that. Can you tell me how to set the data which I have printed in MainActivity on onStart() method (Log.d("")). If you can give me the code for that, that will be much easier for me."
try this:
List<String> listNames = new ArrayList<String>();//global variable
List<History> history = db.getAllHistory();
for (History cn : history) {
listNames.add(cn.getName());
}
or, if have in History field date try is, after easy will sort:
Map<String, Date> historyMap = new HashMap<String, Date>();
List<History> history = db.getAllHistory();
for (History cn : history) {
historyMap.put(cn.getName, cn.getDate);
}
You need make ListView in which will show your data from DB.Because you have many items datas getting from db.
I suggest to the next version:
In xml file you creat:
<ListView
android:id="#+id/list_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...>
You need create Adapter for your list with next xml resource:
<TextView
android:id="#+id/text_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
In java code:
in onCreate:
ListView list = (ListView) findViewById(R.id.list);
OurAdapter adapter = new OurAdapter(..., List<String> yourListWithName);
list.setAdapter(adapter);
if you want a more detailed description of the code tell me.
For add last item in top you need next, create spec. internal class :
class Holder implements Comparable<Holder> {
String key;
Double value;
public int compareTo(Holder another) {
return another.value.compareTo(value);
}
}
and use him how:
List<this.Holder> listSortforLastInTop = new ArrayList<this.Holder>();
and
for(...){
Holder holder = new Holder();
holder.key=...;
older.value=..;
listSortforLastInTop.add(holder);
}

Categories

Resources