0

I have searched couple of titles about this but I couldn't get a proper way what I want to do. I want to connect a server with GET url and must read return xml file into a string that I can use in different activities. My code is working just fine when I debug it but I couldn't get a proper string return from it.

    protected JSONArray doInBackground(String... params) {
    URL url;
    HttpURLConnection urlConnection = null;
    JSONArray response = new JSONArray();

    try {
        url = new URL(params[0]);
        urlConnection = (HttpURLConnection) url.openConnection();
        int responseCode = urlConnection.getResponseCode();

        if(responseCode == HttpStatus.SC_OK){
            String responseString = readStream(urlConnection.getInputStream());
            Log.v("CatalogClient", responseString);
            response = new JSONArray(responseString);
        }else{
            Log.v("CatalogClient", "Response code:"+ responseCode);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(urlConnection != null)
            urlConnection.disconnect();
    }

    return response;
}

private String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuffer response = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}
SinanAy
  • 13
  • 5
  • Using AsyncTask you should use the onPostExecute() method (which runs on your UI thread) to return a value to your activity. It looks like you're trying to achieve that with only the doInBackGround method, which won't work because that isn't in your UI thread. Check out the developer guidelines here: http://developer.android.com/reference/android/os/AsyncTask.html – Frank D. Jan 29 '15 at 08:25
  • Thanks for your answer. Actually I have to wait till asyncTask finish because I will start different activities according to content of xml file. execute().get() is not recommended because it will block my main activity. I understand that I must use onpostexecute() method but I couldn't understand how can I parse the return String into another class like public class finalResult{ String result; } Can you give me an example about that. Thanks again – SinanAy Jan 29 '15 at 09:38
  • You'll need an interface to communicate with your Activity from your AsyncTask: I think this question has exactly what you need: http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a – Frank D. Jan 29 '15 at 10:02

1 Answers1

-1

Try this

public class MainActivity extends ActionBarActivity {

Helper parser = new Helper();
Document doc;
NodeList nl;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    callUrl();

}

private void callUrl() {

    new NetworkRequest(new CallbackInterface() {

        @Override
        public void onRequestSuccess(String result) {
            doc = parser.getDocumentElement(result);
            nl = doc.getElementsByTagName("item");

            for (int i = 0; i < nl.getLength(); i++) {


                String id = parser.getValue(element, "id");
                String name = parser.getValue(element, "name");
                String cost = parser.getValue(element, "cost");
                String description = parser.getValue(element, "description");

                Log.i("Values", id + name + cost + description);
            }

        }
    }, "").execute();
}
}

Create Helper class to parse the datas

public class Helper {

public Document getDocumentElement(String xml) {

    Document doc = null;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    return doc;

}

public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}

public final String getElementValue(Node elem) {
    Node child;
    if (elem != null) {
        if (elem.hasChildNodes()) {
            for (child = elem.getFirstChild(); child != null; child = child
                    .getNextSibling()) {
                if (child.getNodeType() == Node.TEXT_NODE) {
                    return child.getNodeValue();
                }
            }
        }
    }
    return "";
}
}

Create NetworkRequest class

public class NetworkRequest extends AsyncTask<Void, Void, String> {

private String url = "http://api.androidhive.info/pizza/?format=xml";
private CallbackInterface callBack;
private String result;

public interface CallbackInterface {
    public void onRequestSuccess(String result);
}

public NetworkRequest(CallbackInterface callBack, String url) {
    this.url += url;
    this.callBack = callBack;
}

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

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        result = EntityUtils.toString(httpEntity);
        return result;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    callBack.onRequestSuccess(result);
}
}
Jai Rajesh
  • 939
  • 5
  • 18