Monday, 8 February 2016

Android Programming Tutorial 57: Retrofit Example in Android

Creating a Project In Android Studio:

File >> New >> Android Application
Enter Project name: RetrofitExample
Package: com.ambilpursunil.retrofitexample
Keep other default selections, click Next until you reach Finish



  Simply Copy and Past the Code which is display below in the  MainActivity.java

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.retrofitexample.adapter.Adapter;
import com.retrofitexample.model.Flower;
import com.retrofitexample.network.api;

import java.util.List;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MainActivity extends ListActivity {

    List<Flower> dataList;

    @Override    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final RestAdapter restAdapter = new RestAdapter.Builder()
   .setEndpoint("http://services.hanselandpetal.com/").build();
    api dataAPI = restAdapter.create(api.class);

    dataAPI.getData(new Callback<List<Flower>>() {
    @Override    public void success(List<Flower> dataTypes, Response response) {
    dataList = dataTypes;
    Adapter adapter = new Adapter(getApplicationContext(),
    R.layout.item_file, dataList);
    setListAdapter(adapter);
    }
    @Override    public void failure(RetrofitError error) {
    Toast.makeText(getApplicationContext(),
    "SomeThing Went Wrong....!", Toast.LENGTH_SHORT).show();
    }
    });
    }
}

Now Create an Interface Simply Copy and Past the Code which is display below in the  api.java (Interface)
import com.retrofitexample.model.Flower;
import java.util.List;
import retrofit.Callback;
import retrofit.http.GET;

public interface api {

@GET("/feeds/flowers.json")
public void getData(Callback<List<Flower>> response);
}

 Now Create a Data Type Class and Simply Copy and Past the Code which is display below in the  Flower.java 
import android.graphics.Bitmap;
   public class Flower {
    int protductID;
    String name;
    String price;
    String instructions;
    String photo;
    String category;
    Bitmap bitmap;

    public int getProtductID() {
        return protductID;
    }

    public void setProtductID(int protductID) {
        this.protductID = protductID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getInstructions() {
        return instructions;
    }

    public void setInstructions(String instructions) {
        this.instructions = instructions;
    }

    public String getPhoto() {
        return photo;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
}
 Now Create Adapter Class to attach Layout and Simply Copy and Past the Code which is display below in the  Adapter.java 
import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.retrofitexample.R; import com.retrofitexample.model.Flower; import java.util.List; public class Adapter extends ArrayAdapter<Flower> { String url = "http://services.hanselandpetal.com/photos/"; Context context; List<Flower> dataItems; TextView tv; ImageView imgV; public Adapter(Context context, int resource, List<Flower> objects) { super(context, resource, objects); this.context = context; this.dataItems = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { ayoutInflater inflater = (LayoutInflater)context.
    getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.item_file, parent, false);
    Flower data = dataItems.get(position);
    tv = (TextView) view.findViewById(R.id.name);
    tv.setText(data.getName());
    imgV = (ImageView) view.findViewById(R.id.imageView);
    Glide.with(getContext()).load(url + data.getPhoto()).into(imgV);
    return view;
    }
}
 Create a layout and Past the Code which is display below in the  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"> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@android:id/list" /> </RelativeLayout>
Create a layout and Past the Code which is display below in the  item_data.xml 
<?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">
    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:textColor="#ff010101" />
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2" />
</LinearLayout>
Add Following jar in build.gradle display below in the  
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:+'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.3.0'
}
Copy and past the code for manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ambilpursunil.newapp"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="23" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
            </application>
</manifest>
Run Your Project as the below by clicking on shift+10 or like the below-->Android Application and observe the output
      

Please Send Your Comments To ambilpura.sunil@gmail.com

Stay Tune For Next Tutorial... About RecyclerView and Example In Android Studio

No comments:

Post a Comment