将一段代码转换为类

时间:2013-03-29 11:51:49

标签: java android class

我在jave中创建一个单独的类时遇到问题 我有这部分代码

private class Read_from_db extends AsyncTask <String, Long, Void> {
    private final ProgressDialog dialog = new ProgressDialog(Read.this);
    // can use UI thread here
    protected void onPreExecute() {
    this.dialog.setMessage("Wait\nSome SLOW job is being done...");
    this.dialog.show();
    }
    @Override
    protected Void doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        try {
            //txtMsg.append("\n");
            // obtain a list of from DB
                String TABLE_NAME = "classicpoems__poet_header";
                String COLUMN_ID = "_id";
             //   String _ID = "_id";
                String COLUMN_NAME = "poet_name";
                String COLUMN_CENTURY = "century_start";
                String [] columns ={COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY};

            Cursor c = db.query(TABLE_NAME,columns,null, null, null, null, COLUMN_ID);
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(Read.this, R.layout.list_item, c, 
                       new String[] {COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY}, new int[] {R.id.list_item_text_id,R.id.list_item_text_main,R.id.list_item_text_sub}, 0);

            ListView list = (ListView) findViewById(R.id.list_poet_name);
            list.setAdapter(adapter);

            } catch (Exception e) {
                //Toast.makeText(Read.this, e.getMessage(), 1).show();
                Log.i(TAG,  e.getMessage());
            }
        db.close();
        return null;
    }
    // can use UI thread here
    protected void onPostExecute(final Void unused) {
    if (this.dialog.isShowing()) {
    this.dialog.dismiss();
    }
    // cleaning-up, all done
    this.dialog.setMessage("Done");

    }
}

每次活动加载时都必须重复(但有一些更改,例如TABLE_NAMER.id.list_poet_name columns和..) 我认为重复这段代码不是一种专业的方式,所以我想把它转换成一个单独的类,并在我使用它的每个活动中 但我不知道该怎么做..(我试过,但我总是得到错误,例如我不知道如何定义SimpleCursorAdapter的上下文 或者让Toast在这里工作,你可以帮助我如何将这个代码转换为一个单独的类

这是我的班级代码

   package co.tosca.persianpoem;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class Get_data extends AsyncTask<String, Long, Void> {
//Context context;
public String TABLE_NAME;
public String COLUMN_ID;
public String COLUMN_NAME;
public String COLUMN_CENTURY;
public String[] columns;
public int target;
private String DATABASE_NAME;
private static final String  SDcardPath = Environment.getExternalStorageDirectory().getPath();
private String DbPath = SDcardPath + "/Tosca/" + DATABASE_NAME;
private static final String TAG ="DatabaseHelper";
private SQLiteDatabase db;
private ProgressDialog dialog;
private Activity callingActivity;
public int adapter_list;

//public Get_data(Context context){
  //  this.context=context;
  //  DATABASE_NAME="persian_poem.db";
//}


public Get_data(Activity activity) {
    callingActivity = activity;
}
public Get_data() {
    TABLE_NAME="classicpoems__poet_header";
    COLUMN_ID="_id";
    COLUMN_NAME = "poet_name";

}


@Override
protected void onPreExecute() {

    this.dialog.setMessage("Wait\nSome SLOW job is being done...");
    this.dialog.show();
}



@Override
protected Void doInBackground(String... arg0) {
    // TODO Auto-generated method stub
    try {
        // obtain a list of from DB
        //    String TABLE_NAME = "classicpoems__poet_header";
         //   String COLUMN_ID = "_id";
         //   String _ID = "_id";
         //   String COLUMN_NAME = "poet_name";
         //   String COLUMN_CENTURY = "century_start";
          //  String [] columns ={COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY};

        Cursor c = db.query(TABLE_NAME,columns,null, null, null, null, COLUMN_ID);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(callingActivity, adapter_list, c, 
                   new String[] {COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY}, new int[] {R.id.list_item_text_id,R.id.list_item_text_main,R.id.list_item_text_sub}, 0);


        ListView list = (ListView)callingActivity.findViewById(target);
        list.setAdapter(adapter);

        } catch (Exception e) {
            Toast.makeText(callingActivity, e.getMessage(), 1).show();
            Log.i(TAG,  e.getMessage());
        }
    db.close();

    return null;
}


protected void onPostExecute(final Void unused) {
    dialog.dismiss();

}
}

当我想使用它时,我使用此代码

enter code here Get_data poet_name=new Get_data();
        poet_name.TABLE_NAME="classicpoems__poet_header";
        poet_name.COLUMN_ID = "_id";
        poet_name.COLUMN_NAME = "poet_name";
        poet_name.COLUMN_CENTURY = "century_start";
        poet_name.columns =new String[]{"_id","poet_name","century_start"};
        poet_name.adapter_list=R.layout.list_item;
        poet_name.target=R.id.list_poet_name;
        poet_name.execute();

但我收到错误..你能帮我找错吗?

我将初始代码更改为Get_data poet_name=new Get_data(this);,但我收到错误,但这里是logcat的一部分

01-06 04:25:32.262: E/AndroidRuntime(3244): FATAL EXCEPTION: main
01-06 04:25:32.262: E/AndroidRuntime(3244): java.lang.RuntimeException: Unable to start activity ComponentInfo{co.tosca.persianpoem/co.tosca.persianpoem.Read}: java.lang.NullPointerException
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.ActivityThread.access$600(ActivityThread.java:127)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.os.Looper.loop(Looper.java:137)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.ActivityThread.main(ActivityThread.java:4441)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at java.lang.reflect.Method.invoke(Method.java:511)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at dalvik.system.NativeStart.main(Native Method)
01-06 04:25:32.262: E/AndroidRuntime(3244): Caused by: java.lang.NullPointerException
01-06 04:25:32.262: E/AndroidRuntime(3244):     at co.tosca.persianpoem.Get_data.onPreExecute(Get_data.java:54)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:561)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.os.AsyncTask.execute(AsyncTask.java:511)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at co.tosca.persianpoem.Read.onCreate(Read.java:65)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.Activity.performCreate(Activity.java:4465)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-06 04:25:32.262: E/AndroidRuntime(3244):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
01-06 04:25:32.262: E/AndroidRuntime(3244):     ... 11 more

