我想将数据发送到javascript以显示在我的html页面中。
这是我创建json的java代码,但我不知道如何将我的字符串变量转换为json对象以及如何将其转换为javascript:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myBrowser = (WebView)findViewById(R.id.mybrowser);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.setWebChromeClient(new WebChromeClient());
myBrowser.loadUrl("file:///android_asset/index.html");
final SQLiteDatabase mydatabase1 = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
String tmp = "";
String JsonTxt = "";
Cursor c = mydatabase1.rawQuery("SELECT * FROM Details ", null);
if(c.moveToFirst()){
do{
String id = c.getString(0);
String app = c.getString(1);
String txt = c.getString(2);
String text_time = c.getString(3);
tmp += "{\"ID\":"+id+",\"App\":\""+app+"\",\"Content\":\""+txt+"\",\"Date\":\""+text_time+"\"},";
}while(c.moveToNext());
}
JsonTxt = "["+tmp+"]";
myBrowser.loadUrl("javascript:AlertContent("+JsonTxt+")");
c.close();
mydatabase1.close();}
JavaScript:
function AlertContent(msg){alert(msg);}
答案 0 :(得分:0)
关于如何正确地将Java对象转换为JSON,请参阅:Convert object to JSON in Android。
要将此对象传递给JavaScript,您可以使用WebView.evaluateJavascript
方法,请参阅How does evaluateJavascript work?;或WebView.loadUrl
使用javascript:
计划,请参阅this。