0
アンドロイドスタジオでwebviewを作成し、アンドロイドポストリクエストレスポンスをwebiviewのtextareaに配置したいと考えています。投稿のリクエストが正常に動作していて、サーバーからデータを受信しましたが、webview内のJavascript関数が呼び出されてテキストエリアに入力されることはありません。エキスパートが私のコードを見て、それを修正する方法を教えてもらえますか。事前に感謝します。javascript関数にAndroidの投稿要求の応答を渡すには?
WebViewの内部public class MainActivity extends AppCompatActivity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView= (WebView) findViewById(R.id.activity_main_webview);
mWebView.loadUrl("file:///android_asset/index.html");
mWebView.getSettings().setJavaScriptEnabled(true);
// Force links to open in the WebViewinstead of in a browser
mWebView.setWebViewClient(new WebViewClient());
}
@Override
protected void onResume()
{
super.onResume();
new PostClass().execute();
}
private class PostClass extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
final TextView outputView = (TextView) findViewById(R.id.postOutput);
try {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://myownapi.com/api").openConnection();
myURLConnection.setReadTimeout(60000);
myURLConnection.setConnectTimeout(60000);
myURLConnection.setRequestMethod("POST");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setRequestProperty("API_KEY", "12345_ABC_MNO_12345678_123ABC");
myURLConnection.setRequestProperty("Connection", "Keep-Alive");
myURLConnection.addRequestProperty("Content-length", "");
OutputStream os = myURLConnection.getOutputStream();
os.close();
myURLConnection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
System.out.println(sb);
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
outputView.setText(sb.toString());
//outputView.setText("finished");
mWebView.loadUrl("javascript:MyFunction(" + sb.toString() + ")");
//mWebView.loadUrl("javascript:MyFunction()");
} catch (Exception e) {
}
return null;
}
}
}
htmlコード:
<html>
<head>
<script>
function MyFunction(myVar)
{
//var myVar = 'test data';
var myTextArea = document.getElementById('myArea');
myTextArea.innerHTML += myVar;
};
</script>
</head>
<body>
<br>
<br>
<textarea id="myArea" rows="30" cols="40"></textarea>
</body>
が
返信ありがとうございます。私はそれを試みましたが、テキストエリアには何も配置されていません。私もmWebView.loadUrl( "javascript:MyFunction()"を試しました。 myVar = JavaScriptのデフォルト値で、テキストエリアには何も置かれません! onCreate内にwebviewを配置することが問題だと思いますか? – user1788736