数据库教程:对于MainActivity.DBAdapter类型,未定义open()方法

时间:2014-06-02 11:24:50

标签: android database eclipse sqlite

我正在尝试在SQLite Eclipse上执行此数据库教程:https://www.youtube.com/watch?v=j-IV87qQ00M

但最后我收到了一些错误..

在db.ppen();我得到错误:方法open()未定义类型MainActivity.DBAdapter 插入记录和关闭类似。

MainActivity:

    package com.example.studentdatabase;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
/** Called when the activity is first created. */

//DBAdapter db = new DBAdapter(this); 


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_main);

    Button addBtn = (Button)findViewById(R.id.add);
    addBtn.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this,     addassignment.class);
            startActivity(i);
        }
    });


    try {           
        String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
        File f = new File(destPath);            
        if (!f.exists()) {          
            CopyDB( getBaseContext().getAssets().open("mydb"), 
                new FileOutputStream(destPath));
        }
    } catch (FileNotFoundException e) {         
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    DBAdapter db = new DBAdapter(); 


    //---add an assignment---

    db.open();        
    long id = db.insertRecord("Hello World", "2/18/2012", "DPR 224", "First Android Project");        
    id = db.insertRecord("Workbook Exercises", "3/1/2012", "MAT 100", "Do odd numbers");
    db.close();


    //---get all Records---
    /*
    db.open();
    Cursor c = db.getAllRecords();
    if (c.moveToFirst())
    {
        do {          
            DisplayRecord(c);
        } while (c.moveToNext());
    }
    db.close();
    */

    /*
    //---get a Record---
    db.open();
    Cursor c = db.getRecord(2);
    if (c.moveToFirst())        
        DisplayRecord(c);
    else
        Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG).show();
    db.close();
    */


    //---update Record---
    /*
    db.open();
    if (db.updateRecord(1, "Hello Android", "2/19/2012", "DPR 224", "First Android Project"))
        Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();        
    db.close();
    */

    /*
    //---delete a Record---
    db.open();
    if (db.deleteRecord(1))
        Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show();            
    db.close();
    */
}

private class DBAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    //private ArrayList<>

    @Override
    public int getCount() {

        return 0;
    }

    @Override
    public Object getItem(int arg0) {

        return null;
    }

    @Override
    public long getItemId(int arg0) {

        return 0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {

        return null;
    }

}

public void CopyDB(InputStream inputStream, OutputStream outputStream) 
throws IOException {
    //---copy 1K bytes at a time---
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    inputStream.close();
    outputStream.close();
}

public void DisplayRecord(Cursor c)
{
    Toast.makeText(this, 
            "id: " + c.getString(0) + "\n" +
            "Title: " + c.getString(1) + "\n" +
            "Due Date:  " + c.getString(2),
            Toast.LENGTH_SHORT).show();        
} 

public void addAssignment(View view)
{

    Intent i = new Intent("com.pinchtapzoom.addassignment");
    startActivity(i);
    Log.d("TAG", "Clicked");
}

}

DBAdapter代码:

package com.example.studentdatabase;

public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_DUEDATE = "duedate";
public static final String KEY_COURSE = "course";
public static final String KEY_NOTES = "notes";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "AssignmentsDB";
private static final String DATABASE_TABLE = "assignments";
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_CREATE =
    "create table if not exists assignments (id integer primary key autoincrement, "
    + "title VARCHAR not null, duedate date, course VARCHAR, notes VARCHAR );";

private final Context context;    

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) 
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper 
{
    DatabaseHelper(Context context) 
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        try {
            db.execSQL(DATABASE_CREATE);    
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }
}    

//---opens the database---
public DBAdapter open() throws SQLException 
{
    db = DBHelper.getWritableDatabase();
    return this;
}

//---closes the database---    
public void close() 
{
    DBHelper.close();
}

//---insert a record into the database---
public long insertRecord(String title, String duedate, String course, String notes) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_TITLE, title);
    initialValues.put(KEY_DUEDATE, duedate);
    initialValues.put(KEY_COURSE, course);
    initialValues.put(KEY_NOTES, notes);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

//---deletes a particular record---
public boolean deleteContact(long rowId) 
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

//---retrieves all the records---
public Cursor getAllRecords() 
{
    return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
            KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, null, null, null, null, null);
}

//---retrieves a particular record---
public Cursor getRecord(long rowId) throws SQLException 
{
    Cursor mCursor =
            db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
            KEY_TITLE, KEY_DUEDATE, KEY_COURSE, KEY_NOTES}, 
            KEY_ROWID + "=" + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

//---updates a record---
public boolean updateRecord(long rowId, String title, String duedate, String course, String notes) 
{
    ContentValues args = new ContentValues();
    args.put(KEY_TITLE, title);
    args.put(KEY_DUEDATE, duedate);
    args.put(KEY_COURSE, course);
    args.put(KEY_NOTES, notes);
    return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}

addassignment code:

 package com.example.studentdatabase;


public class addassignment extends Activity {

DBAdapter db = new DBAdapter(this); 

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

}
public void addAssignment(View v)
{
    Log.d("test", "adding");
    //get data from form
    EditText nameTxt = (EditText)findViewById(R.id.editTitle);
    EditText dateTxt = (EditText)findViewById(R.id.editDuedate);
    EditText courseTxt = (EditText)findViewById(R.id.editCourse);
    EditText notesTxt = (EditText)findViewById(R.id.editNotes);

       db.open();        
       long id = db.insertRecord(nameTxt.getText().toString(), dateTxt.getText().toString(), courseTxt.getText().toString(), notesTxt.getText().toString());        
       db.close();

    nameTxt.setText("");
    dateTxt.setText("");
    courseTxt.setText("");
    notesTxt.setText("");
    Toast.makeText(addassignment.this,"Assignment Added", Toast.LENGTH_LONG).show();  

}

public void viewAssignments(View v)
{
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}

}

这里有什么问题?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您有两个名为DBAdapter的班级。另一个是MainActivity中的内部类,另一个是单独的类。 open()在单独的类中定义,而MainActivity隐式使用内部类版本。

要修复它,要么使用完全限定的包名称来引用该类,要么只重命名另一个类以将它们分开。