将微调器值作为参数传递给异步任务

时间:2017-04-02 06:42:48

标签: android android-asynctask

我是android新手。我需要将值从微调器传递给asynctask作为参数,直到现在我成功地在微调器中成功显示结果。现在我需要将微调器中的选定值传递给按钮单击时的另一个活动(作为asynctask的参数)。下面是代码。提前谢谢。
BackgroundFetchWorker.java:

public class BackgroundFetchWorker extends AsyncTask<String,Void,String> {
String json_string;
ProgressDialog progressDialog;
Context context;

BackgroundFetchWorker(Context ctx)
{
    context = ctx;
}

@Override
protected String doInBackground(String... params) {
    String type2 = params[0];
    String student_fetch_url = "http://pseudoattendance.pe.hu/studentFetch.php";
    if (type2.equals("fetchSubject")) {
        try {
            String semester = params[1];
            String stream = params[2];

            URL url = new URL(student_fetch_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("semester", "UTF-8") + "=" + URLEncoder.encode(semester, "UTF-8")
                    + URLEncoder.encode("stream","UTF-8")+"="+URLEncoder.encode(stream,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = " ";
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return null;
}
@Override
protected void onPreExecute() {

    progressDialog = new ProgressDialog(context);
    progressDialog.setTitle("Fetching Data....");
    progressDialog.setMessage("This may take a while..");
    progressDialog.show();
}

@Override
protected void onPostExecute(String result) {

    progressDialog.dismiss();
    String s = result.trim();
    if(s.equals("{\"result\":[]}")){
        Toast.makeText(context, "ERROR OCCURED", Toast.LENGTH_SHORT).show();
    }
    else {
        json_string = result;
        Intent i = new Intent(context, TakeAttendanceActivity.class);
        i.putExtra("studentdata", json_string);
        context.startActivity(i);
        Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
    }

}
@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

}

FacultyWelcomeActivity.java:

public class FacultyWelcomeActivity extends AppCompatActivity  implements Spinner.OnItemSelectedListener{
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;


//Declaring an Spinner
private Spinner spinner;
private Spinner spinner1;

//An ArrayList for Spinner Items
private ArrayList<String> students;
private ArrayList<String> stream;

//JSON Array
private JSONArray result;
private JSONArray result1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_faculty_welcome);
    //Initializing the ArrayList
    students = new ArrayList<String>();
    stream = new ArrayList<String>();
    //Initializing Spinner
    spinner = (Spinner) findViewById(R.id.spinner);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String semesters= parent.getItemAtPosition(position).toString();

            String stream= parent.getItemAtPosition(position).toString();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
    spinner1 = (Spinner) findViewById(R.id.spinner1);

    //Adding an Item Selected Listener to our Spinner
    //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener

    getData();
    getData1();


    listView = (ListView) findViewById(R.id.lectureList);

    contactAdapter = new ContactAdapter(this, R.layout.rowlayout);
    listView.setAdapter(contactAdapter);
    JSON_STRING = getIntent().getExtras().getString("JSON Data");

    try {
        jsonObject = new JSONObject(JSON_STRING);
        jsonArray = jsonObject.getJSONArray("result");
        int count = 0;
        String sub1, sub2, sub3, sub4;
        while (count < jsonArray.length()) {
            JSONObject JO = jsonArray.getJSONObject(count);

            sub1 = JO.getString("fname");
            sub2 = JO.getString("lname");
            sub3 = JO.getString("id");
            sub4 = JO.getString("email");

            Contacts contacts = new Contacts(sub1, sub2, sub3, sub4);
            contactAdapter.add(contacts);
            count++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
    public void fetchSubject(View view) {
        String type2 = "fetchSubject";
        String spinnerdata = spinner.getSelectedItem().toString();
        String spinner1data = spinner1.getSelectedItem().toString();
        BackgroundFetchWorker background = new BackgroundFetchWorker(this);
        background.execute(type2,spinnerdata,spinner1data);
    }

private void getData1(){

    StringRequest stringRequest = new StringRequest(Config2.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result1 = j.getJSONArray(Config2.JSON_ARRAY);
                        getStudents1(result1);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
}

private void getData(){

    StringRequest stringRequest = new StringRequest(Config.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);
                        result = j.getJSONArray(Config.JSON_ARRAY);
                        getStudents(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
}

private void getStudents(JSONArray j){

    for(int i=0;i<j.length();i++){
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);


            students.add(json.getString(Config.TAG_SEMESTER));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    spinner.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}

private void getStudents1(JSONArray j){
    //Traversing through all the items in the json array
    for(int i=0;i<j.length();i++){
        try {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            stream.add(json.getString(Config2.TAG_STREAM));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    spinner1.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, stream));
}


@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    //check which spinner triggered the listener
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}}

1 个答案:

答案 0 :(得分:1)

您正以这种方式将参数传递给doInBackground()

 background.execute("your string");

现在字符串"your string"将成为doInBackground()回调中的参数:

@Override
protected String doInBackground(String... params) {
    String type2 = params[0]; // type2 == "your string"
    ...
}

有关详细信息,请参阅docs