I am trying to make an Android music player. To make things easier, I have decided to copy the Artists on the phone to a local DB and then make some custom queries to the local data. I know how to copy the managedQuery to a db, but cannot do so on an AsyncTask since managedQuery is only accessible by an Activity class. I am trying to do this call in my Application class upon app startup. Does anyone know a way to call managedQuery inside of the AsyncTask? I really do not want to do this in my first activity that is called since it will slow my load speed significantly.
This is what I would like to do, although I know this will not compile...
public class AplayApplication extends Application implements
OnSharedPreferenceChangeListener {
private static final String TAG = AplayApplication.class.getSimpleName();
private SharedPreferences prefs;
protected MusicData musicData;
protected PlayerHandler mMediaPlayer;
protected boolean isPlaying;
private boolean prefUseDefaultShuffle;
private boolean prefUseSmartShuffle;
private int prefArtistSkipDuration;
private int prefUnheardArtistPct;
protected TabHost tabHost;
protected Song currentSong;
protected int currentSongPosition;
private static final String PREFERENCE_KEY = "seekBarPreference";
protected boolean hasLoadedSongs;
private static AplayApplication aplayapp;
#Override
public void onCreate() {
super.onCreate();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
setPrefs();
Log.i(TAG, "Application started");
mMediaPlayer = new PlayerHandler();
// code in question below this line
musicData = new MusicData(this); // this creates instance of database helper to access db
// will call execute on async task here.
// new getArtist().execute();
}
private class getArtists extends AsyncTask<Void, Void, Boolean>{
Cursor artCursor;
#Override
protected Boolean doInBackground(Void... params) {
String[] proj = {
MediaStore.Audio.Artists._ID,MediaStore.Audio.Artists.ARTIST,
};
artCursor = managedQuery(
MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, proj, null,
null, MediaStore.Audio.Artists.ARTIST + " ASC");
ContentValues values = new ContentValues();
artCursor.moveToPosition(-1);
while (artCursor.moveToNext()) {
values.put(
MusicData.S_DISPLAY,
newMusicCursor.getString(newMusicCursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
values.put(MusicData.S_ARTIST, newMusicCursor
.getString(newMusicCursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
values.put(MusicData.S_FILE, newMusicCursor
.getString(newMusicCursor
.getColumnIndex(MediaStore.Audio.Media.DATA)));
this.musicData.insertMastSong(values);
}
return true;
}
//// code continues.....
As Sparky says, you could use CursorLoader instead of managedQuery.
If you are developing for sdk 8 you need to add Support Package to your project.
To avoid delay your application start maybe you could use a Service.
This is a little example for use a service, get the data from an url and then insert it to the database
public class GetArticlesService extends IntentService {
private static final String TAG = "GetArticlesService";
public GetArticlesService() {
super("GetdArticlesService");
}
/* (non-Javadoc)
* #see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
#Override
protected void onHandleIntent(Intent intent) {
String url = "http://example.com/artists.json";
String response = null;
try {
response = Utils.httpPost(getApplicationContext(), url + "/api/GetArticles", null);
} catch (HttpHostConnectException e) {
e.printStackTrace();
}
if(!TextUtils.isEmpty(response)){
try {
JSONArray list = new JSONArray(response);
if(list.length() > 0){
ContentValues toInsert = new ContentValues[];
JSONObject art = null;
int cant = list.length();
for(int i = 0;i< cant; i++){
toInsert.clear();
art = list.getJSONObject(i);
toInsert = new ContentValues();
toInsert.put(Articles._ID, art.getInt("id"));
toInsert.put(Articles.DESCRIPTION, art.getString("description"));
toInsert.put(Articles.BARCODE, art.getString("barcode"));
toInsert.put(Articles.RUBRO, art.getString("rubro"));
toInsert.put(Articles.CLAVE, art.getString("clave"));
getContentResolver().inert(Articles.CONTENT_URI, toInsert);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
managedQuery is deprecated. Use CursorLoader instead.
Related
I am busy with an application where i am getting data from my azure database with sql and storing it in an array. I created a separate class where i get my data and my main activity connects to this class and then displays it.
Here is my getData class:
public class GetData {
Connection connect;
String ConnectionResult = "";
Boolean isSuccess = false;
public List<Map<String,String>> doInBackground() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr=new ConnectionHelper();
connect =conStr.connectionclass(); // Connect to database
if (connect == null) {
ConnectionResult = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String,String> datanum=new HashMap<String,String>();
datanum.put("NAME",rs.getString("RAIL_NAME"));
datanum.put("PRICE",rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE",rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER",rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE",rs.getString("RAIL_SIZE"));
data.add(datanum);
}
ConnectionResult = " successful";
isSuccess=true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
ConnectionResult = ex.getMessage();
}
return data;
}
}
And in my Fragmentactivity.java I simply just call the class as shown here:
List<Map<String,String>> MyData = null;
GetValence mydata =new GetValence();
MyData= mydata.doInBackground();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_valence, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
My problem comes when I want to include the onPreExecute and onPostExecute because I am relatively new to android studio and I do not know where to put the following lines of code:
#Override
protected void onPreExecute() {
ProgressDialog progress;
progress = ProgressDialog.show(MainActivity.this, "Synchronising", "Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
}
You need to get the data from your azure database using a background service or AsyncTask. However, you are defining a class GetData which does not extend AsyncTask and hence the whole operation is not asynchronous. And I saw you have implemented doInBackground method which is not applicable here as you are not extending AsyncTask. I would suggest an implementation like the following.
You want to get some data from your azure database and want to show them in your application. In these kind of situations, you need to do this using an AsyncTask to call the server api to get the data and pass the data to the calling activity using an interface. Let us have an interface like the following.
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
Now from your Activity while you want to get the data through an web service call, i.e. AsyncTask, just the pass the interface from the activity class to the AsyncTask. Remember that your AsyncTask should have an instance variable of that listener as well. So the overall implementation should look like the following.
public abstract class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
public HttpResponseListener mHttpResponseListener;
private final Context mContext;
HttpRequestAsyncTask(Context mContext, HttpResponseListener listener) {
this.mContext = mContext;
this.mHttpResponseListener = listener;
}
#Override
protected String doInBackground(Void... params) {
String result = null;
try {
// Your implementation of getting data from your server
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
#Override
protected void onCancelled() {
mHttpResponseListener.httpResponseReceiver(null);
}
}
Now you need to have the httpResponseReceiver function implemented in the calling Activity. So the sample activity should look like.
public class YourActivity extends AppCompatActivity implements HttpResponseListener {
// ... Other code and overriden functions
public void callAsyncTaskForGettingData() {
// Pass the listener here
HttpRequestAsyncTask getDataTask = new HttpRequestGetAsyncTask(
YourActivity.this, this);
getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void httpResponseReceiver(String result) {
// Get the response callback here
// Do your changes in UI elements here.
}
}
To read more about how to use AsyncTask, you might consider having a look at here.
I have a database like this:
#Database(name = QuestionDatabase.NAME, version = QuestionDatabase.VERSION)
public class QuestionDatabase {
public static final String NAME = "QuestionDatabase"; // we will add the .db extension
public static final int VERSION = 1;
}
and a table like this:
#Table(database = QuestionDatabase.class)
public class Question extends BaseModel {
#PrimaryKey
public int localID;
#Column
public int Id;
#Column
public String Answer;
#Column
public String ImageURL;
#Column
public boolean IsFavorite;
#Column
public boolean IsSolved;
}
and an asynctask to retrive data from server:
public class QuestionRetriever extends AsyncTask<Integer, Void, Integer> {
private Activity callerActivity;
private QuestionAdapter questionsAdapter;
private List<Question> callerQuestions;
private Integer pageSize = 10;
public QuestionRetriever(Activity callerActivity, QuestionAdapter questionsAdapter, List<Question> questions){
this.callerActivity = callerActivity;
this.questionsAdapter = questionsAdapter;
this.callerQuestions = questions;
}
#Override
protected Integer doInBackground(Integer... pageNumbers) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.33:313/")
.addConverterFactory(GsonConverterFactory.create())
.build();
QuestionWebService service = retrofit.create(QuestionWebService.class);
Call<List<Question>> call = service.getQuestionsPaged(pageNumbers[0].toString(), pageSize.toString());
try {
Response<List<Question>> excecuted = call.execute();
List<Question> questions = excecuted.body();
FastStoreModelTransaction
.insertBuilder(FlowManager.getModelAdapter(Question.class))
.addAll(questions)
.build();
callerQuestions.addAll(questions);
callerActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
questionsAdapter.notifyDataSetChanged();
}
});
//Get TotalQuestionCount if not yet
if (((StatefulApplication) callerActivity.getApplication()).getQuestionCount() == -1){
Call<Integer> call2 = service.getQuestionsSize();
try {
((StatefulApplication) callerActivity.getApplication()).setQuestionCount(call2.execute().body());
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return 1;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO: show loader
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//TODO: hide loader
}
}
as you see every thing seems ok and eve after running FastStoreModelTransaction nothing wrong happens. no errors.
the init job is done in splash screen activity like this:
private void initializeEveryRun() {
//Initializing DBFlow
//DBFlow needs an instance of Context in order to use it for a few features such as reading from assets, content observing, and generating ContentProvider.
//Initialize in your Application subclass. You can also initialize it from other Context but we always grab the Application Context (this is done only once).
FlowManager.init(new FlowConfig.Builder(getApplicationContext()).build());
}
any idea about what should cause this problem or any solution to try?
TG.
I found the answer!!!
As you see in the model, the Id is the identifier of the object retrieved from server and LocalId is the auto-increment identifier that is stored locally. This was the problem. I've used the Id field as Primary Key and added a field named OnlineId for server side identifer and everything is ok now.
Is this a bug or I was using that wrong?
TG.
This is not execute transaction, it's just transaction creation.
As you can see it this test DBFlow - FastModelTest.kt.
FastStoreModelTransaction
.insertBuilder(FlowManager.getModelAdapter(Question.class))
.addAll(questions)
.build();
You must execute your transaction like this :
FlowManager.getDatabase(QuestionDatabase.class).executeTransaction(<<YourTransaction>>);
Otherwise, if you already had a DatabaseWrapper instance you can do <<YourTransaction>>.excute(<<YourDatabaseWrapper>>);.
I need from MyService (extends Service) start new AsyncLoadJSONDoc(this).execute(), but problem is "this" can't be there.
If im working from Activity there is no problem, i just have to create constructor for taking activity in asynctask.
The main problem is i need OPEN my database below in asynctask from service (null pointer exception)
Service is checking cloud for new information and saving in the android database. (every minute)
public class AsyncLoadJSONDoc extends AsyncTask<URL, Integer, ArrayList<Storage.JSONDocument>> {
private static final String TAG = "AsyncLoadJSONDoc";
Activity mActivity;`
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSS'Z'");
Date date = new Date();
private static final String TAG = "AsyncLoadJSONDoc";
Activity mActivity;
public AsyncLoadJSONDoc(Activity activity){
mActivity = activity;
}
#Override
protected ArrayList<Storage.JSONDocument> doInBackground(URL... params) {
StorageService storageService = App42API.buildStorageService();
Storage storage = storageService.findAllDocuments(
Constants.CLOUD_DB_NAME, Constants.COLLECTION_NAME);
ArrayList<Storage.JSONDocument> jsonDocList = storage.getJsonDocList();
Log.i(TAG, "Velikost databaze> " + jsonDocList.size());
return jsonDocList;
}
protected void onPostExecute(ArrayList<Storage.JSONDocument> jsonDocList) {
saveToDatabase(jsonDocList);
}
private void saveToDatabase(ArrayList<Storage.JSONDocument> jsonDocs) {
Log.i(TAG, "saveToDatabase");
Log.i(TAG + " Start>", df.format(date));
SQLiteDatabase db = (new DatabaseHelper(mActivity)).getWritableDatabase(); // <---There is null exception
ContentValues cv=new ContentValues();
DatabaseHelper dq = new DatabaseHelper(mActivity);
dq.onUpgrade(db, 1, 2);
for(Storage.JSONDocument oneJsonDoc : jsonDocs) {
cv.put(Constants.UPDATED_AT, oneJsonDoc.getUpdatedAt());
cv.put(Constants.CREATED_AT, oneJsonDoc.getCreatedAt());
cv.put(Constants.DOC_ID, oneJsonDoc.getDocId());
cv.put(Constants.JSON, oneJsonDoc.getJsonDoc());
if (oneJsonDoc.getLocation() == null) {
Log.i(TAG, "Location NULL");
cv.put(Constants.LATITUDE, (byte[]) null);
cv.put(Constants.LONGITUDE, (byte[]) null);
} else {
cv.put(Constants.LATITUDE, oneJsonDoc.getLocation().getLat().floatValue());
cv.put(Constants.LONGITUDE, oneJsonDoc.getLocation().getLng().floatValue());
}
db.insert(Constants.TABLE_NAME, Constants.JSON, cv);
Log.i(TAG, "insert");
}
db.close();
Log.i(TAG + " End>", df.format(date));
}
}
that is a very simple fix, the DatabaseOpenHelper only needs a context, not the actual activity, so u can just change the constructor:
public class AsyncLoadJSONDoc extends AsyncTask<URL, Integer, ArrayList<Storage.JSONDocument>> {
private Context mContext;
public AsyncLoadJSONDoc(Context context){
mContext = context.getApplicationContext();
}
and replace with mContext in new DatabaseHelper(mContext)
Also you should delete those lines:
DatabaseHelper dq = new DatabaseHelper(mActivity);
dq.onUpgrade(db, 1, 2);
They are simply wrong. You should never call onUpgrade, the system automatically calls it for you when necessary.
I'm developing an android 3.1 application.
This question is not specific for Android, it is about how to design a class that access a database. I asked here because my code is for Android.
I have a class, DBManager, to work with Sqlite database. This is a part of its implementation:
public class DBManager
{
// Variable to hold the database instance
private SQLiteDatabase db;
// Database open/upgrade helper
private DatabaseHelper dbHelper;
public DBManager(Context _context)
{
Log.v("DBManager", "constructor");
dbHelper = new DatabaseHelper(_context, SqlConstants.DATABASE_NAME, null, SqlConstants.DATABASE_VERSION);
}
public DBManager open() throws SQLException
{
Log.v("DBManager", "open");
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
Log.v("DBManager", "close");
db.close();
}
...
/**
* Query all forms available locally.
* #return A list with all forms (form.name and form.FormId) available on local db
* or null if there was a problem.
*/
public ArrayList<Form> getAllForms()
{
Log.v("DBManager", "getAllForms");
ArrayList<Form> list = null;
Cursor c = null;
try
{
c = this.getAllFormsCursor();
if (c != null)
{
int formNameIndex = c.getColumnIndex(SqlConstants.COLUMN_FORM_NAME);
int formIdIndex = c.getColumnIndex(SqlConstants.COLUMN_FORM_ID);
c.moveToFirst();
if (c.getCount() > 0)
{
list = new ArrayList<Form>(c.getCount());
do
{
Form f = new Form();
f.Name = c.getString(formNameIndex);
f.FormId = c.getString(formIdIndex);
list.add(f);
}
while (c.moveToNext());
}
}
}
catch (Exception e)
{
e.printStackTrace();
list = null;
}
finally
{
if (c != null)
c.close();
}
return list;
}
private Cursor getAllFormsCursor()
{
Log.v("DBManager", "getAllFormsCursor");
return db.query(SqlConstants.TABLE_FORM,
new String[] {
SqlConstants.COLUMN_FORM_ID,
SqlConstants.COLUMN_FORM_NAME}, null, null, null, null, null);
}
}
And this is an AsyncTask that uses DBManager:
private class DbFormListAsyncTask extends AsyncTask<Void, Void, ArrayList<Form>>
{
private Context mContext;
private ProgressDialog loadingDialog;
private DBManager dbMan;
DbFormListAsyncTask(Context context)
{
this.mContext = context;
loadingDialog = new ProgressDialog(mContext);
loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loadingDialog.setMessage("Retriving forms. Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.show();
}
#Override
protected ArrayList<Form> doInBackground(Void... arg0)
{
dbMan = new DBManager(mContext);
dbMan.open();
return dbMan.getAllForms();
}
protected void onPostExecute(ArrayList<Form> forms)
{
if (forms != null)
{
ListActivity act = (ListActivity) mContext;
act.setListAdapter(new AvaFormAdapter(act, R.layout.ava_list_item, forms));
}
else
{
TextView errorMsg = (TextView)
((FormsListActivity) mContext).findViewById(R.id.formErrorMsg);
errorMsg.setText("Problem getting forms. Please try again later.");
}
loadingDialog.dismiss();
if (dbMan != null)
dbMan.close();
}
}
As you can see I have to:
Create DBManager instance.
Open database with dbMan.open()
Call dbMan.getAllForms()
Close database with dbMan.close() on onPostExecute.
I thought that I could add db.open() and db.close() on dbMan.getAllForms() to avoid calling it every time I use dbMan.getAllForms().
What do you think about this? What is the best approach?
I would put it inside getAllForms() or do something like that
protected ArrayList<Form> doInBackground(Void... arg0)
{
dbMan = new DBManager(mContext);
dbMan.open();
ArrayList<Form> resutl = dbMan.getAllForms();
dbMan.close();
return result;
}
Since you don't need the db connection after you have the result you can close it right away.
Edit: if you run that AsyncTask several times then opening/closing will introduce unnecessary overhead. In that case you may want to instanciate the dbManager from your Activity (maybe open() in the constructor of DbManager) and close it once you leave your activity. Then pass Dbmanager to the AsyncTask.
Make your database helper class a singleton, and don't explicitly close the SQLiteDatabase. It will be closed and flushed when your app's process exits.
I face two main problems when using a sqlite command inside an AsncTask in android.
When I execute a select command on the first try I get no results but on the second try (loading a activity that has this Asynctask) I do get results.
Sometimes I get an error that the database is not closed despite that it is already closed/
What is the problem with this?
UPDATE:
This is the code that retrive data from database (db.getAllMessage)
private ArrayList<FriendMessagesResulted> getMessagesFromCach(Context c){
FriendMessagesResulted messagesResulted1 = new FriendMessagesResulted();
DBAdapter db = new DBAdapter(c);
Cursor c1;
db.open();
c1 = db.getAllMessage(Settings.getCurrentUserId(c),Integer.parseInt(fId));
Log.d("***Database count",c1.getCount()+" from: "+Settings.getCurrentUserId(c)+" to:"+Integer.parseInt(fId));
c1.moveToFirst();
if(c1.getCount()>0)
status=true;
if (messagesResultedList == null) {
messagesResultedList = new ArrayList<FriendMessagesResulted>();
}
else
messagesResultedList.clear();
while (c1.isAfterLast() == false) {
if(Integer.parseInt(c1.getString(0))>maxId)
maxId=Integer.parseInt(c1.getString(0));
messagesResulted1.set_mId(Integer.parseInt(c1.getString(0)));
messagesResulted1.set_msgTxt("MD:"+c1.getString(3));
messagesResulted1.set_MessageTime(c1.getString(4));
messagesResulted1.set_dir(c1.getString(5));
messagesResultedList.add(messagesResulted1);
c1.moveToNext();
}
db.close();
c1.close();
return messagesResultedList;
}
and this the code for AsyncTask, where I call get getMessagesFromCach method
private void getMessages(final Context c)
{
handler = new Handler();
r=new Runnable() {
public void run() {
class RecentMessageLoader extends AsyncTask<Void, Void, ArrayList<FriendMessagesResulted>>{
ArrayList<FriendMessagesResulted> messagesResultedList=null;
#Override
protected ArrayList<FriendMessagesResulted> doInBackground(Void... params) {
if(!finishLoadingPastMessages)
{
messagesResultedList=getMessagesFromCach(c);
if(!status){
Log.d("Where are you","I'm in JSON");
messagesResultedList=getMessagesFromJSON(c);
}
}
else{
Log.d("Where are you","I'm in Recent messages");
messagesResultedList=getRecentMessages(c,Settings.getCurrentUserId(c),Integer.parseInt(fId));
}
return messagesResultedList;
}
protected void onPostExecute( ArrayList<FriendMessagesResulted> FMRList ) {
// to disappear loading message
d.dismiss();
finishLoadingPastMessages=true;
if(FMRList!=null){
for(int i=FMRList.size()-1;i>=0;i--)
addMessage(FMRList.get(i),c);
}
handler.postDelayed(r, 2000);
}
}
new RecentMessageLoader().execute();
}
};
handler.post(r);
}
UPDATE 2 : Cach class ..
public class Cach {
static DBAdapter db;
public Cach(Context c)
{
}
public static void AddMessages(Context c,
int id,
int fromId,
int toId,
String message,
String dir,
String MessageTime)
{
db = new DBAdapter(c);
db.open();
long id2;
id2 = db.insertMessage(id, fromId, toId, message, dir,MessageTime);
db.close();
}
}
It seems the problem is with the type of variables you are using.. there must be Static variables of instance variables which are getting set from many sources... try not to use static variables and use local variables I mean in the methods implicitly.