Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: load sqlite database content to webview

I have an sqlite database in which I have a content I want to load in webview ,, as I want to select from database and show in web view,, Is there any way to do so ?

public class TataworatYawmeeh extends Activity {
    WebView webView;
    String javascrips;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.tataworat);

        webView = (WebView) findViewById(R.id.tatworatWebView);
        webView.setBackgroundColor(0x00000000);

        try {       
            DataBaseHelper myDbHelper = new DataBaseHelper(this);

            myDbHelper = new DataBaseHelper(this);

            try {
                myDbHelper.createDataBase();

                String selectQuery = "SELECT  * FROM 'nnn'";
                SQLiteDatabase db = myDbHelper.getReadableDatabase();
                db.execSQL(selectQuery);
            } catch (IOException ioe) {      
                throw new Error("Unable to create database");
            }

            try {
                myDbHelper.openDataBase();

            } catch (SQLException sqle) {
                throw sqle;
            }
        }   
    }
}
like image 634
Android Developer Avatar asked Dec 05 '12 06:12

Android Developer


1 Answers

You have to use a Java Class as interface:

DataLoader dl = new DataLoader();

// For passing the data
webView.addJavascriptInterface(dl, "accessor");
webView.loadUrl("file:///android_asset/yourpage.html");

In your activity you can declare the anonymous class DataLoader, with a get method where you retrieve data and return it using JSON like this:

class ChartDataLoader {
    public String getData() {
        String selectQuery = "SELECT  * FROM 'nnn'";
        SQLiteDatabase db = myDbHelper.getReadableDatabase();
        result = db.execSQL(selectQuery);

        Gson gson = new Gson();
        data = gson.toJson(result, resultype.class);

        return data;
    }
}

And finally, you can use this data in your html, using javascript:

<script id="source" language="javascript" type="text/javascript">
     var obj = window.accessor;
     var data = JSON.parse(obj.getBalances());
     /* Loop */
</script>
like image 183
frayab Avatar answered Sep 28 '22 01:09

frayab