android: how to assign value to a global variable from sql query? - android

i'd like to assign the resulting "reason" to a global variable for use with another process. How can i achieve this from this declaration and function?
private static String[] FROM = { _ID, EVENT01, EVENT02, EVENT03, REASON};
private static String ORDER_BY = EVENT01;
private Cursor getEvent() {
return managedQuery(CONTENT_URI, FROM, null, null, ORDER_BY);
}
many thanks for your help.

If you have the Cursor, then iterate it and access the value
while (cursor.moveToNext()) {
//access the value using getString(0), or getInt(0)
}
U need to store this global, I think its better to use static variable,
class Abc {
public static final String staticString;
----------------
----------------
}
Then you can access it anywhere using Abc.staticString
And its always better to create you Cursor inside a method and close it there itself, after its use.

Another process or thread?
For another process: If you have ContentProvider you can get Cursor from others processes.

Related

How can I get String in String[]?

String[] string = {getResourse().getString(R.string.girl), getResourse().getString(R.string.boy), getResourse().getString(R.string.child)};// Why is this code not working
And I tried do like this
String[] string = {getString(R.string.girk)....};
And also I tried do like
String[] string = {R.string.girl...};
Everything is not working, or it is impossible?
First of all, R.string.girl is int type.
If you really want to define it programatically like below,
String[] string2 = {getString(R.string.app_name)};
You should define it when your Activity/fragment's context is avaliable. For example, you can define it inside onCreate method but it is impossible to define it as a global variable (Because getString is the method of Context class).
You can do like in this example.
For more info https://developer.android.com/guide/topics/resources/string-resource.html#StringArray

How do I access the same database from different activities?

I am writing an app and I want to store the high scores. I have it working to show the high score on the end activity. However, I want to have a highscores activity to show all the highscores. I am doing this by, in the highscores activity, calling the end activity to return the high score, so the database doesn't change. After running a debug, I saw that it got to the databasehandler but got caught on getReadableDatabase(), saying that it was unable to invoke the method on a null object reference.
This is my highscores method(I didn't include the whole thing, and the ifs are because there are different difficulties of the game)
public class highscores extends Activity {
TextView mode, score;
Button right, back;
int modenum;
end get=new end();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_highscores);
mode =(TextView)findViewById(R.id.scorebar);
score =(TextView)findViewById(R.id.score);
right =(Button)findViewById(R.id.button14);
back =(Button)findViewById(R.id.highscores);
mode.setText("Easy");
score.setText(get.datatostring(1));
modenum =1;
}
public void right(View view){
if(modenum==1) {
modenum = 2;
mode.setText("Hard");
score.setText(get.datatostring(2));
}else if(modenum==2) {
modenum = 3;
mode.setText("X-Mode");
score.setText(get.datatostring(3));
}else {
modenum = 1;
mode.setText("Easy");
score.setText(get.datatostring(1));
}
}
This is in the end method
public String datatostring(int difficulty){
MyDBHandler db = new MyDBHandler(this, null,null,1);
return db.datatostring(difficulty);
}
And this is in the databasehandler
public String datatostring(int difficulty){
SQLiteDatabase db = getReadableDatabase();
String dbString = "";
String c;
if(difficulty==1)
c = COLUMN_SCORE;
else if(difficulty==2)
c = COLUMN_HARD;
else
c = COLUMN_X;
String query = "SELECT "+c+" FROM "+TABLE_SCORES;
Cursor cursor = db.rawQuery(query,null);
cursor.moveToFirst();
if(!cursor.isAfterLast()){
int index = cursor.getColumnIndex(c);
String value = cursor.getString(index);
if(value!=null){
dbString += cursor.getString(cursor.getColumnIndex(c));
}
}
db.close();
cursor.close();
return dbString;
}
I suggest to use a SQLiteOpenHelper to handle this.
You should see this example:
Android Sqlite DB
Hope that helps, i personally works in this way.
The other option is to use som ORM, i recommend to use GreenDao, its good, and lets handle easy way this kind of actions.
Regards.
Follow this tutorial to create a concurrent and scalable database
Remember :
You should always make database queries through one instance (Singleton) of your database adapter else you will face a lot of issues when accessing your database concurrently from different classes.
Use SQLiteOpenHelper class for accessing your database. As it gives you many useful functions eg. upgrading user's database when you publish app updates with schema changes.
The short answer is yes.
But as you see you have no clear concept of the connection.
Bd in the android is SQLite (recommendation) Always be on the same route, you need to create a class that allows you to manage and connect to the database. The class will be SQLiteOpenHelper
Check THIS
You can connect one or more times to the database, since activity A, B or activity you want.
The important thing is to define the handler to connect, close, make request to the database.

Globally defined instance of SQLite generates error

