1. Are you ready for the Galaxy S20? Here is everything we know so far!

Passing Data from a Ansunc class to another class

Discussion in 'Android Development' started by HeavensSentSword, Feb 5, 2016.

  1. HeavensSentSword

    HeavensSentSword Well-Known Member
    Thread Starter

    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

    Code (Java):
    1. public class JsonDownloaderTask extends AsyncTask<String, Void, String> {
    2.  
    3.     private String username;
    4.     private String password;
    5.     private AsyncResponse<String> callback;
    6.  
    7.  
    8.     public JsonDownloaderTask(String username, String password) {
    9.         this.username = username;
    10.         this.password = password;
    11.     }
    12.  
    13.     public void setCallback(AsyncResponse<String> callback)
    14.     {
    15.         this.callback = callback;
    16.     }
    17.  
    18.     @Override
    19.     protected String doInBackground(String... params) {
    20.         String url = params[0];
    21.         return readFromFile(url);
    22.     }
    23.  
    24.     @Override
    25.     protected void onPostExecute(String s) {
    26.         super.onPostExecute(s);
    27.         if (callback != null) {
    28.             callback.onResponse(s);
    29.         }else
    30.         {
    31.             Log.d(JsonDownloaderTask.class.getSimpleName(), " The Respone was ignored");
    32.         }
    33.     }
    34.  
    35.     private String streamToString(InputStream is) throws IOException {
    36.  
    37.         StringBuilder sb = new StringBuilder();
    38.         BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    39.         //add a fake parent to the line json data
    40.         sb.append("{ \"\"");
    41.         String line;
    42.         while ((line = rd.readLine()) != null) {
    43.             sb.append(line);
    44.         }
    45.         sb.append("}");
    46.         return sb.toString();
    47.     }
    48.  
    49.     private String readFromFile(String myWebpage) {
    50.  
    51.         String response = null;
    52.         HttpURLConnection urlConnection = null;
    53.  
    54.         try {
    55.             //Get the url connection
    56.             URL url = new URL(myWebpage);
    57.             Authenticator.setDefault(new Authenticator() {
    58.                 @Override
    59.                 protected PasswordAuthentication getPasswordAuthentication() {
    60.                     return new PasswordAuthentication(username, password.toCharArray());
    61.                 }
    62.             });
    63.             urlConnection = (HttpURLConnection) url.openConnection();
    64.  
    65.             InputStream inputStream = urlConnection.getInputStream();
    66.  
    67.             if (inputStream != null) {
    68.                 response = streamToString(inputStream);
    69.                 inputStream.close();
    70.                 //Log.d("Final String", response);
    71.             }
    72.  
    73.         } catch (IOException e) {
    74.             e.printStackTrace();
    75.         } finally {
    76.             if (urlConnection != null) {
    77.                 urlConnection.disconnect();
    78.             }
    79.         }
    80.  
    81.         return response;
    82.     }
    83. }
    And this is the JsonParser coce;

    Code (Java):
    1. public class JSONParser {
    2.  
    3.     JSONObject jsonResponse;
    4.     String jsonData;
    5.     String username = "admin";
    6.     String password = "admin";
    7.  
    8.     //Consturctor
    9.     public JSONParser() { }
    10.  
    11.  
    12.  
    13.     public void parsesData(String promo,
    14.                            ArrayList<String> pictureHTTP,
    15.                            ArrayList<String> pathHTTP,
    16.                            ArrayList<String> labelText) throws IOException {
    17.  
    18.         JsonDownloaderTask task = new JsonDownloaderTask(username, password);
    19.         task.setCallback(new AsyncResponse<String>() {
    20.             @Override
    21.             public void onResponse(String response) {
    22.                 //Assign Resutls to the Json data
    23.                 jsonData = response;
    24.                 Log.d("Respons in Json :", jsonData);
    25.                 //parsesData();
    26.  
    27.             }
    28.         });
    29.         task.execute(promo);
    30.  
    31.         //Try to parse the data
    32.         try
    33.         {
    34.             //Log.d("In the Try bloack" , jsonData);
    35.  
    36.             //if the jsonData is emplty then use hardcode crap
    37.             if(jsonData == null)
    38.             {
    39.                 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\"}] }";
    40.  
    41.             }
    42.  
    43.             //Creaate a new JSONObject ith the name/value mapping from the JSON string
    44.             jsonResponse = new JSONObject(jsonData);
    45.             //Returns the value mapped by the name if it exists and is a JSONArry
    46.             JSONArray jsonMainNode = jsonResponse.optJSONArray("");
    47.  
    48.             //Proccess the JSON node
    49.             int lenghtJsonArrar = jsonMainNode.length();
    50.             for (int i = 0; i<lenghtJsonArrar; i++)
    51.             {
    52.                 //Get object for each json node
    53.                 JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    54.                 //Get the node values
    55.                 //int song_id = Integer.parseInt(jsonChildNode.optString("song_id").toString());
    56.                 String picture = jsonChildNode.optString("picture").toString();
    57.                 String pathName = jsonChildNode.optString("path").toString();
    58.                 String lableName = jsonChildNode.optString("label".toString());
    59.                 //Debug Testing code
    60.                 pictureHTTP.add(picture);
    61.                 pathHTTP.add(pathName);
    62.                 labelText.add(lableName);
    63.  
    64.  
    65.             }
    66.  
    67.         } catch (JSONException e) {
    68.             e.printStackTrace();
    69.         }
    70.  
    71.     }
    72. }
    73.  
    And I am using a interface here as a go between
    Code (Java):
    1. public interface AsyncResponse<T> {
    2.     void onResponse(T response);
    3. }
    4.  

    Any help will be appreciated very much.
     


  2. Best Answer:
    Post #2 by Deleted User, Feb 5, 2016 (3 points)

    1. Download the Forums for Android™ app!


      Download

       
  3. Deleted User

    Deleted User Guest

    HeavensSentSword likes this.
  4. HeavensSentSword

    HeavensSentSword Well-Known Member
    Thread Starter

    YES!
    Thank you Lv426 the .get() made it work perfectly.
     
Loading...

Share This Page

Loading...