Вопрос

I have three java files, the Main activity calls an AsyncTask by:

AsyncTaskRunner backgroundTask = new AsyncTaskRunner();
backgroundTask.execute();

This executes the task (http connect to pho files and returns JSON file). On the PostExcecute im trying to write the result to the SQLlite DB on the android device by running:

 class AsyncTaskRunner extends AsyncTask<Void, Void, String> {

      protected void onPostExecute(String result) {
             // super.onPostExecute(result);

          DatabaseHandler db = new DatabaseHandler(this);
             try{
                    JSONArray arr = new JSONArray(result);
                    db.dropAll();
                    for (int i=0; i<arr.length(); i++){
                    JSONObject jObj = arr.getJSONObject(i);
                    db.addEvent(new Event(jObj.getString("course"), jObj.getString("date"), jObj.getString("time"), jObj.getString("event")));        
                    }
                }
                catch (JSONException e) {e.printStackTrace();}

         }

The problem arises here = new DatabaseHandler(this), as I need to pass the Context to the DatabaseHandler.

Here is the start of the DatabaseHandler:

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

DatabaseHandler db = new DatabaseHandler(this) works fine when called from the MainActivity.

Это было полезно?

Решение

You could change your AsyncTask to recieve the context in its constructor.

So your code will look something like this:

class AsyncTaskRunner extends AsyncTask<Void, Void, String> {

  private Context ctx;
  public AsyncTaskRunner(Context ctx){
      this.ctx = ctx;
  }

  protected void onPostExecute(String result) {
         // super.onPostExecute(result);

      DatabaseHandler db = new DatabaseHandler(ctx);
         try{
                JSONArray arr = new JSONArray(result);
                db.dropAll();
                for (int i=0; i<arr.length(); i++){
                JSONObject jObj = arr.getJSONObject(i);
                db.addEvent(new Event(jObj.getString("course"), jObj.getString("date"), jObj.getString("time"), jObj.getString("event")));        
                }
            }
            catch (JSONException e) {e.printStackTrace();}

     }

Другие советы

How to pass Context from AyncTask to DatabaseHandler

Use AsyncTaskRunner class constructor for getting Activity context in AsyncTaskRunner class then pass it to DatabaseHandler constructor

In AsyncTaskRunner class add constructor which take Context as parameter:

  Context context;
  public AsyncTaskRunner(Context context){
      this.context = context;
  }

And pass as from Activity:

AsyncTaskRunner backgroundTask = new AsyncTaskRunner(Your_Activity_Name.this);
backgroundTask.execute();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top