调用javascript函数时未定义

时间:2012-08-03 06:10:21

标签: javascript android html android-webview

我能够将数据从我的android传递给javascript。但问题是当我调用函数setValue()时它变为Undefined但是当它在加载时它传递了正确的值。以下是我的代码。

这是我的Java类代码

public class PaymentActivity extends Activity {

String amount1;


    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment);

         Bundle extras = getIntent().getExtras(); 
            if(extras !=null)
            {
                amount1 = extras.getString("amount1");

            }

        WebView web = (WebView) findViewById(R.id.web1);
        web.getSettings().setJavaScriptEnabled(true);
        web.loadUrl("javascript:window.onload = function(){setValue(\""+ amount1 +"\");};");
        web.loadUrl("file:///android_asset/www/index.html");


    }

}

这是我的网页代码

<!DOCTYPE html>
<html>
<head>
</head>
<body>

    Whats your Name?
    <input id="name" value="" />
    <input id="pass" value="" />
    <button onclick = "setValue()">Submit</button>

<script type="text/javascript"> 
    function setValue(amount1){
    myValue = amount1;
    document.getElementById("pass").value = myValue;

    }
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您无法直接从加载活动中调用java脚本函数。您需要使用处理程序和线程以及隐藏按钮

public class AskUsActivity extends Activity{
private Button scriptButton;
private WebView webView;
private Handler handler;;

MyJavaScriptInterface myJavaScriptInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ask_us);

    webView = (WebView)findViewById(R.id.askUs_webView);
    scriptButton=(Button)findViewById(R.id.scriptButton);

    loadData();

    myJavaScriptInterface = new MyJavaScriptInterface(this);

    webView.loadUrl("file:///android_asset/AskUs.htm");

    webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");

    webView.getSettings().setJavaScriptEnabled(true);

    webView.setWebChromeClient(new WebChromeClient());

    handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            System.out.println("inside handler");
            scriptButton.performClick();
        }
    };

    scriptButton.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {
            webView.loadUrl("javascript:setcontactInfo('1|*|nikhil|||');");
        }
    });

    //      String selectedImagePath="1|*|nikhil|||";

    //      webView.loadUrl("javascript:setInternational()");

    //      new Thread(){
    //          @Override
    //          public void run() {
    //              System.out.println("inside thread.................Start.......");
    //              webView.loadUrl("javascript:setcontactInfo('1|*|nikhil|||');");
    //              System.out.println("inside thread.................end.......");
    //          }
    //      }.start();

}

@Override
protected void onResume() {
    super.onResume();
    try {
        Thread.sleep(400);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    new Thread(){
        public void run() {
            System.out.println("inside thread................");
            handler.sendEmptyMessage(0);
        };
    }.start();
}


private void loadData(){
    try {

        String destPath = "/data/data/" + getPackageName()+ "/databases/kellypipe.sqlite";

        File f = new File(destPath);
        if(!f.exists()){
            Log.v("<<< TAG >>>","File Not Exist");
            InputStream in = getAssets().open("kellypipe.sqlite");
            OutputStream out = new FileOutputStream(destPath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.v("<<< TAG >>>","ioexeption");
        e.printStackTrace();
    }

    DBManager dbManager =  new DBManager(this);
    Log.v("<<< TAG >>>","Database is there with version: "+dbManager.getReadableDatabase().getVersion());
    //      String sql = "select * from CasingMetric";

    String sql= "SELECT ID,listname,name,address,contact,email from contactInfo order by ID";


    SQLiteDatabase db = dbManager.getReadableDatabase();
    Cursor cursor = db.rawQuery(sql, null);
    Log.v("<<< TAG >>>","Query Result:"+cursor);
    cursor.moveToFirst();
    int i=cursor.getColumnIndex("listname");
    int j=cursor.getColumnIndex("name");

    int x=0;
    while(!cursor.isAfterLast()){
        x++;
        System.out.println("Listname : "+cursor.getString(i)+ "  Name: "+cursor.getString(j)+" :: X is : "+x);
        cursor.moveToNext();
    }

    cursor.close();
    db.close();
    dbManager.close();
}

public class MyJavaScriptInterface {
    Context mContext;

    MyJavaScriptInterface(Context c) {
        mContext = c;
    }

    public void showToast(String toast){
        //Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        webView.loadUrl("javascript:callFromActivity()");
    }

    public void openAndroidDialog(){
        AlertDialog.Builder myDialog = new AlertDialog.Builder(AskUsActivity.this);
        myDialog.setTitle("DANGER!");
        myDialog.setMessage("You can do what you want!");
        myDialog.setPositiveButton("ON", null);
        myDialog.show();
    }
}

}