Introduce how to use sqlite with Android - Save current page.
1. webviewactivity.xml
add: button which will save current page to your sqlite server
<Button
android:id="@+id/bScript"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:text="save" />
2. WebviewActivity.java
add: below lines
public class WebviewActivity extends Fragment implements OnClickListener {
...
private String currentUrl, currentUrlTitle;
private Button save;
private void getInitialValues(View view) {
...
save = (Button) view.findViewById(R.id.bScript);
save.setOnClickListener(this);
...
}
...
...
private void setWebCondition() {
...
webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onReceivedTitle(WebView view, String sTitle) {
super.onReceivedTitle(view, sTitle);
if (sTitle != null && sTitle.length() > 0) {
currentUrlTitle = sTitle;
} else {
currentUrlTitle = "Web Page";
}
}
});
...
}
...
...
private void startWebView(WebView view, String url) {
// TODO Auto-generated method stub
view.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
// If you will not use this method url links are open in new brower
// not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != "outofapp") {
view.loadUrl(url);
currentUrl = url;
return true;
}
return false;
}
...
...
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bScript:
DatabaseOperations dop = new DatabaseOperations(ctx);
dop.addUrl(dop, currentUrl, currentUrlTitle);
Toast.makeText(ctx, "URL is successfully saved", 0).show();
break;
}
}
...
3. DatabaseOperations.java
package com.example.sidebarmenuwebview;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseOperations extends SQLiteOpenHelper {
private DatabaseOperations dop;
private SQLiteDatabase sql;
public static final int database_version = 1;
public String TABLE_QUERY = "CREATE TABLE urlhistory ( id INTEGER primary key AUTOINCREMENT, "
+ "url TEXT, title TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );";
public DatabaseOperations(Context context) {
//DB name
super(context, "url_info", null, database_version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// create new table
db.execSQL(TABLE_QUERY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void addUrl(DatabaseOperations dop, String url, String title) {
sql = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("url", url);
cv.put("title", title);
long k = sql.insert("urlhistory", null, cv);
}
}
No comments:
Post a Comment