• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Passing Data from a Ansunc class to another class

HeavensSentSword

Well-Known Member
Jan 19, 2016
134
36
So I have been working on this and now I am stuck. I have got some useful tips here and there but I can not figure out how to get the data out of the callBack method so I can use it in the parsing method.
What I am trying to do is to download a JSon file from the web (This is done fine and works)
Then pass the results to the Json parser class (this part is where I am stuck)
Then parse out the Json file(this works fine too)

I am at a lost as to how to pass the information right. I know I am missing something with android methods but cant lay my finer on it.

So this is the downloader class that I am using

Java:
public class JsonDownloaderTask extends AsyncTask<String, Void, String> {

    private String username;
    private String password;
    private AsyncResponse<String> callback;


    public JsonDownloaderTask(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public void setCallback(AsyncResponse<String> callback)
    {
        this.callback = callback;
    }

    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        return readFromFile(url);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (callback != null) {
            callback.onResponse(s);
        }else
        {
            Log.d(JsonDownloaderTask.class.getSimpleName(), " The Respone was ignored");
        }
    }

    private String streamToString(InputStream is) throws IOException {

        StringBuilder sb = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        //add a fake parent to the line json data
        sb.append("{ \"\"");
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        sb.append("}");
        return sb.toString();
    }

    private String readFromFile(String myWebpage) {

        String response = null;
        HttpURLConnection urlConnection = null;

        try {
            //Get the url connection
            URL url = new URL(myWebpage);
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            });
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();

            if (inputStream != null) {
                response = streamToString(inputStream);
                inputStream.close();
                //Log.d("Final String", response);
            }

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

        return response;
    }
}

And this is the JsonParser coce;

Java:
public class JSONParser {

    JSONObject jsonResponse;
    String jsonData;
    String username = "admin";
    String password = "admin";

    //Consturctor
    public JSONParser() { }



    public void parsesData(String promo,
                           ArrayList<String> pictureHTTP,
                           ArrayList<String> pathHTTP,
                           ArrayList<String> labelText) throws IOException {

        JsonDownloaderTask task = new JsonDownloaderTask(username, password);
        task.setCallback(new AsyncResponse<String>() {
            @Override
            public void onResponse(String response) {
                //Assign Resutls to the Json data
                jsonData = response;
                Log.d("Respons in Json :", jsonData);
                //parsesData();

            }
        });
        task.execute(promo);

        //Try to parse the data
        try
        {
            //Log.d("In the Try bloack" , jsonData);

            //if the jsonData is emplty then use hardcode crap
            if(jsonData == null)
            {
                jsonData =  "{ \"\" :[{\"picture\":\"https://apivitadev-643304293.ap-northeast-1.elb.amazonaws.com/media/wysiwyg/_HP_0122-0214.jpg\",\"path\":\"http://52.68.68.86/magento\",\"label\":\"Product One\"},{\"picture\":\"http://i.imgur.com/OMDyG8I.jpg\",\"path\":\"http://52.68.68.86/magento/index.php/hair-care.html\",\"label\":\"Product Two\"},{\"picture\":\"http://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg\",\"path\":\"http://52.68.68.86/magento/index.php/face-care.html\",\"label\":\"Product Three\"}] }";

            }

            //Creaate a new JSONObject ith the name/value mapping from the JSON string
            jsonResponse = new JSONObject(jsonData);
            //Returns the value mapped by the name if it exists and is a JSONArry
            JSONArray jsonMainNode = jsonResponse.optJSONArray("");

            //Proccess the JSON node
            int lenghtJsonArrar = jsonMainNode.length();
            for (int i = 0; i<lenghtJsonArrar; i++)
            {
                //Get object for each json node
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                //Get the node values
                //int song_id = Integer.parseInt(jsonChildNode.optString("song_id").toString());
                String picture = jsonChildNode.optString("picture").toString();
                String pathName = jsonChildNode.optString("path").toString();
                String lableName = jsonChildNode.optString("label".toString());
                //Debug Testing code
                pictureHTTP.add(picture);
                pathHTTP.add(pathName);
                labelText.add(lableName);


            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

And I am using a interface here as a go between
Java:
public interface AsyncResponse<T> {
    void onResponse(T response);
}


Any help will be appreciated very much.
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones