I want to display the String value of one of my data in my database inside a toast.
Here's what I've tried so far.
this is my main activity:
Button btnShow = (Button)findViewById(R.id.btnShow);
btnShow.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
DBUser dbUser = new DBUser(EditUserActivity.this);
dbUser.newNumber();
//get the new value of the number from the DB
Cursor c = dbUser.newNumber();
String numberRetrieved = c.getString(c.getColumnIndex("number")).toString();
Toast.makeText(EditUserActivity.this,"Current Modem No. is:" + numberRetrieved, Toast.LENGTH_LONG).show();
c.close();
dbUser.close();
}
});
and this is my method in my Database class:
public Cursor newNumber() {
String query = "SELECT * FROM " + DATABASE_TABLE + " WHERE _id=1";
System.out.println(query);
Cursor cur = db.rawQuery(query, null);
cur.moveToFirst();
return cur;
}
Just so you know that my database exist and it definitely has some values in it.
But whenever I run this code my application always force closes!
Hope anyone can help me in it. thanks!
public static final String COL_2 = "DRIVERNO";
Please be sure your columns like this then put COL_2 value DRIVERNO in c.getColumnIndex("DRIVERNO")
Like this
String numberRetrieved = c.getString(c.getColumnIndex("DRIVERNO")).toString();
I hope your app will not crash again I will solve my problem from this solution.Thanks
Related
I'm new to Android Studio and can't seem to find what I'm asking for.
I want to have a database that stores the data of a few people, e.g.
Steve Hardy, 16 Somewhere Land, Colorado, U.S.A.
I would like this to have headings (Name, Address, City, Country).
I'm just struggling with how to format a table like this and how I would link a database to this.
In android, mostly use sqlite databases. I can give you 3 simple functions I use to create database and table, insert data to table, & to read database values. If there is any unclear thing or you want any clarification, ask. I can help you.
public class MainActivity extends AppCompatActivity {
//Assign below 3 variables as global variables where class start.
SQLiteDatabase db; //Assign as a global variable
String DBName = "MyDB"; //Assign as a global variable
String TableName = "PeopleData"; //Assign as a global variable
//Call 3 function inside oncreate method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createDB_Table(); //calling 3 functions.
InsertDataToDB();
ReadDBData();
}
public void createDB_Table(){ //This function use to create database, table & columns.
db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS " + TableName + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Address TEXT, City TEXT, Country TEXT);");
db.close();
}
public void InsertDataToDB(){ //This function use to inset values to database.
db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
ContentValues cv = new ContentValues();
cv.put("Name","Steve Hardy");
cv.put("Address","16 Somewhere Land");
cv.put("City","Colorado");
cv.put("Country","USA");
db.insert(TableName, null, cv);
db.close();
}
public void ReadDBData() { //This function use to read data from database.
db = this.openOrCreateDatabase(DBName, MODE_PRIVATE, null);
Cursor cursor = db.rawQuery("SELECT * FROM " + TableName, null);
if (cursor.getCount() > 0) { //check cursor is not empty.
cursor.moveToFirst();
String DName = cursor.getString(cursor.getColumnIndex("Name"));
String DAddress = cursor.getString(cursor.getColumnIndex("Address"));
String DCity = cursor.getString(cursor.getColumnIndex("City"));
String DCountry = cursor.getString(cursor.getColumnIndex("Country"));
//Got the values from database. Then you can set those values to text view or something you use.
}
cursor.close();
db.close();
}
}
I have a simple function with SQLite raw query, it looks like :
public Cursor getOccurations ()
{
SQLiteDatabase db =this.getWritableDatabase();
Cursor data= db.rawQuery("select count(*) from Beacon_occurations where BEACON_ADDRESS='" + COL_2 + "' and TIME='" + COL_3 +"'", null);
return data;
}
And now here is a question, how should I display it properly ? When I try do something like :
data = db.getOccurations();
string = data.toString();
Log.e("Message",string);
I get : Message: android.database.sqlite.SQLiteCursor#1a81ae97 ofc it isn't data which I want get :)
How should I do it properly ?
For such debug logging purposes, have a look at DatabaseUtils#dumpCursorToString().
For non-debug purposes, call getString() et al. on the cursor.
try this:
while(data.moveToNext()){
String s = data.getString(data.getColumnIndex("column Name"));
}
or
while(data.moveToNext()){
String s = data.getString(0);
}
Reading a single value from a query is easier with a helper function, such as longForQuery() or stringForQuery():
public long getOccurations()
{
SQLiteDatabase db = getWritableDatabase();
return DatabaseUtils.longForQuery(db,
"select count(*) from Beacon_occurations where BEACON_ADDRESS=? and TIME=?",
new String[]{ COL_2, COL_3 });
}
But to count rows, there is an even easier helper function, queryNumEntries():
public long getOccurations()
{
SQLiteDatabase db = getWritableDatabase();
return DatabaseUtils.queryNumEntries(
db, "Beacon_occurations",
"BEACON_ADDRESS=? and TIME=?",
new String[]{ COL_2, COL_3 });
}
I am developing a dictionary app. I have the following code which show 20 most recent history word.
public List<Bean> getHistoryWords() {
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + HISTORY_NAME +
" WHERE " + STATUS + " ORDER BY " + STATUS + " DESC LIMIT 20" ;
Cursor cursor = db.rawQuery(sql, null);
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String english = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Bean(id, english, bangla, status));
}
cursor.close();
db.close();
return wordList;
}
I would like to provide an option for user to change the number of history item from LIMIT 20 to LIMIT 50 or LIMIT 100 through Preferences.
I follow this tutorial, but I was stuck in "5) Saving/reading data". I tried to put the SharedPreferences under getHistoryWords, but I got error cannot resolve getBaseContext.
public List<Bean> getHistoryWords() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Where should I put the code?
There is a simplest way for it.
First, create YourAppName , that extends Application
Declare Context as static and init it on Application 's onCreate method,
public YourApp extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
YourApp.context = getApplicationContext();
}
public static Context getAppContext() {
return YourApp.context;
}
}
declare YourApp in Manifest.xml
android:name="com.yourpackagename.app.YourApp" in application tag,
Now, you can get for Context, every where you need like this,
YourApp.getAppContext()
I hope this will help for you.
I have a task in which i have to display the rows selected using a query in one tab and the remaining rows in another tab. I have displayed the selected rows using SimpleCursorAdapter. When i tried to display the remaining rows in next tab it throws error. I have tried NOT IN but it also doesn't work. I have tried NOT EXISTS also it shows all rows. Anyone who can answer please help. I have posted my code here. Thanks in advance.
This is the activity of first tab which displays selected rows
public class OnlineDevices extends Activity {
ListView listOnline;
DatabaseHelper databaseHelper;
String count;
int conut;
TextView tvOnlineCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_online_devices);
listOnline=(ListView)findViewById(R.id.listView3);
tvOnlineCount = (TextView) findViewById(R.id.textView59);
databaseHelper=new DatabaseHelper(this);
SQLiteDatabase db=databaseHelper.getReadableDatabase();
String date= DateFormat.getDateInstance().format(new Date());
String statusQuery="select rowid _id, deviceContact from statusTable where sentTime='"+date+"'";
Cursor cursor1=db.rawQuery(statusQuery,null);
if (cursor1.getCount()>0){
while (cursor1.moveToNext()){
String deviceNo=cursor1.getString(cursor1.getColumnIndex("deviceContact"));
String device=deviceNo.substring(2, 12);
String query="select rowid _id, userName, uSerialNo from bikeTable where uContactNo='"+device+"' AND userName IS NOT NULL";
Cursor cursor2=db.rawQuery(query, null);
SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.status_item,cursor2,new String[]{"userName","uSerialNo"},new int[]{R.id.textView51,R.id.textView52});
listOnline.setAdapter(adapter);
}
}
try {
conut = listOnline.getAdapter().getCount();
count = String.valueOf(conut);
tvOnlineCount.setText(count);
}catch (Exception e){
e.printStackTrace();
int i=0;
Toast.makeText(OnlineDevices.this,"No device is active",Toast.LENGTH_SHORT).show();
tvOnlineCount.setText(String.valueOf(i));
}
}
}
Activity for second tab which display the remaining rows are
public class OfflineDevices extends Activity {
ListView listOffline;
DatabaseHelper databaseHelper;
String deviceContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline_devices);
listOffline=(ListView)findViewById(R.id.listView4);
databaseHelper=new DatabaseHelper(this);
SQLiteDatabase db=databaseHelper.getReadableDatabase();
String date= DateFormat.getDateInstance().format(new Date());
String query="select rowid _id, deviceContact from statusTable where sentTime='"+date+"'";
Cursor cursor1=db.rawQuery(query,null);
if (cursor1.getCount()>0){
while (cursor1.moveToNext()) {
deviceContact = cursor1.getString(cursor1.getColumnIndex("deviceContact"));
}
String device=deviceContact.substring(2, 12);
String query2="select rowid _id, userName, uSerialNo from bikeTable where userName IS NOT NULL AND uContactNo='"+device+"'";
Cursor cursor3=db.rawQuery(query2,null);
String query1="select rowid _id,*from bikeTable where userName IS NOT NULL NOT IN('"+query2+"')";
Cursor cursor2=db.rawQuery(query1,null);
SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.status_item,cursor2,new String[]{"userName","uSerialNo"},new int[]{R.id.textView51,R.id.textView52});
listOffline.setAdapter(adapter);
}
}
}
You have syntax errors in your query. In theory the following should work:
String query2 = "SELECT userName FROM bikeTable WHERE userName IS NOT NULL "
+ "AND uContactNo = '" + device + "'";
String query1 = "SELECT * FROM bikeTable WHERE userName IS NOT NULL "
+ "AND userName NOT IN(" + query2 + ")";
Here are the differences:
Your original code has single quotes around query2 inside the parentheses. This makes SQLite treat it as a string literal instead of an inner query.
Since query2 is being used in a NOT IN expression, it needs to
have a single result column, and it seems like userName is the one
you are interested in.
I advise spending some time going through the SQLite language pages. I'm fairly certain you can actually get the results you want using a single query that has a JOIN instead of making one query, checking the result, then making another query.
As an aside, it's considered best practice in Android to load data from a database on a background thread. Typically this is done with the Loader framework. You should also be closing cursors when you are finished with them (not the ones you give to the adapters, but the ones you use just to check for an online device).
private static String[] FROM = { _ID, DESCRIPTION, DATE, TITLE };
//private static String ORDER_BY = _ID + " DESC" ;
private Cursor getEvents() {
// Perform a managed query. The Activity will handle closing
// and re-querying the cursor when needed.
SQLiteDatabase db = post.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
null, null);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
TextView tv = new TextView(this);
// Stuff them all into a big string
StringBuilder builder = new StringBuilder(
"Saved events:\n" );
while (cursor.moveToNext()) {
// Could use getColumnIndexOrThrow() to get indexes
long id = cursor.getLong(0);
String description = cursor.getString(1);
String date = cursor.getString(2);
String title = cursor.getString(3);
builder.append(id).append(": " );
builder.append(description).append(": " );
builder.append(date).append(": " );
builder.append(title).append("\n" );
}
// Display on the screen
tv.setText(builder);
this.setContentView(tv);
}
So the showEvents function which is supposed to display the database is displaying a larger database than I created. It is showing 19 rows, yet I only called the insertorthrow function twice so it should have two rows, so I don't know how it can have more than 19 rows. I feel the problem may lie in my getEvents() function or showEvents() function which returns the cursor. Help would be appreciated.
Using db shell go to the location and delete the database .