使用fragement和asynctask时出错
我试图从托管的MySQL中获取数据列表,然后以列表视图返回结果。 但是在使用碎片时我无法做到。
我收到以下错误:
com.example.test.myapp E / AndroidRuntime:致命异常:AsyncTask#1进程:com.exampletest.myapp,PID:31491 java.lang.RuntimeException:在android.os.AsyncTask $ 3执行doInBackground()时发生错误。 java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)在java.util.concurrent.FutureTask.setException(FutureTask.java:222)在java.util.concurrent.FutureTask完成(AsyncTask.java:300) .run(FutureTask.java:242)at android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)at java.util.concurrent .ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)at java.lang.Thread.run(Thread.java:818)引发:java.lang.ArrayIndexOutOfBoundsException:length = 1; 索引= 1 com.example.test.myapp.homeOperation.doInBackground(homeOperation.java:71)在com.example.test.myapp.homeOperation.doInBackground(homeOperation.java:23)在android.os.AsyncTask $ 2.call (AsyncTask.java:288)at java.util.concurrent.FutureTask.run(FutureTask.java:237)at android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)at java.util.concurrent.ThreadPoolExecutor .runWorker(ThreadPoolExecutor.java:1112)at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)at java.lang.Thread.run(Thread.java:818)
使用下面显示的类:我连接到服务器,然后获取结果,以便我可以解析数据并将其放入ArrayLists中。
public class homeOperation extends AsyncTask<String, Void, String> {
List<String> title_list = new ArrayList<String>();
List<String> id_list = new ArrayList<String>();
Context context;
AlertDialog alertDialog;
homeOperation(Context ctx) {
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://xxxx/data.php";
if (type.equals("home")) {
try {
String events = params[1];
String task_owner = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("events", "UTF-8") + "=" + URLEncoder.encode(events, "UTF-8") + "&"
+ URLEncoder.encode("task_owner", "UTF-8") + "=" + URLEncoder.encode(task_owner, "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();
String[] arr = result.split("--");
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String result) {
Toast toast = Toast.makeText(this.context, result, Toast.LENGTH_LONG);
toast.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
现在,这是我试图从homeOperation类获取数据然后将数据放入ListView的类。
public class ContentFragment extends Fragment {
ListView lv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_fragment, container, false);
lv = (ListView) view.findViewById(R.id.resultList);
String type = "home";
homeOperation homeOperation = new homeOperation(ContentFragment.this.getActivity());
homeOperation.execute(type, "", "");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ContentFragment.this.getActivity(), android.R.layout.simple_list_item_1, homeOperation.title_list);
lv.setAdapter(arrayAdapter);
//addButton onClick
ImageButton addButton = (ImageButton) view.findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addPaige(view);
}
});
return view;
}
public void addPaige(View v) {
Intent goToAddPaige = new Intent(getActivity(), AddPaige.class);
startActivity(goToAddPaige);
}
}
我认为使用片段发送上下文时存在问题。
title_list
将没有数据,因为您的AsyncTask.execute()
将在lv.setAdapter(arrayAdapter);
之后完成lv.setAdapter(arrayAdapter);
。
所以如果你想用足够的数据处理title_list
,可以使用onPostExecute()
android.os.Handler
来发送AsyncTask的结果。
尝试如下:
你的AsyncTask
public class homeOperation extends AsyncTask<String,Void,String> {
List<String> title_list = new ArrayList<String>();
List<String> id_list = new ArrayList<String>();
Context context;
Handler handler;
AlertDialog alertDialog;
homeOperation(Context ctx, Handler hnd) {
context = ctx;
handler = hnd;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://xxxx/data.php";
if (type.equals("home")) {
try {
String events = params[1];
String task_owner = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("events", "UTF-8") + "=" + URLEncoder.encode(events, "UTF-8") + "&"
+ URLEncoder.encode("task_owner", "UTF-8") + "=" + URLEncoder.encode(task_owner, "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();
String[] arr = result.split("--");
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String result) {
Toast toast = Toast.makeText(this.context, result, Toast.LENGTH_LONG);
toast.show();
handler.sendEmptyMessage(0);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
你的片段
public class ContentFragment extends Fragment {
ListView lv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_fragment,container,false);
lv = (ListView) view.findViewById(R.id.resultList);
ViewHandler viewHnd = new ViewHandler(ContentFragment.this); // add this handler for parameter of yout AsyncTask.
String type = "home";
homeOperation homeOperation = new homeOperation(ContentFragment.this.getActivity(), viewHnd);
homeOperation.execute(type, "", "");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ContentFragment.this.getActivity() , android.R.layout.simple_list_item_1, homeOperation.title_list);
//
// lv.setAdapter(arrayAdapter);
//addButton onClick
ImageButton addButton = (ImageButton) view.findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addPaige(view);
}
});
return view;
}
public void addPaige(View v){
Intent goToAddPaige = new Intent(getActivity(), AddPaige.class);
startActivity(goToAddPaige);
}
private static class ViewHandler extends Handler {
private final WeakReference<ContentFragment> mFragment;
ViewHandler(ContentFragment fragment) {
mFragment = new WeakReference<ContentFragment>(fragment);
}
@Override
public void handleMessage(Message msg) {
ContentFragment fragment = mFragment.get();
if (fragment != null) {
fragment.handleMessage(msg);
}
}
}
private void handleMessage(Message msg) {
if (msg.what == 0) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ContentFragment.this.getActivity() , android.R.layout.simple_list_item_1, homeOperation.title_list);
lv.setAdapter(arrayAdapter);
}
}
}
更换:
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
有:
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
String[] temp = cur.split(":");
if (temp.length == 2){
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
}
堆栈跟踪本身非常清晰:
java.lang.Thread.run(Thread.java:818) Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 at
这应该转化为这一行:
id_list.add(cur.split(":")[1]);
你不应该指望split方法总会给你一定数量的子串。 所以你不得不编写一个后备时间。
链接地址: http://www.djcxy.com/p/78413.html