繁体   English   中英

Android-使用碎片和asynctask时出错

[英]Android - Error when using fragement and asynctask

我正在尝试从托管的MySQL获取数据列表,然后在listview中返回结果。 但是使用片段时我无法做到。

我收到以下错误:

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)完成(AsyncTask.java:300)在java.util.concurrent.FutureTask .run(FutureTask.java:242)在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:231)在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)在java.util.concurrent .ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:587)at java.lang.Thread.run(Thread.java:818)由以下原因引起:java.lang.ArrayIndexOutOfBoundsException:length = 1; index = 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方法总是会给您一定数量的子字符串。 因此,您必须为没有的时机编写备用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM