Android 将微调器值作为参数传递给异步任务
我是android新手。我需要将值作为参数从微调器传递到asynctask,到目前为止,我成功地在微调器中显示了结果。现在,我需要通过单击按钮将所选值从微调器传递到另一个活动(作为asynctask的参数)。下面是代码。提前感谢。Android 将微调器值作为参数传递给异步任务,android,android-asynctask,Android,Android Asynctask,我是android新手。我需要将值作为参数从微调器传递到asynctask,到目前为止,我成功地在微调器中显示了结果。现在,我需要通过单击按钮将所选值从微调器传递到另一个活动(作为asynctask的参数)。下面是代码。提前感谢。 BackgroundFetchWorker.java: public class BackgroundFetchWorker extends AsyncTask<String,Void,String> { String json_string; Progr
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);
}
公共类BackgroundFetchWorker扩展异步任务{
字符串json_字符串;
进行对话进行对话;
语境;
BackgroundFetchWorker(上下文ctx)
{
上下文=ctx;
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串类型2=参数[0];
字符串student\u fetch\u url=”http://pseudoattendance.pe.hu/studentFetch.php";
if(type2.equals(“fetchSubject”)){
试一试{
字符串学期=参数[1];
字符串流=参数[2];
URL URL=新URL(学生获取URL);
HttpURLConnection HttpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(“POST”);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoOutput(true);
OutputStream OutputStream=httpURLConnection.getOutputStream();
BufferedWriter BufferedWriter=新的BufferedWriter(新的OutputStreamWriter(outputStream,UTF-8));
字符串post_data=URLEncoder.encode(“学期”,“UTF-8”)+“=”+URLEncoder.encode(学期,“UTF-8”)
+URLEncoder.encode(“流”,“UTF-8”)+“=”+URLEncoder.encode(流,“UTF-8”);
bufferedWriter.write(post_数据);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream InputStream=httpURLConnection.getInputStream();
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(inputStream,“iso-8859-1”);
字符串结果=”;
字符串行=”;
而((line=bufferedReader.readLine())!=null){
结果+=行;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
返回结果;
}捕获(IOE异常){
e、 printStackTrace();
}
}
返回null;
}
@凌驾
受保护的void onPreExecute(){
progressDialog=新建progressDialog(上下文);
progressDialog.setTitle(“获取数据…”);
progressDialog.setMessage(“这可能需要一段时间…”);
progressDialog.show();
}
@凌驾
受保护的void onPostExecute(字符串结果){
progressDialog.disclose();
字符串s=result.trim();
如果(s.equals(“{\”结果\“:[]}”)){
Toast.makeText(上下文“出错”,Toast.LENGTH_SHORT).show();
}
否则{
json_string=结果;
意图i=新意图(上下文,TakeAttendanceActivity.class);
i、 putExtra(“studentdata”,json_字符串);
背景。起始触觉(i);
Toast.makeText(上下文,“Success”,Toast.LENGTH_SHORT).show();
}
}
@凌驾
受保护的void onProgressUpdate(void…值){
super.onProgressUpdate(值);
}
}
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) {}}
公共类FacultyWelcomeActivity扩展AppCompativeActivity实现Spinner.OnItemSelectedListener{
字符串JSON_字符串;
JSONObject JSONObject;
JSONArray JSONArray;
触点适配器触点适配器;
列表视图列表视图;
//宣布成为纺纱工
私人纺纱机;
私人纺纱机1;
//微调器项的ArrayList
私立ArrayList学生;
私有数组列表流;
//JSON数组
私人JSONArray结果;
私有JSONArray结果1;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u faculty\u welcome);
//初始化ArrayList
学生=新数组列表();
stream=newarraylist();
//初始化微调器
微调器=(微调器)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(新的AdapterView.OnItemSelectedListener(){
@凌驾
已选择公共视图(AdapterView父视图、视图视图、整型位置、长id){
字符串学期=parent.getItemAtPosition(position.toString();
String stream=parent.getItemAtPosition(position.toString();
}
@凌驾
未选择公共无效(AdapterView父级){
}
});
喷丝头1=(喷丝头)findViewById(R.id.spinner1);
//向微调器添加选定项侦听器
//由于我们已经将类Spinner.OnItemSelectedListener实现到这个类本身,我们将把它传递给setOnItemSelectedListener
getData();
getData1();
listView=(listView)findViewById(R.id.讲师列表);
contactAdapter=新的contactAdapter(this,R.layout.rowlayout);
setAdapter(contactAdapter);
JSON_STRING=getIntent().getExtras().getString(“JSON数据”);
试一试{
jsonObject=新的jsonObject(JSON_字符串);
jsonArray=jsonObject.getJSONArray(“结果”);
整数计数=0;
字符串sub1、sub2、sub3、sub4;
while(count background.execute("your string");
@Override
protected String doInBackground(String... params) {
String type2 = params[0]; // type2 == "your string"
...
}