0

我正在尝试将我的代码转换为使用片段。我对 Android 还是很陌生,我最初是通过制作很多类开始的,只是使用意图从一个 Activity 更改为另一个 Activity。我正在学习我的一个类,该类从服务器读取 JSON 数组并将表显示为列表并尝试将其转换为片段。为此,我遵循了此处提供的教程:

https://www.youtube.com/watch?v=TGXenxtDEGQ

它说我应该将我的 onCreate 更改为 onStart 并包含我已经完成的 onCreateView。我还将“ClassName.this”更改为它出现的“getActivity()”。该代码在尝试将其转换为片段之前运行良好,但现在我正在尝试使用片段时遇到问题。我认为这与 AsyncTask 有关。

在下面的代码块中,jParser 是我创建的 JSONParser 类的一个实例,它处理解析 JSON 数据。我还检查以确保我传递给该方法的 URL 返回有效的 JSON 以进行解析。这个类和我上面调用的方法作为一项活动工作得很好;当我在片段中操作时,我不能简单地做同样的事情吗?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.read_options, container, false);
    return view;
}
@Override
public void onStart() {
    super.onStart();
    // TODO Auto-generated method stub
    optionsList = new ArrayList<HashMap<String, String>>();
    new LoadOptions().execute();
    ListView lv = getListView();
    ...
    (Code to launch new activity when an item in list is pressed)
    ...
}


class LoadOptions extends AsyncTask<String, String, String>{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading options.  Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... args){
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(url_options, "GET", params);
        Log.d("All Options: ", json.toString());

        try{
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1){
                // Options Found, Iterate Through
                options = json.getJSONArray(TAG_OPTIONS);
                for(int i = 0; i < options.length(); i++){
                    JSONObject c = options.getJSONObject(i);
                    String id = c.getString(TAG_OPTIONID);
                    String duration = c.getString(TAG_DURATION);
                    String reward = c.getString(TAG_REWARD);

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_OPTIONID,  id);
                    map.put(TAG_DURATION, duration);
                    map.put(TAG_REWARD, reward);

                    optionsList.add(map);
                }
            } else {
                // Options are not available or server is down.
                // Dismiss the loading dialog and display an alert onPostExecute
                pDialog.dismiss();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url){
        pDialog.dismiss();
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                ListAdapter adapter = new SimpleAdapter(
                        getActivity(), optionsList, R.layout.list_options, new String[] 
                                {TAG_OPTIONID, TAG_DURATION, TAG_REWARD},
                                new int[] {R.id.tvOption, R.id.tvDuration, R.id.tvReward});
                setListAdapter(adapter);

                // Check for whether or not there are options available and display alert
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                JSONObject json = jParser.makeHttpRequest(url_options, "GET", params);
                int success = 0;
                try {
                    success = json.getInt(TAG_SUCCESS);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (success == 0){
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
                alertDialog.setTitle("No Options Available!");
                alertDialog.setMessage("No options currently available.  You will receive a " + 
                "notification when there are options available.  Click 'Okay' to return to main screen");
                alertDialog.setCancelable(false);
                alertDialog.setPositiveButton("Okay", new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int id){
                        Intent i = new Intent(getActivity().getApplicationContext(), MainActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                });
                alertDialog.show(); 
                }

            }
        });
    }

错误日志如下:

