[Android]对象无法转换为java.lang.String Asynctask

4

我遇到了这个错误。

java.lang.ClassCastException:java.lang.Object[]无法转换为 java.lang.String []

以下是完整代码。

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edTenDangNhap =(EditText) findViewById(R.id.edTenDangNhap);
    edMatKhau =(EditText) findViewById(R.id.edMatKhau);
    btnDangKi =(Button) findViewById(R.id.btnDangKi);
    btnDangNhap =(Button) findViewById(R.id.btnDangNhap);

    btnDangNhap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String tentk = edTenDangNhap.getText().toString();
            String matkhau = edMatKhau.getText().toString();

            // ==== I execute AsyncTask there
            AsyncTask dangnhap = new AsyncDangNhap();
            dangnhap.execute(tentk,matkhau); // IDE announce there : JDK 5.0 only.  Unchecked to call execute Params ...
        }
    });
}

public class AsyncDangNhap extends AsyncTask<String[], Void, Integer>{//error there
    @Override
    protected Integer doInBackground(String[]... params) {
        WebService sv = new WebService();
        int kiemtra = sv.KiemTraDangNhap(params[0],params[1]);
        return kiemtra;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(getApplicationContext(),"Dang xu li ... !",Toast.LENGTH_LONG).show();
    }
    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        if(result >0){
            //Dang nhap thanh cong
            Toast.makeText(getApplicationContext(),"Dang nhap thanh cong !",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getApplicationContext(),"Dang nhap that bai !",Toast.LENGTH_LONG).show();
        }
    }
}`
2个回答

1

AsyncTaskdoInBackground方法中将String[]更改为String,因为当前在dangnhap.execute方法中传递的是字符串而不是字符串数组,例如:

public class AsyncDangNhap extends AsyncTask<String, Void, Integer>{ 
    @Override
    protected Integer doInBackground(String... params) {
         .....
    }

  ....
}

谢谢,但我尝试使用String和String [],但仍然不起作用。有可能是JDK的问题吗?因为还有人在使用这段代码!? - Giang Strider

1
正如异常中所指出的,您试图将字符串传递给异步任务对象的超类async task execute方法,该方法接受一个varag(可变长度参数,基本上是一个数组)对象。
要解决此问题,只需替换该行代码即可。
AsyncTask dangnhap = new AsyncDangNhap();

AsyncDangNhap dangnhap = new AsyncDangNhap();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接