I want to declare an instance of SQLite Database globally as a private final variable.
1)why the way i used in the below posted code causes the logcat to generate erros and the app crashes.
2)is there any other way so I can define an instance of my DB globally and final?
Java_Code:
public class SQLiteTest00 extends Activity {
final MyDB myDB = new MyDB(this);
final SQLiteDatabase mySQLiteDB = myDB.getWritableDatabase();
final ContentValues myContVals = new ContentValues();
private final String TABLE_NAME = "MYDATA";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite_test00);
myContVals.put("name", "loc00");
myContVals.put("lat", 33);
myContVals.put("lng", 53);
myContVals.put("time", "12:30");
myContVals.put("date", "11/05/2014");
lodgeIntoDB(myContVals);
}
private void lodgeIntoDB(ContentValues cv) {
long newID = mySQLiteDB.insert(TABLE_NAME, null, cv);
if (newID == -1) {
Toast.makeText(getBaseContext(), "Error Commiting Record(s)", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Data Commited Successfully", Toast.LENGTH_SHORT).show();
}
}
}
Is MyDB your extended version of SQLiteOpenHelper? Also, why are you creating a final version of a ContentValues? Could you explain why you need a final copy of the db? The db will be private to your app by default, that is the way Android does it. If you extend SQLiteOpenHelper, then you can call the getWritableDatabase() in the onCreate of your main activity and if your db variable is a member variable you will have it. Maybe I am missing something. Also, from what I have read, it is best to close the db if you are not using it and then to use the helper class later to get it again if you need to read from or write to it. Thanks. Ps. one other thing, anytime I have seen the helper class called to get a copy of the db, it is done inside onCreate or another method not at the top in the variable declartions. Try moving it into onCreate.

Android Cursor with ORMLite to use in CursorAdapter

Is there any way to get Cursor for a query, which I am processing with ORMLite Dao object?
ORMLite now supports next(), previous(), moveRelative(offset), ... methods on the CloseableIterator class. This should allow you to move the underlying Cursor object around at will.
It also supports the following DAO Cursor methods:
dao.mapSelectStarRow(databaseResults) Return the latest row from the database results from a query to select *. With this you can change the cursor location (for example) and then get the current object.
dao.getSelectStarRowMapper() Provides a mapper that you can use to map the object outside of the Dao.
When you are building your own query with ORMLite, you use the QueryBuilder object. queryBuilder.prepare() returns a PreparedQuery which is used by various methods in the DAO. You can call dao.iterator(preparedQuery) which will return a CloseableIterator which is used to iterate through the results. There is a iterator.getRawResults() to get access to the DatabaseResults class. Under Android, this can be cast to an AndroidDatabaseResults which has a getCursor() method on it to return the Android Cursor.
Something like the following code:
// build your query
QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
qb.where()...;
// when you are done, prepare your query and build an iterator
CloseableIterator<Foo> iterator = dao.iterator(qb.prepare());
try {
// get the raw results which can be cast under Android
AndroidDatabaseResults results =
(AndroidDatabaseResults)iterator.getRawResults();
Cursor cursor = results.getRawCursor();
...
} finally {
iterator.closeQuietly();
}
This is a bit complicated but you are definitely having to peer behind the vale to get to this object which is hidden by the database abstraction classes.
Did you try some of Gray's advice from this post? He explains how you can select a column as another name, such as, select id as _id.
If you're in an Activity and don't want to mess around with the QueryBuilder give the following a go, which is just as effective.
Cursor cursor = getHelper().getReadableDatabase().query(tableName, projection, selection, selectionArgs, groupBy, having, sortOrder)
If you mean the getHelper() method to reach the dao methods create etc. you only have to inherit from the OrmLiteBaseActivity<YourDBHelper> and you can call it. It will look sth like this:
public class YourClass extends OrmLiteBaseActivity<YourDBHelper> {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
getHelper().getDao().queryForAll();
...
}
}
If you mean the cursor to handle database operation: I don't think that you can reach it! But I don't understand why you should need it. ORMLite has nearly all functions of the cursor. So what do you need it for?

How can getContentResolver() be called in Android?

I want to know the context in which getContentResolver() is called?
I have a scenario like this:
I have an activity A that calls a method myFunc() of class B which is not an activity.
So, in class B I have to use getContentResolver(). I directly called getContentResolver(). It was showing error. Then I called myFunc(Acitivy act) from the activity and called act.getContentResolver() which solved my problem. Is this the only way to call getContentResolver(), which means it can be used in context with activity or can be used alone.
getContentResolver() is method of class android.content.Context, so to call it you definitely need an instance
of Context ( Activity or Service for example).
You can use like this:
getApplicationContext().getContentResolver()
with the proper context.
The getContentResolver()method is also used when you query a Contact, using a Cursor object. I have used getContentResolver() to query the Android phone Contacts app, looking for contact info from a person's phone number, to include in my app. The different elements in a query (as shown below) represent what kind of contact details you want, and if they should be ordered, etc. Here is another example.
From the Content Provider Basics page from Android docs.
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
import android.content.Context;
import android.content.ContentResolver;
context = (Context)this;
ContentResolver result = (ContentResolver)context.getContentResolver();
//create activity object to get activity from Activity class for use to content resolver
private final Activity ActivityObj;
//create constructor with ActivityObj to get activity from Activity class
public RecyclerViewAdapterClass(Activity activityObj) {
this.ActivityObj = activityObj;
}
ActivityObj.getContentResolver(),.....,.....,null);
Access contentResolver in Kotlin , inside activities, Object classes &... :
Application().contentResolver
This one worked for me
getBaseContext();
A solution would be to get the ContentResolver from the context
ContentResolver contentResolver = getContext().getContentResolver();
Link to the documentation : ContentResolver

Categories

Resources