为什么我会收到此上下文和数据库错误?

时间:2015-04-12 00:06:49

标签: android database listview

  

我想...

创建一个简单的列表视图,可以使用sqldatabase中的数据填充。数据库工作,我已经看到它与其他代码一起工作。 XML很好,我真的不需要分享它。说到XML,主要活动中有两个按钮:new和show。 New会将您发送到下一个要添加到列表的活动。 Show会将数据添加到listview。这是主要活动的全部内容。另一个名为NewEntry的活动有一个取消按钮和一个保存按钮。它还有三个编辑视图来帮助您添加数据。

  

问题:

现在它甚至没有编译而没有错误。下面的主要活动列出了这两个错误。如果我注释掉这两个错误,我可以让应用程序运行。当我打开一个新活动并尝试保存它时,它会崩溃。它们与Context有关。我只是理解上下文所做的事情,除了它在所有事物中的事实。

  

此错误已在底部解决   此处的代码中包含两个编译器错误。这是主要活动。   没有其他编译器错误,只是逻辑错误。   我已经在评论中指出了它们   “”数据库管理员无法应用于听众“”   “无法解析构造函数”

此外,对上下文的任何解释都将受到赞赏。

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import java.util.ArrayList;



public class Main extends Activity {
    private DatabaseManager mydManager;
    private ListView productRec;
    ArrayList<String> tableContent;
    private LinearLayout addLayout;
    ArrayList<String> arrayAdpt;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        productRec=(ListView)findViewById(R.id.list);               
        Button newButton = (Button) findViewById(R.id.new_button);
        Button showButton = (Button) findViewById(R.id.show_button);
        Button newButton = (Button) findViewById(R.id.new_button);

        newButton.setOnClickListener(new OnClickListener() {            
            public void onClick(View n) {
               Intent x = new Intent(Main.this.getApplicationContext(), NewEntry.class);
               startActivity(x);

            }
        });


        showButton.setOnClickListener(new OnClickListener() {            //Want this to launch new intent
            public void onClick(View s) {    
               mydManager = new DatabaseManager(this); // <ERROR: 
               mydManager.openReadable();               //"DATA BASE MANAGER CANNOT BE APPLIED TO LISTENER"     
               tableContent = mydManager.retrieveRows();                
               productRec = (ListView)findViewById(R.id.list);       
               mydManager.retrieveRows();  //ERROR:
               ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent);    //ERROR:CANNOT RESOLVE CONSTRUCTOR
               productRec.setAdapter(arrayAdpt);
               productRec.setVisibility(View.VISIBLE);
               mydManager.close();

            }
        });


    }

}
  

这是NewEntry java类:

import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

public class NewEntry extends Activity {
    //   public static final int REQUEST_CODE = 1;
    private EditText titleView;
    private EditText authorView;
    private EditText priceView;
    private Button doneButton;
    private Button cancelButton;
    private DatabaseManager mydManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit);

        titleView = (EditText) findViewById(R.id.title_input);
        authorView = (EditText) findViewById(R.id.author_input);
        priceView = (EditText) findViewById(R.id.price_input);
        doneButton = (Button) findViewById(R.id.done_button);
        cancelButton = (Button) findViewById(R.id.cancel_button);

        Intent i = this.getIntent();


//rec inserted, its a boolean in the other one
        doneButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {

                mydManager = new DatabaseManager(NewEntry.this);
                mydManager.addRow(Integer.parseInt(titleView.getText().toString()), authorView.getText().toString(),
                        Float.parseFloat(priceView.getText().toString()));            ///sending in back to database
                // InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                // imm.hideSoftInputFromWindow(priceView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                mydManager.close();
                titleView.setText("");
                authorView.setText("");                //SOMETHING TO DO WITH DATA? maybe its blanking it out
                priceView.setText("");

                finish();
            }
        });
        cancelButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
} 
This is the database:
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;

