Paul Moore
Paul Moore

Reputation: 134

How is context used in a class usage?

The line of code that is giving me fits is:

this.databaseHandler = new DatabaseHandler(MainActivity.

I have that module in the project and this line is from another project that I am trying to incorporate. I believe I need this line and am having trouble getting the idea of context parameter as it is used here. Yes, the line is incomplete because I can not finish it. Could my whole structure or thinking be wrong?

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.AsyncTask;


import com.Table.TableMainLayout;
import com.example.tablefreezepane.DatabaseHandler;

public class MainActivity extends Activity {

final String TAG = "MainActivity.java";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* Loads next module */
    setContentView(new TableMainLayout(this));
}
}
public class AsyncInsertData extends AsyncTask<String, String, String> {

DatabaseHandler databaseHandler;
String type;
long timeElapsed;

protected AsyncInsertData(String type){
    this.type  = type;
    this.databaseHandler = new DatabaseHandler(MainActivity.
     //(MainActivity.this);
}

// @type - can be 'normal' or 'fast'
//@Override
//protected void onPreExecute() {
//    super.onPreExecute();
//    tvStatus.setText("Inserting " + editTextRecordNum.getText() + " records...");
//}

@Override
protected String doInBackground(String... aurl) {

    try {

        // get number of records to be inserted
        int insertCount = 20;

        // empty the table
        databaseHandler.deleteRecords();

        // keep track of execution time
        long lStartTime = System.nanoTime();

        if (type.equals("normal")) {
            databaseHandler.insertNormal(insertCount);
        } else {
            databaseHandler.insertFast(insertCount);
        }

        // execution finised
        long lEndTime = System.nanoTime();

        // display execution time
        timeElapsed = lEndTime - lStartTime;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

protected void onPostExecute(String unused) {
    //Toast.makeText(getApplicationContext(),"This is an Android Toast Message", Toast.LENGTH_LONG).show();
    //tvStatus.setText("Done " + choice + " inserting " + databaseHandler.countRecords() + " records into table: [" + this.databaseHandler.tableName + "]. Time elapsed: " + timeElapsed / 1000000 + " ms.");
}

}

Thank you in advance.

Upvotes: 0

Views: 39

Answers (1)

Chad Bingham
Chad Bingham

Reputation: 33856

Where this is async, you can't access the context from MainActivity the way you are. To do so, add constructor with a context parameter, then replace your MainActivity.this with context

Upvotes: 1

Related Questions