4 个答案:

答案 0 :(得分:1)

您应该在自己的文件中创建一个单独的类。将其公开,以便其他类可以看到它,并为其提供一些创建参数。

将调用Activity传递给类,然后您可以将该值用于需要当前Activity的toast之类的调用。

public class Read_from_db extends AsyncTask <String, Long, Void> {
    private final ProgressDialog dialog = new ProgressDialog(Read.this);
    private Activity callingActivity;
    public Read_from_db(Activity activity) {
        callingActivity = activity;
    }


    // can use UI thread here
    protected void onPreExecute() {
    this.dialog.setMessage("Wait\nSome SLOW job is being done...");
    this.dialog.show();
    }
    @Override
    protected Void doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        try {
            //txtMsg.append("\n");
            // obtain a list of from DB
                String TABLE_NAME = "classicpoems__poet_header";
                String COLUMN_ID = "_id";
             //   String _ID = "_id";
                String COLUMN_NAME = "poet_name";
                String COLUMN_CENTURY = "century_start";
                String [] columns ={COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY};

            Cursor c = db.query(TABLE_NAME,columns,null, null, null, null, COLUMN_ID);
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(Read.this, R.layout.list_item, c, 
                       new String[] {COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY}, new int[] {R.id.list_item_text_id,R.id.list_item_text_main,R.id.list_item_text_sub}, 0);

            ListView list = (ListView) findViewById(R.id.list_poet_name);
            list.setAdapter(adapter);

            } catch (Exception e) {
                Toast.makeText(callingActivity, e.getMessage(), 1).show();
                Log.i(TAG,  e.getMessage());
            }
        db.close();
        return null;
    }
    // can use UI thread here
    protected void onPostExecute(final Void unused) {
    if (this.dialog.isShowing()) {
    this.dialog.dismiss();
    }
    // cleaning-up, all done
    this.dialog.setMessage("Done");

    }
}

答案 1 :(得分:0)

(我希望我能正确理解你的问题。) 以下是我的建议:

使用具有SimpleCursorAdapter类型作为参数的构造函数,从上面的代码创建一个单独的类。使用Read_from_db创建具有表和列值的SimpleCursorAdapter对象,并在doInBackground方法中使用相同的值。

答案 2 :(得分:0)

您可以在AsyncTask类中创建一个构造函数,您可以在其中传递Context:

Context ctx;
public Read_from_db(Context ctx) {
    this.ctx = ctx;
}

上下文ctx是一个全局类变量,您可以使用它来代替Read.this

答案 3 :(得分:0)

只需像这样制作自定义类的构造函数:

public class Read_from_db extends AsyncTask<String, Long, Void> {
Context context;
private ProgressDialog dialog;

public Read_from_db(Context context){
    this.context=context;

}

@Override
protected void onPreExecute() {
    dialog = ProgressDialog.show(context, "dialog title", "dialog message.....");
}



@Override
protected Void doInBackground(String... arg0) {
    // TODO Auto-generated method stub

    //do your work here


    return null;
}


protected void onPostExecute(final Void unused) {
    dialog.dismiss();

}
}