Karthik CP
Karthik CP

Reputation: 1200

Call a method in my parent activity and return a value to fragment

I created a parent activity and Fragments are added to parent activity. But i need to call a function (HTTP request) in parent activity and return the result in fragment activity. But i am able to access the function from fragment using

 String stage = ((TabActivity)getActivity()).fetchStage(tabid,"12");

But the value is not receiving in fragments stage variable..

my TabActivity Function:

public String fetchStage(String tabid,String userId){
        Log.e("URL","http://35.184.41.163/phpmyadmin/app/demo/getstage.php?tabid="+tabid+"&userid="+userId);
        RestClientHelper.getInstance().get("http://35.184.41.163/phpmyadmin/app/demo/getstage.php?tabid="+tabid+"&userid="+userId, new RestClientHelper.RestClientListener() {
            @Override
            public void onSuccess(String response) {
                try {
                    Log.e("onSUcess Stage","onSUcess Stage");
                    JSONObject stageresponse = new JSONObject(response);
                    JSONArray posts = stageresponse.optJSONArray("stage");
                    for (int i = 0; i < posts.length(); i++) {
                        JSONObject post = posts.optJSONObject(i);
                        stage = post.optString("stage");
                        Log.e("onSUcess FOR","onSUcess FOR"+stage);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String error) {
                Log.e("onError Stage","onError Stage");
                stage = "stage1";
            }
        });
        Log.e("STAGE",stage);
        return stage;
    }

Upvotes: 1

Views: 288

Answers (2)

payloc91
payloc91

Reputation: 3809

You could supply an instance of RestClientListener to fetchStage.

The method signature would become:

fetchStage(String tabId, String userId, RestClientHelper.RestClientListener listener);

and when you call it from the Fragment you'd write:

((TabActivity)getActivity()).fetchStage(
    tabid, 
    "12", 
    new RestClientHelper.RestClientListener () {
        // this anonymous class has access to your instance members
        @Override
        public void onSuccess(String response) {
            // ...
            MyFragment.this.stage = ...
        }
        @Override
        public void onError(String error) {
            MyFragment.this.stage = "stage 1";
        }
});

This is widely used in Android; e.g setting a LocationListener to a LocationManager.

Upvotes: 1

karandeep singh
karandeep singh

Reputation: 2334

Your rest client is doing the network call asynchronously. So, your onSuccess isCalling after sometime. You should declare a public function in your fragment and call that from the onSuccess method.

Upvotes: 2

Related Questions