在WebView中使用sqlite数据库中的URL

时间:2014-03-26 05:55:01

标签: java android sqlite

我正在尝试根据主要活动传递的意图数据构建一个从数据库中提取网址的应用

我已经实现了代码,但应用程序不断崩溃/强制关闭。

这是我的DBHelper课程

package com.snplabs.learncpp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

final protected static String DATABASE_NAME="cppreference";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null,2);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion) return;
db.execSQL("DROP DATABASE IF EXISTS " + DATABASE_NAME +";");
onCreate(db);
}
@Override
public void onCreate(SQLiteDatabase db) {

//here is the database definition
db.execSQL("CREATE TABLE cppref " +
"(_id INTEGER PRIMARY KEY, link TEXT);");
//insert pre-configured records
db.execSQL("INSERT INTO cppref (_id, link) VALUES(1,'URL_HERE');");
db.execSQL("INSERT INTO cppref (_id, link) VALUES(2,'URL_HERE');");
db.execSQL("INSERT INTO cppref (_id, link) VALUES(3,'URL_HERE');");
db.execSQL("INSERT INTO cppref (_id, link) VALUES(4,'URL_HERE');");
db.execSQL("INSERT INTO cppref (_id, link) VALUES(5,'URL_HERE');");
  }


}

这是使用DBHelper获取网址的类:

package com.snplabs.learncpp;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class ViewItem extends Activity{
private DBHelper dbhelper=new DBHelper(this);
private SQLiteDatabase db;
private String pgurl;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.item_view);

    db = dbhelper.getReadableDatabase();

    TextView txtProduct = (TextView) findViewById(R.id.product_label);

    Intent i = getIntent();
    // getting attached intent data
    String product = i.getStringExtra("product");
    int data=Integer.parseInt(product.substring(4));
    // displaying selected product name

    txtProduct.setText(product);

    Cursor quer=db.rawQuery("SELECT link FROM cppref "+"WHERE _id='"+data+"';", null);
            //-fetch record
            if(quer.getCount()!=0){
            quer.moveToFirst();//go to first row
            pgurl=quer.getString(1).toString();
            }
            else{
            //display some notice here saying no data found
            txtProduct.setText("Error");
            }

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(new WebViewClient());
    myWebView.loadUrl(pgurl);
}

}

1 个答案:

答案 0 :(得分:1)

首先纠正这个移动

 DBHelper dbhelper=new DBHelper(this);

onCreate(......)

之后的setContentView(.....)