使用从一个类到类的方法

时间:2014-07-22 21:34:52

标签: java android

我有两个班级:

  • MyActivity.Java
  • DatabaseHandler.Java

我想从方法“getCurrentCar”中获取返回的String并将其放在MyActivity.java中

DatabaseHandler.Java:

public class DatabaseHandler extends SQLiteOpenHelper {
    public Car getCurrentCar() {

            SQLiteDatabase db       =   getWritableDatabase();
            String sql              =   "SELECT " + KEY_ID + "," + KEY_IMAGE + " FROM " + TABLE_CARS + "ORDER BY RANDOM() LIMIT 1";
            Cursor cursor           =   db.rawQuery(sql, new String[] {});
            Car car = null;

            try {
                if (cursor.moveToFirst()) {
                    car = new Car(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3));
                }
            }
            finally {
                if (cursor != null && !cursor.isClosed()) {
                    cursor.close();
                }
                    db.close();
            }
            return car;
        }
}

我已尝试过,但参数是要求上下文。

//DatabaseHandler handler = new DatabaseHandler(contexthere);
DatabaseHandler handler = new DatabaseHandler();
handler.getCurrentCar();

我想知道如何获取该返回并将其放入MyActivity.java中,以便我可以使用BitmapFactory重新创建图像。

由于

1 个答案:

答案 0 :(得分:1)

Context表示当前运行时:

protected void onCreate(Bundle savedInstanceState) {
        ...........
        ...........

         // you should  instantiate 'DatabaseHandler'  here
        DatabaseHandler db = new DatabaseHandler(this); // "this" refer to the context

        ..........
        ..........

 // insert the rows
 db.createCar(new Car("Sesame street A","23423","anImage1"));
 db.createCar(new Car("Sesame street B","43543","anImage2"));

 // get the rows which you mean string
 for(Car cars : db.getCurrentCar()){
 String rows= "id : "+ cars.getID()+ " address : "+getAddress() + "postcode : "+getPostcode()+" image : "+getImage());
 }  
}

根据' getter'进行调整.getID(),getAddress(),getPostcode(),getImage()Car类中的方法名称,因为我可能写错了

** 我在上面编写的代码基于您通过链接共享的文件。 (您的文件缺少Car类),但我只是预测它应该像上面那样: