Retrofit is same as Volley and it is definitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier.
Now let’s see the action of retrofit by creating a new project. As an example, we are going to download some json and show it in RecyclerView as a list.
Step 1. Create a new project in Android Studio
Step 2. Open build.gradle and add Retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
make change over dependencies
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
}
Step 3. Since we are working with network operations we need to add INTERNET permissions in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
Step 4. Open activity_main.xml and replace the design
<?xml version="1.0" encoding="utf-8"?>
<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="com.ufours.retrofit_sample.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/idRecycler"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Step 5. Create new xml card_view.xml and replace the design
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="1dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/card_view">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/person_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/person_name"
android:layout_toRightOf="@+id/person_photo"
android:layout_alignParentTop="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
public interface APICallInterface {
@GET
@Headers("Connection:close")
Call<ResponseBody>
callAPI(@Url String url);
@GET
@Headers("Connection:close")
Call<ResponseBody> callAPI(@Url String url, @QueryMap Map<String,
String> parameters);
@POST
@Headers("Connection:close")
Call<ResponseBody> postToAPI(@Url String url, @Body RequestBody
parameter);
@PUT
@Headers("Connection:close")
Call<ResponseBody> putToAPI(@Url String url, @Body RequestBody
parameter);
}
Step 7. Open MainActivity.java and replace the coding
public class MainActivity extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
Retrofit retrofit;
APICallInterface service;
Call<ResponseBody> call = null;
static ProgressDialog pDialog;
private int mStatusCode;
private static RecyclerView recyclerView;
private RecyclerView.LayoutManager m_LayoutManager;
String strTesti, strUrl;;
public static String TAG_IMAGE_URL = "Image";
public static String TAG_CONTENT = "content";
ArrayList<HashMap<String, String>> arraySend = new ArrayList<>();
CustomAdapter customAdapter;
//Reponsecode
public static final int SUCEESSRESPONSECODE = 200;
public static final int FAILURERESPONSECODE = 204;
public static final int INTERNALERRORRESPONSECODE = 500;
public static final int ERRORRESPONSECODE = 400;
String base_url = "http://YOUR_URL_HERE.com/";
String url = "YOUR_METHOD_URL_HERE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder()
.baseUrl(base_url)
.build();
service = retrofit.create(APICallInterface.class);
recyclerView = (RecyclerView)findViewById(R.id.idRecycler);
recyclerView.setHasFixedSize(true);
m_LayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(m_LayoutManager);
if (isConnectingToInternet(MainActivity.this)) {
loadImage();
}else{
alertbox(MainActivity.this,
getString(R.string.str_networkmessage),
getString(R.string.str_networktitlemessage));
}
}
private void loadImage() {
showDialog(MainActivity.this, "Loading");
call = service.callAPI(url);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try{
mStatusCode = response.code();
if (mStatusCode == SUCEESSRESPONSECODE) {
JSONArray resultarray = new JSONArray(response.body().string());
for (int i = 0; i < resultarray.length(); i++) {
JSONObject nmcdata = resultarray.getJSONObject(i);
strUrl = nmcdata.getString(TAG_IMAGE_URL);
strTesti = nmcdata.getString(TAG_CONTENT);
HashMap<String, String> objMap = new HashMap<>();
objMap.put(TAG_IMAGE_URL, strUrl);
objMap.put(TAG_CONTENT, strTesti);
arraySend.add(objMap);
}
dismissDialog();
}else if (mStatusCode == FAILURERESPONSECODE) {
dismissDialog();
Snackbar snackbar = Snackbar.make(coordinatorLayout,
response.errorBody().string(), Snackbar.LENGTH_LONG);
snackbar.show();
} else {
if (mStatusCode == INTERNALERRORRESPONSECODE) {
dismissDialog();
Snackbar snackbar = Snackbar.make(coordinatorLayout,
response.errorBody().string(), Snackbar.LENGTH_LONG);
snackbar.show();
}
}
}catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (arraySend.size() > 0) {
customAdapter = new CustomAdapter(MainActivity.this, arraySend, recyclerView);
recyclerView.setAdapter(customAdapter);
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
//internet_connection_check
public boolean isConnectingToInternet(Context _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info == null) {
return false;
} else
return true;
}
public void alertbox(Context _context, String message, String title) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(_context);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(true);
builder1.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
public static void showDialog(Context mContext, String strMessage) {
try {
if (pDialog != null)
if (pDialog.isShowing())
pDialog.dismiss();
pDialog = ProgressDialog.show(mContext, "", strMessage, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void dismissDialog() {
try {
if (pDialog.isShowing())
pDialog.dismiss();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
URL used here brings the response as this
Step 8. Create a adapter class CustomAdapter.java
public class CustomAdapter extends RecyclerView.Adapter{
RecyclerView mrecyclerview;
static Context context;
ArrayList<HashMap<String, String>> Items = new ArrayList<>();
public CustomAdapter(MainActivity context, ArrayList<HashMap<String, String>> arraySend, RecyclerView recyclerView) {
this.context = context;
mrecyclerview = recyclerView;
Items = arraySend;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, null);
vh = new ViewHolder(itemLayoutView);
return vh;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
final HashMap<String, String> tempMap = Items.get(position);
((ViewHolder) holder).txtConten.setText(tempMap
.get(MainActivity.TAG_CONTENT));
String urlImg = tempMap
.get(MainActivity.TAG_IMAGE_URL);
Glide.with(context)
.load(urlImg)
.into(((ViewHolder) holder).imgUrl);
}catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return Items.size();
}
private class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtConten;
ImageView imgUrl;
CardView cardview;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
cardview = (CardView) itemLayoutView.findViewById(R.id.card_view);
imgUrl = (ImageView) itemLayoutView.findViewById(R.id.person_photo);
txtConten = (TextView) itemLayoutView.findViewById(R.id.person_name);
}
}
}
Now run the application and the output is as
________________________________________________________
Sourcecode for RetrofitSample.zip
Happy Coding...
Comments
Post a Comment