Retrofit Example
Step 1:
Step 1:
activity_main.xml
activity_main.xml
<RelativeLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="Hello Response here"
android:textColor="#ff2323"
android:textSize="22sp" />
</RelativeLayout>
build.gradle(Module: app)
build.gradle(Module: app)
dependencies {
compile 'com.squareup.retrofit:retrofit:1.9.0'
}
DetailsAPI
DetailsAPI
public interface DetailsAPI {
@GET("/key/value/one/two")
void insertUser(Callback<JsonObject> jsonObjectCallback);
}
MainActivity
MainActivity
public class MainActivity extends AppCompatActivity {
public static final String Root_url = "http://echo.jsontest.com/";
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv_response);
insertUser();
}
private void insertUser() {
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(Root_url).build();
DetailsAPI api = adapter.create(DetailsAPI.class);
api.insertUser(new Callback<JsonObject>() {
@Override
public void success(JsonObject jsonObject, Response response) {
Toast.makeText(MainActivity.this, "Success!" + "status is :" + response.getStatus(), Toast.LENGTH_SHORT).show();
if (response.getStatus() == 200)
tv.setText("You got the data");
}
public void failure(RetrofitError error) {
Toast.makeText(MainActivity.this, "try again!", Toast.LENGTH_SHORT).show();
}
});
}
}
Learn JSON parsing:
Learn JSON parsing: