错误:未使用的Import语句 - 导入android.widget.AdapterView.OnItemClickListener; &安培; import android.content.Context;

时间:2015-10-03 14:56:07

标签: java android sqlite android-layout importerror

我制作了一个简单的应用程序,用于保存和显示书签 通过单击主活动中的菜单项来调用视图书签活动。

问题是当我单击选项查看存储在视图书签Activity中的书签时,我的应用程序崩溃了。
我认为问题在于书签Activity,因为我有一个未使用的导入语句AdapterView.OnItemClickListener& content.Context。

如何解决此问题?

PS:当我点击主Activity中的选项以通过启动保存书签活动来保存书签时,它可以很好地工作。

这是我的代码:

BookmarkPage.class

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

import android.view.KeyEvent;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import java.util.ArrayList;




public class BookmarkPage extends Activity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;

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

    mydb = new DBHelper(this);
    ArrayList array_list = mydb.getAllBookmarks();
    ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);

    obj = (ListView)findViewById(R.id.listView1);
    obj.setAdapter(arrayAdapter);
    obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            // TODO Auto-generated method stub
            int id_To_Search = arg2 + 1;

            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", id_To_Search);

            Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);

            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });
}

public boolean onKeyDown(int keycode, KeyEvent event) {
    if (keycode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
    }
    return super.onKeyDown(keycode, event);
}
} 

bookmark_page.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".BookmarkPage">



<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:text="Bookmarks"
    android:textSize="30sp" />

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView">
</ListView>


</RelativeLayout>

logcat的:

    OpenGL ES Shader Compiler Version: E031.25.03.00
Build Date: 12/04/14 Thu
Local Branch:
Remote Branch: quic/LA.BF.1.1_rb1.14
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1_RB1.05.00.00.002.030 +  NOTHING
10-03 18:10:35.793  18581-18642/com.carsaleindiaofficial.csitestapp W/cr.media﹕ Requires BLUETOOTH permission
10-03 18:10:35.830  18581-18581/com.carsaleindiaofficial.csitestapp E/libEGL﹕ validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-03 18:10:35.890  18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.891  18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
10-03 18:10:35.922  18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:35.922  18581-18581/com.carsaleindiaofficial.csitestapp I/art﹕ Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
10-03 18:10:36.276  18581-18581/com.carsaleindiaofficial.csitestapp W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
10-03 18:10:36.318  18581-18581/com.carsaleindiaofficial.csitestapp W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
10-03 18:10:36.836  18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Render dirty regions requested: true
10-03 18:10:36.902  18581-18581/com.carsaleindiaofficial.csitestapp D/Atlas﹕ Validating map...
10-03 18:10:36.944  18581-18639/com.carsaleindiaofficial.csitestapp W/chromium﹕ [WARNING:data_reduction_proxy_config.cc(630)] SPDY proxy OFF at startup
10-03 18:10:37.192  18581-18681/com.carsaleindiaofficial.csitestapp I/OpenGLRenderer﹕ Initialized EGL, version 1.4
10-03 18:10:37.201  18581-18681/com.carsaleindiaofficial.csitestapp D/OpenGLRenderer﹕ Enabling debug mode 0
10-03 18:10:38.109  18581-18581/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 49 frames!  The application may be doing too much work on its main thread.
10-03 18:10:38.213  18581-18581/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Visible
10-03 18:10:38.222  18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background sticky concurrent mark sweep GC freed 10653(792KB) AllocSpace objects, 6(92KB) LOS objects, 12% free, 6MB/7MB, paused 1.507ms total 130.800ms
10-03 18:10:38.894  18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:41.925  18581-18596/com.carsaleindiaofficial.csitestapp I/art﹕ Background partial concurrent mark sweep GC freed 12880(607KB) AllocSpace objects, 1(39KB) LOS objects, 40% free, 7MB/11MB, paused 1.053ms total 158.419ms
10-03 18:10:42.812  18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581
10-03 18:10:43.549  18581-18581/com.carsaleindiaofficial.csitestapp W/cr.BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 18581

问题在进度条之后开始:消失(即当我按下查看保存的书签选项时)

10-03 21:13:12.096  18489-18489/com.carsaleindiaofficial.csitestapp I/pageFinished﹕ yesss
10-03 21:13:12.353  18489-18489/com.carsaleindiaofficial.csitestapp I/progressBar﹕ Gone
10-03 21:13:26.413  18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 64 frames!  The application may be doing too much work on its main thread.
10-03 21:13:28.701  18489-18489/com.carsaleindiaofficial.csitestapp W/art﹕ Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
10-03 21:13:30.289  18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 129 frames!  The application may be doing too much work on its main thread.
10-03 21:13:31.604  18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 78 frames!  The application may be doing too much work on its main thread.
10-03 21:13:33.328  18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 80 frames!  The application may be doing too much work on its main thread.
10-03 21:13:35.714  18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 38 frames!  The application may be doing too much work on its main thread.
10-03 21:13:36.532  18489-18489/com.carsaleindiaofficial.csitestapp I/Choreographer﹕ Skipped 44 frames!  The application may be doing too much work on its main thread.
10-03 21:13:37.719  18489-18489/com.carsaleindiaofficial.csitestapp E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns.
10-03 21:13:37.777  18489-18489/com.carsaleindiaofficial.csitestapp D/AndroidRuntime﹕ Shutting down VM
10-03 21:13:37.892  18489-18489/com.carsaleindiaofficial.csitestapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.carsaleindiaofficial.csitestapp, PID: 18489
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carsaleindiaofficial.csitestapp/com.carsaleindiaofficial.csitestapp.BookmarkPage}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
        at android.app.ActivityThread.access$800(ActivityThread.java:148)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
 Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
        at android.database.CursorWindow.nativeGetString(Native Method)
        at android.database.CursorWindow.getString(CursorWindow.java:438)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
        at com.carsaleindiaofficial.csitestapp.DBHelper.getAllBookmarks(DBHelper.java:90)
        at com.carsaleindiaofficial.csitestapp.BookmarkPage.onCreate(BookmarkPage.java:32)
        at android.app.Activity.performCreate(Activity.java:5953)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
        at android.app.ActivityThread.access$800(ActivityThread.java:148)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
