如何使用EditText在doInbackGround(AsyncTask)中获取参数?

时间:2016-12-23 15:50:18

标签: android android-asynctask

我想在我的网址中使用3个编辑文本来获取(id,name,family)。我已经制作了Rest Web服务,现在我想在我的Android应用程序中使用套接字。下面是我的代码,它不断收到错误。我错过了什么?

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    public void ok (View view){
        Havij havij = new Havij();
        havij.execute();
    }
    public class Havij extends AsyncTask{
        String name="";
        @Override
        protected Object doInBackground(Object[] objects)  {

            String str1 = (String) objects[0];
            String str2 = (String) objects[1];
            String str3 = (String) objects[2];
            try {
                URL url =new URL("http://192.168.1.100:8083/rest/pm/rp?id=&name=&family="+str1+str2+str3);
                URLConnection urlConnection = url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                int ascii = inputStream.read();
                String json = "";
                while (ascii !=-1){
                    json += (char) ascii;
                    ascii = inputStream.read();
                }
                inputStream.close();
                JSONArray jsonArray = (JSONArray) new JSONParser().parse(json);
                for (Object o : jsonArray) {
                    JSONObject jsonObject = (JSONObject) o;
                    name =name+jsonObject.get("name")+ " ";
                }
            }
            catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return name;
        }

        @Override
        protected void onPostExecute(Object o) {
            EditText editText1 = (EditText) findViewById(R.id.editText1);
            EditText editText2 = (EditText) findViewById(R.id.editText2);
            EditText editText3 = (EditText) findViewById(R.id.editText3);
            execute(editText1.getText().toString(),editText2.getText().toString(),editText3.getText().toString());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

public void ok (View view){
     EditText editText1 = (EditText) findViewById(R.id.editText1);
     EditText editText2 = (EditText) findViewById(R.id.editText2);
     EditText editText3 = (EditText) findViewById(R.id.editText3);
     Havij havij = new Havij();
     havij.execute(editText1.getText().toString(),editText2.getText().toString(),editText3.getText().toString());
}

您需要在开始时调用execute时发送strings。 在您postExecute中提出的问题中。 在后台任务完成后,该方法称为。 有关AsyncTask

的信息,请查看here

你的网址应该是

http://192.168.1.100:8083/rest/pm/rp?id="+str1+"&name="+str2+"&family="+str3