onCreateView值为AsyncLogin

时间:2016-10-22 13:00:19

标签: android android-asynctask fragment

我是android的初学者,我想知道如何将数据从我的oncreateView传递到我的异步任务。例如,我在oncreate中有一个用户ID,如何将此用户ID称为我的asyntask?

这是我的代码。

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 //   myView = inflater.inflate(R.layout.currently_history_rvmainfragment,container, false);
     myView = inflater.inflate(R.layout.currently_history_rvmainfragment,container, false);
    Bundle bundle = this.getArguments();
    int myInt = bundle.getString("key","")

    //I HAVE A DATA HERE AND I WANT TO PASS IT TO MY ASYNC TASK

    new AsyncLogin().execute();
    return myView;
}

private class AsyncLogin extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(getActivity());
    HttpURLConnection conn;
    URL url = null;
    MaincommentShowmore maincommentShowmore= new MaincommentShowmore();

        // I WANT TO PASS IT HERED SO THAT I MAY CALL IT TO MY URL

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();
    }

    @Override //SO THAT I MAY ADD INT VALUES IN THIS URL
    protected String doInBackground(String... params) {
        try {
            // Enter URL address where your json file resides
            // Even you can make call to php file which returns json data
            url = new URL("http://192.168.1.6/jmiappphp/showRateCommentShowMore.php");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");

            // setDoOutput to true as we recieve data from json file
            conn.setDoOutput(true);

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

2 个答案:

答案 0 :(得分:1)

on onCreateview

new AsyncLogin(yourId).execute();

在AsyncTask中创建一个构造函数:

int id;

public AsyncLogin(int id) {
    super();
    this.id = id;
}

答案 1 :(得分:1)

您可以将params传递给execute方法,如下所示,

String data1 = "your_data1";
String data2 = "your_data2";

new AsyncLogin().execute(data1, data2);

内部doInBackground将其检索为

@Override
protected String doInBackground(String... params) {
    String data1 = params[0];
    String data2 = params[1];
}