Callback in android(Network call in separate class)

I have layout xml name main.xml and i have main.java class in that class now i send network call and get data from rest service.But now i want to separate network call in anohther class.How can i do that.

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/callsubclass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call sub-class" />
    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

main.java

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttonCallSubClass = (Button)findViewById(R.id.callsubclass);
        textResult = (TextView)findViewById(R.id.result);

       // i can set network call here and update TExtview

       textResult .setText(result);
    }

rest service response ={"id":1958,"content":"Hello, World!"}

my separate nework.java class

String url1 = String.format("http://rest-service.guides.spring.io/greeting");
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                url1, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Test", response.toString());
                        String token="a";
                        String id="";
                        String result="";
                        try {
                            id= response.get("id").toString();
                            result= response.get("content").toString();
                        }catch (JSONException e){
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }


                    }

now i want to do network call in separate class give a solution.


Source: xml

Leave a Reply