0

What i am trying to do: I am trying to parse a value from URL http://api.androidhive.info/contacts/ and display a value in the textview on click of a button

What is happening: I am not able to show the result in the fragment though i can see the log that the value has correctly been parsed.

How can i resolve this ! !


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;
    }

}

log::

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

Output::

enter image description here

2 Answers 2

1

just set textview in your asynctask onPostExecute() method:

for ex:

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

Note: i did this without using onProgressUpdate() method. it must be something wrong over there

Sign up to request clarification or add additional context in comments.

Comments

0

1) You have to return a value from doInBackground() like so:

 @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) And then you have to actually set the value of name to your TextView

 @Override
    protected void onPostExecute(String result) {

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

    }

5 Comments

Yup ! ... that's the solution right ! ...... So If we are printing a value in the onPostExecute() ..... We have to return the value from doInBackground()as you mentioned in order for the OnPostExecute() to to update the UI-Thread ?
you dont have to set a return value for doInBackground() way you did this is ok. besides you already have a return value which is name
Devrath - yes, return the value in doInBackground() but update the UI element from main thread in onPostExecute(). @santalu - if he does not return the value, it will be a null value returned.
he has already a global variable "name" and he's setting name = c.getString(TAG_NAME); inside doInBackground() method. so it doesn't matter whether he's returning null from doInBackground() cause he already retrieved what he want
Yup, you're right, saw that now. But to hash this out, I'm setting the textView with the parameter result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.