03-03 23:30:50.812: W/System.err(28019): java.net.SocketException: Permission denied
03-03 23:30:50.863: W/System.err(28019):    at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
03-03 23:30:50.863: W/System.err(28019):    at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)
03-03 23:30:50.863: W/System.err(28019):    at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)
03-03 23:30:50.863: W/System.err(28019):    at java.net.Socket.checkOpenAndCreate(Socket.java:821)
03-03 23:30:50.863: W/System.err(28019):    at java.net.Socket.connect(Socket.java:967)
03-03 23:30:50.863: W/System.err(28019):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-03 23:30:50.863: W/System.err(28019):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:156)
03-03 23:30:50.863: W/System.err(28019):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-03 23:30:50.867: W/System.err(28019):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-03 23:30:50.867: W/System.err(28019):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
03-03 23:30:50.867: W/System.err(28019):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-03 23:30:50.867: W/System.err(28019):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-03 23:30:50.867: W/System.err(28019):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-03 23:30:50.867: W/System.err(28019):    at com.example.abtest.JSONParser.makeHttpRequest(JSONParser.java:62)
03-03 23:30:50.867: W/System.err(28019):    at com.example.abtest.ReadOptionsFragment$LoadOptions.doInBackground(ReadOptionsFragment.java:111)
03-03 23:30:50.867: W/System.err(28019):    at com.example.abtest.ReadOptionsFragment$LoadOptions.doInBackground(ReadOptionsFragment.java:1)
03-03 23:30:50.867: W/System.err(28019):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-03 23:30:50.867: W/System.err(28019):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
03-03 23:30:50.867: W/System.err(28019):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
03-03 23:30:50.871: W/System.err(28019):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-03 23:30:50.871: W/System.err(28019):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-03 23:30:50.871: W/System.err(28019):    at java.lang.Thread.run(Thread.java:1019)
03-03 23:30:50.871: E/Buffer Error(28019): Error converting result java.lang.NullPointerException
03-03 23:30:50.871: E/JSON Parser(28019): Error parsing data org.json.JSONException: End of input at character 0 of 
03-03 23:30:50.882: W/dalvikvm(28019): threadid=10: thread exiting with uncaught exception (group=0x4001e578)
03-03 23:30:50.882: E/AndroidRuntime(28019): FATAL EXCEPTION: AsyncTask #1
03-03 23:30:50.882: E/AndroidRuntime(28019): java.lang.RuntimeException: An error occured while executing doInBackground()
03-03 23:30:50.882: E/AndroidRuntime(28019):    at android.os.AsyncTask$3.done(AsyncTask.java:200)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.lang.Thread.run(Thread.java:1019)
03-03 23:30:50.882: E/AndroidRuntime(28019): Caused by: java.lang.NullPointerException
03-03 23:30:50.882: E/AndroidRuntime(28019):    at com.example.abtest.ReadOptionsFragment$LoadOptions.doInBackground(ReadOptionsFragment.java:112)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at com.example.abtest.ReadOptionsFragment$LoadOptions.doInBackground(ReadOptionsFragment.java:1)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-03 23:30:50.882: E/AndroidRuntime(28019):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
03-03 23:30:50.882: E/AndroidRuntime(28019):    ... 4 more
03-03 23:30:56.742: E/WindowManager(28019): Activity com.example.abtest.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4055c690 that was originally added here
03-03 23:30:56.742: E/WindowManager(28019): android.view.WindowLeaked: Activity com.example.abtest.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4055c690 that was originally added here
03-03 23:30:56.742: E/WindowManager(28019):     at android.view.ViewRoot.<init>(ViewRoot.java:263)
03-03 23:30:56.742: E/WindowManager(28019):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:171)
03-03 23:30:56.742: E/WindowManager(28019):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:114)
03-03 23:30:56.742: E/WindowManager(28019):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
03-03 23:30:56.742: E/WindowManager(28019):     at android.app.Dialog.show(Dialog.java:242)
03-03 23:30:56.742: E/WindowManager(28019):     at com.example.abtest.ReadOptionsFragment$LoadOptions.onPreExecute(ReadOptionsFragment.java:104)
03-03 23:30:56.742: E/WindowManager(28019):     at android.os.AsyncTask.execute(AsyncTask.java:391)
03-03 23:30:56.742: E/WindowManager(28019):     at com.example.abtest.ReadOptionsFragment.onStart(ReadOptionsFragment.java:62)
03-03 23:30:56.742: E/WindowManager(28019):     at android.support.v4.app.Fragment.performStart(Fragment.java:1332)
03-03 23:30:56.742: E/WindowManager(28019):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:906)
03-03 23:30:56.742: E/WindowManager(28019):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
03-03 23:30:56.742: E/WindowManager(28019):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
03-03 23:30:56.742: E/WindowManager(28019):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
03-03 23:30:56.742: E/WindowManager(28019):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:420)
03-03 23:30:56.742: E/WindowManager(28019):     at android.os.Handler.handleCallback(Handler.java:587)
03-03 23:30:56.742: E/WindowManager(28019):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 23:30:56.742: E/WindowManager(28019):     at android.os.Looper.loop(Looper.java:130)
03-03 23:30:56.742: E/WindowManager(28019):     at android.app.ActivityThread.main(ActivityThread.java:3687)
03-03 23:30:56.742: E/WindowManager(28019):     at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:30:56.742: E/WindowManager(28019):     at java.lang.reflect.Method.invoke(Method.java:507)
03-03 23:30:56.742: E/WindowManager(28019):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
03-03 23:30:56.742: E/WindowManager(28019):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-03 23:30:56.742: E/WindowManager(28019):     at dalvik.system.NativeStart.main(Native Method)

谢谢 - 非常感谢任何朝着正确方向的帮助或轻推!

4

1 回答 1

1

添加此权限 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 <uses-permission android:name="android.permission.INTERNET"/>

在你的清单中

于 2013-03-04T07:54:51.330 回答