2

I am using Retrofit for sending POST request.Server return's a JSON Response and i am able to parse the response in the callback method. I need to pass the data from server to another activity. But i can't use the response data outside.

    api.LoginUser(
            Email.getText().toString(),          // passing value to interface of retrofit
            Password.getText().toString(),
            new Callback<Response>() {
                @Override
                public void success(Response result, Response response) {
                    BufferedReader reader = null;
                    String output = "";
                    try {                   
                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                        output = reader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //Json PArsing
                    try {
                        JSONObject mainObject = new JSONObject(output);
                        JSONObject dataObj = mainObject.getJSONObject("data");
                        String id = dataObj.getString("id");
                        String name = dataObj.getString("name");
              n=name;
                        Log.d("jsontext", n);                               //This works
                    }
                    catch(JSONException e)
                    {
                         e.printStackTrace();
                    }

                    Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
                }
                @Override
                public void failure(RetrofitError error) {
                    //If any error occured displaying the error as toast
                    Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                }
            }
    );

I can't use this when it executes App crashes.its ok now there is no value in the variable.how to get values out of the callback Responds OnSuccess method???

            Log.d("outer",n);
            Intent dash = new Intent(this,Dashboard.class);
            dash.putExtra("Value",fi);
            startActivity(dash);

}
tomas.pecserke
  • 3,260
  • 25
  • 26
livemaker
  • 464
  • 1
  • 9
  • 19

4 Answers4

0

You can create an object and implement Serializable:

class User implements Serializable {
...
}

Then put object User to bundle, add to intent:

Bundle bundle = new Bundle();
bundle.putSerializable("data", user);
Intent intent = new Intent(this, YourClass.class);
intent.putExtras(bundle);
startActivity(intent);

Hope it help you.

Sinh Phan
  • 1,180
  • 3
  • 16
  • 36
  • Thanx for your responds, the value is available only in the Callback fuction i cant store it to a global variable it doesnt work Intent can't be implemented in the callback fuction. – livemaker May 24 '16 at 09:00
  • i understand that you want send object to another activity? – Sinh Phan May 24 '16 at 09:23
0

Hold all data in a string and using intent app another activity and parse it;

0

You can do it as follows

public void onSuccess(int statusCode, Header[] headers, byte[] response) {

            try {

                BufferedReader br = new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(
                                response)));
                String st = "";
                String st1 = "";
                while ((st = br.readLine()) != null) {

                    st1 = st1 + st;

                }
               showStoreData(st1);

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

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              byte[] errorResponse, Throwable e) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
            Log.e("FAIL", "FAIl" + statusCode);
                       }

        @Override
        public void onRetry(int retryNo) {
            // called when request is retried
        }
    });

after that

public void showStoreData(String st) {

   Intent intent = new Intent(this, YourClass.class);
    intent.putExtras(st);
     startActivity(intent);
}
0

You should use an interface that you initialize from the calling method and pass as a parameter into you request class, that way you can call the requests from anywhere and get the callback response back to where you called it from, an example would be:

A general interface, separated in another file:

public interface SomeCustomListener<T>
{
    public void getResult(T object);
}

In the class holding your call (complete the stuff you need):

public void someRequestReturningString(Object param1, final SomeCustomListener<String> listener)
{
//here you initialize what you need... it's your stuff

    response.enqueue(new Callback<ResponseBody>()
    {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> rawResponse)
        {
            try
            {
              String response = rawResponse.body().string();

              // do what you want with it and based on that...
              //return it to who called this method
              listener.getResult("someResultString");
            }
            catch (Exception e)
            {
             e.printStackTrace();
             listener.getResult("Error1...");
            }
        }  
        @Override
        public void onFailure(Call<ResponseBody> call, Throwable throwable)
        {
            try
            {
             // do something else in case of an error
             listener.getResult("Error2...");
            }
            catch (Exception e)
            {
             throwable.printStackTrace();
             listener.getResult("Error3...");
            }
        }
    });
}

Then from where you're calling the request (could be anywhere, Fragments, onClicks, etc):

public class BlaBla
{
//.....

    public void someMethod()
    {
    NetworkManager.getInstance().someRequestReturningString(someObject, new SomeCustomListener<String>()
        {
            @Override
            public void getResult(String result)
            {
                if (!result.isEmpty())
                {
                 //do what you need with the result...
                }
            }
        });
    }
}

If you need more context, you can refer to this SO thread.

Hope this helps!

Community
  • 1
  • 1
TommySM
  • 3,793
  • 3
  • 24
  • 36