从URL解析json时的超时消息

时间:2014-09-15 07:40:42

标签: android

我要做的是:我正在尝试解析网址http://api.androidhive.info/contacts/中的值,并在点击按钮时显示textview中的值

发生了什么:我无法在片段中显示结果,但我可以看到正确解析了该值的日志。

我该如何解决这个问题! !


apache_http_connection.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/apacheBtnId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ParseData" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center" >

        <TextView
            android:id="@+id/apacheTxtId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="MyText"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="@android:color/white" />
    </LinearLayout>

</LinearLayout>

ApacheHttpConnection.java

public class ApacheHttpConnection extends Fragment {


    // JSON Node names 
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";

    String name;

    private String errMsg="";
    private static boolean isErr=false;
    String url="http://api.androidhive.info/contacts/";
    private TextView apacheTxtId;
    private Button apacheBtnId;

    //Creating a new instance
    public static ApacheHttpConnection newInstance(){
        ApacheHttpConnection fragment=new ApacheHttpConnection();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.apache_http_connection, container, false);

        apacheTxtId=(TextView) view.findViewById(R.id.apacheTxtId);
        apacheBtnId=(Button) view.findViewById(R.id.apacheBtnId);

        return view;
    }


    @Override
    public void onStart() {
        super.onStart();

        apacheBtnId.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new LongOperation().execute("");
            }
        });
    }


    private class LongOperation extends AsyncTask<String, Integer, String> {

        String webData;
        JSONArray contacts = null;



        @Override 
        protected String doInBackground(String... params) {

            try {
                webData=doConnection(url);
                if (webData != null) { 
                    // Getting JSON Object node 
                    JSONObject jsonObj = new JSONObject(webData);
                    // Getting JSON Array node 
                    contacts = jsonObj.getJSONArray(TAG_CONTACTS); 
                    // Getting data from Object node
                    JSONObject c = contacts.getJSONObject(1); 
                    name = c.getString(TAG_NAME); 
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                publishProgress(1);
            } catch (IOException e) {
                e.printStackTrace();
                publishProgress(2);
            } catch (JSONException e) {
                e.printStackTrace();
                publishProgress(3);
            } catch (Exception e) {
                e.printStackTrace();
                publishProgress(4);
            }
            return null; 
        } 

        @Override 
        protected void onPostExecute(String result) {

        } 

        @Override 
        protected void onPreExecute() {} 

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

            if(values[0]==1){
                if(isErr==true){
                    DlgUniversalError.showQuitAlert(getActivity(),errMsg);
                }
            }
            else if(values[0]==2){
                if(isErr==true){
                    DlgUniversalError.showQuitAlert(getActivity(),errMsg);
                }
            }
            else if(values[0]==3){
                if(isErr==true){
                    DlgUniversalError.showQuitAlert(getActivity(),errMsg);
                }
            }
            else if(values[0]==4){
                if(isErr==true){
                    DlgUniversalError.showQuitAlert(getActivity(),errMsg);
                }
            }   
        }
    } 



    public String doConnection(String url) throws ClientProtocolException,IOException,Exception{

        HttpGet httpget=null;
        String mContent=null;
        HttpClient Client=null;

        try {
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 500);

            Client = new DefaultHttpClient(params);
            httpget = new HttpGet(url);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            mContent = Client.execute(httpget, responseHandler);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            if(isErr==false){
                errMsg=e.getLocalizedMessage();
                isErr=true;
            }
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            if(isErr==false){
                errMsg=e.getLocalizedMessage();
                isErr=true;
            }
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            if(isErr==false){
                errMsg=e.getLocalizedMessage();
                isErr=true;
            }
            throw e;
        }   
        return mContent;
    }

}

登录 ::

09-15 12:59:25.609: D/<--MyResult-->(1128): Johnny Depp

输出 ::

enter image description here

2 个答案:

答案 0 :(得分:1)

只需在asynctask onPostExecute()方法中设置textview:

代表:

 @Override 
            protected void onPostExecute(String result) {
                apacheTxtId.setText(name);
            } 

注意:我没有使用onProgressUpdate()方法就这样做了。它一定是错的

答案 1 :(得分:0)

1)你必须像这样从doInBackground()返回一个值:

 @Override
    protected String doInBackground(String... params) {
        Log.d(TAG, "doInBackground()");
        try {
            webData = doConnection(url);
            if (webData != null) {
                // Getting JSON Object node 
                JSONObject jsonObj = new JSONObject(webData);
                // Getting JSON Array node 
                contacts = jsonObj.getJSONArray(TAG_CONTACTS);
                // Getting data from Object node
                JSONObject c = contacts.getJSONObject(1);
                name = c.getString(TAG_NAME);
                Log.d(TAG, "doInBackground() contacts, name: "+contacts+", "+name);

                //HERE :)
                return name;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            publishProgress(1);
        } catch (IOException e) {
            e.printStackTrace();
            publishProgress(2);
        } catch (JSONException e) {
            e.printStackTrace();
            publishProgress(3);
        } catch (Exception e) {
            e.printStackTrace();
            publishProgress(4);
        }
        return null;
    }

2)然后你必须实际将name的值设置为TextView

 @Override
    protected void onPostExecute(String result) {

        if (apacheTxtId != null){
            apacheTxtId.setText(result);
        }

    }