public class DatabaseManager {
    public static final String DB_NAME = "shopping";
    public static final String DB_TABLE = "products";
    public static final int DB_VERSION = 1;
    private static final String CREATE_TABLE = "CREATE TABLE " + DB_TABLE + " (code INTEGER PRIMARY KEY, product_name TEXT, date FLOAT);";
    private SQLHelper helper;
    private SQLiteDatabase db;
    private Context context;

    public DatabaseManager(Context c){
        this.context = c;
        helper=new SQLHelper(c);
        this.db = helper.getWritableDatabase();
    }

    public DatabaseManager openReadable() throws android.database.SQLException {
        helper=new SQLHelper(context);
        db = helper.getReadableDatabase();
        return this;
    }
    public void close(){
        helper.close();
    }
    public boolean addRow(int t, String a, float p){
        ContentValues newProduct = new ContentValues();
        newProduct.put("title", t);
        newProduct.put("author", a);
        newProduct.put("price", p);
        try{db.insertOrThrow(DB_TABLE, null, newProduct);}
        catch(Exception e) {
            Log.e("Error in inserting rows ", e.toString());
            e.printStackTrace();
            return false;
        }
        db.close();
        return true;
    }

    public ArrayList<String> retrieveRows(){    ///Retrieves edit
        ArrayList<String> productRows=new ArrayList<String>();
        String[] columns = new String[]{"title", "author", "price"};
        Cursor cursor = db.query(DB_TABLE, columns, null, null, null, null, null);
        cursor.moveToFirst();
        while (cursor.isAfterLast() == false) {
            productRows.add(Integer.toString(cursor.getInt(0)) + ", "+cursor.getString(1)+", "+Float.toString(cursor.getFloat(2)));
            cursor.moveToNext();
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        return productRows;
    }


    public class SQLHelper extends SQLiteOpenHelper {
        public SQLHelper(Context c){
            super(c, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w("Products table","Upgrading database i.e. dropping table and recreating it");
            db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
            onCreate(db);
        }
    }
}

尝试检索行时出错:

04-11 22:08:25.552  21767-21767/com.example.alex.checkbox W/dalvikvm? threadid=1: thread exiting with uncaught exception (group=0x41e7cda0)
04-11 22:08:25.572  21767-21767/com.example.alex.checkbox E/AndroidRuntime? FATAL EXCEPTION: main
    Process: com.example.alex.checkbox, PID: 21767
    android.database.sqlite.SQLiteException: no such column: title (code 1): , while compiling: SELECT title, author, price FROM products
            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
            at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
            at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1448)
            at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1295)
            at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1166)
            at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1334)
            at com.example.alex.favoritebooks.DatabaseManager.retrieveRows(DatabaseManager.java:56)
            at com.example.alex.favoritebooks.Main$2.onClick(Main.java:45)
            at android.view.View.performClick(View.java:4654)
            at android.view.View$PerformClick.run(View.java:19438)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5487)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

newButton.setOnClickListener(...)代码中,您在创建Context时正在使用应用Intent。不要这样做 - 而是使用Activity Context ...

newButton.setOnClickListener(new OnClickListener() {
    public void onClick(View n) {
        // Simply use Main.this on the next line...
        Intent x = new Intent(Main.this, NewEntry.class);
        startActivity(x);
    }
});

showButton.setOnClickListener(...)代码中,您将OnClickListener对象的引用传递给DatabaseManager的构造函数,并且在创建ArrayAdapter时也是如此...

showButton.setOnClickListener(new OnClickListener() {
    public void onClick(View s) {
        mydManager = new DatabaseManager(this); //Here is the error

        ...

        ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tableContent);

        ...
    }
});

this关键字是指使用它的任何对象的当前实例 - 在这种情况下,this指的是OnClickListener不是Context。另外,您可以在ArrayAdapter代码中声明新的OnClickListener变量,而不是使用Activity中声明的变量。更改代码如下...

showButton.setOnClickListener(new OnClickListener() {
    public void onClick(View s) {
        mydManager = new DatabaseManager(Main.this);

        ...

        arrayAdpt = new ArrayAdapter<String>(Main.this, android.R.layout.simple_list_item_1, tableContent);

        ...
    }
});