10-03 21:13:43.601  18489-18489/com.carsaleindiaofficial.csitestapp I/Process﹕ Sending signal. PID: 18489 SIG: 9

我的数据库:DBHelper.class

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";
public static final String BOOKMARKS_TABLE_NAME = "bookmarks";
public static final String BOOKMARKS_COLUMN_ID = "id";
public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";
private HashMap hp;

public DBHelper(Context context)
{
    super(context, DATABASE_NAME , null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(
            "create table bookmarks " +
                    "(id integer primary key, bmtitle text)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS bookmarks");
    onCreate(db);
}

public boolean insertBookmark  (String title)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("dbtitle", title);
    db.insert("bookmarks", null, contentValues);
    return true;
}

public Cursor getData(int id){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from bookmarks where id="+id+"", null );
    return res;
}

public int numberOfRows(){
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, BOOKMARKS_TABLE_NAME);
    return numRows;
}

public boolean updateBookmark (Integer id, String title)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("name", title);
    db.update("bookmarks", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deleteBookmark (Integer id)
{
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete("bookmarks",
            "id = ? ",
            new String[] { Integer.toString(id) });
}

public ArrayList<String> getAllBookmarks()
{
    ArrayList<String> array_list = new ArrayList<String>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from bookmarks", null );
    res.moveToFirst();

    while(res.isAfterLast() == false){
        array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
        res.moveToNext();
    }
    return array_list;
}
}

MainActivity.class

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;

@SuppressLint("SetJavaScriptEnabled")

public class MainActivity extends  AppCompatActivity {



private WebView view;
ProgressBar progressBar;
ImageView im;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setLogo(R.drawable.ic_launcher);
    getSupportActionBar().setDisplayUseLogoEnabled(true);
    setContentView(R.layout.activity_main);

    progressBar = (ProgressBar) this.findViewById(R.id.progressBar1);
    im = (ImageView) this.findViewById(R.id.imageView2);
    String url = "http://www.carsaleindiaofficial.com/?m=1";
    view = (WebView) this.findViewById(R.id.webView);
    view.setWebViewClient(new MyWebViewClient());
    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setDomStorageEnabled(true);
    view.loadUrl(url);

}

public class MyWebViewClient extends WebViewClient {

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        Log.i("pageFinished", "yesss");
        progressBar.setVisibility(View.GONE);
        im.setVisibility(View.GONE);
        Log.i("progressBar", "Gone");
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        progressBar.setVisibility(View.VISIBLE);
        Log.i("progressBar", "Visible");
        super.onPageStarted(view, url, favicon);
    }


    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(Uri.parse(url).getHost().endsWith("carsaleindiaofficial.com"))  {
            Log.i("ShldOvrideUrl", "CSI");
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        Log.i("ShldOvrideUrl", "OtherSite");
        return true;

    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item){
    super.onOptionsItemSelected(item);

    switch(item.getItemId())
    {
        case R.id.add_bookmark:
            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", 0);
            Log.i("addBookmark", "loadingAddBookmark");
            Intent intent = new Intent(getApplicationContext(),DisplayBookmarks.class);
            intent.putExtras(dataBundle);

            startActivity(intent);
            return true;

        case R.id.show_bookmark:
            Log.i("showBookmark", "loadingShowBookmark");
            Intent intent2 = new Intent(getApplicationContext(),BookmarkPage.class);
            startActivity(intent2);
            return true;

        case R.id.action_reload:
        Log.i("actionReload", "ReloadingURL");
        view.loadUrl(view.getUrl());


        default:
            return super.onOptionsItemSelected(item);
    }
}



@Override
public void onBackPressed() {
    if (view.canGoBack()) {
        view.goBack();
    } else {
        super.onBackPressed();
    }
}

}

1 个答案:

答案 0 :(得分:1)

这是你的错误:

Failed to read row 0, column -1 from a CursorWindow which has 9 rows, 2 columns. ... Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

这是因为你创建了这个表:

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(
            "create table bookmarks " +
                    "(id integer primary key, dbtitle text)"
    );
}

然后您尝试访问不存在的列:

while(res.isAfterLast() == false){
    array_list.add(res.getString(res.getColumnIndex(BOOKMARKS_COLUMN_NAME)));
    res.moveToNext();
}

其定义为字符串常量:

public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";

但它不是作为表格列创建的。

column -1表示您的表格中没有名为bmtitle的列 这是正确的,因为相反,有一个名为dbtitle的列。

快速修复:

只需更改

public static final String BOOKMARKS_COLUMN_NAME = "bmtitle";

public static final String BOOKMARKS_COLUMN_NAME = "dbtitle";