Skip to content

Instantly share code, notes, and snippets.

@MostafaAtefsaber
Last active December 27, 2018 18:34
Show Gist options
  • Save MostafaAtefsaber/b2e9ef60a72a5abe17f3ea8529986556 to your computer and use it in GitHub Desktop.
Save MostafaAtefsaber/b2e9ef60a72a5abe17f3ea8529986556 to your computer and use it in GitHub Desktop.
get data through Api using Retrofit and set Data at view cart
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp"
>
<Button
android:id="@+id/btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Get Data"
android:layout_weight="1"
android:onClick="getData"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Userid:"
android:layout_weight="1"
android:paddingLeft="20dp"
android:textSize="20dp"/>
<EditText
android:id="@+id/EdittextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingLeft="20dp"
android:inputType="number"
android:hint="id"/>
<Button
android:id="@+id/btndelete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_weight="1"
android:onClick="Delete"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/catView"
android:id="@+id/recycale"/>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
/>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
package com.example.mostafa.jsonretrofit;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.text.ParseException;
import java.util.List;
public class Adabterpost extends RecyclerView.Adapter<Adabterpost.PostViewholder>{
private Context mCtx;
private List<Post>postList;
public Adabterpost(Context mCtx, List<Post> postList)throws ParseException {
this.mCtx =mCtx;
this.postList =postList;
}
@NonNull
@Override
public PostViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.cardview,parent,false);
return new PostViewholder(view);
}
@Override
public void onBindViewHolder(@NonNull final PostViewholder holder,final int position) {
final Post post = postList.get(position);
holder.textViewid.setText(String.valueOf(post.getId()));
holder.textViewuserid.setText(String.valueOf(post.getUserId()));
holder.textViewtitle.setText(post.getTitle());
holder.textViewbody.setText(post.getText());
}
@Override
public int getItemCount() {
return postList.size();
}
public class PostViewholder extends RecyclerView.ViewHolder {
TextView textViewid,textViewuserid,textViewtitle,textViewbody;
public PostViewholder(View itemView) {
super(itemView);
textViewid = itemView.findViewById(R.id.id);
textViewuserid= itemView.findViewById(R.id.userid);
textViewtitle = itemView.findViewById(R.id.title);
textViewbody = itemView.findViewById(R.id.body);
}
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.mostafa.jsonretrofit"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// Retofit
//implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
// recyclerview
implementation 'com.android.support:recyclerview-v7:27.0.0'
// cardview
implementation 'com.android.support:cardview-v7:27.+'
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:CardView="http://schemas.android.com/tools"
app:cardCornerRadius="5dp"
app:cardElevation="8dp"
app:cardBackgroundColor="#fff"
app:cardUseCompatPadding="true"
android:id="@+id/cardss"
CardView:cardCornerRadius="20dp">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="4dp">
<TextView
android:id="@+id/id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="id"
android:textColor="#000"
android:textSize="15dp" />
<TextView
android:id="@+id/userid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="userid"
android:textColor="#000"
android:textSize="15dp" />
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="title"
android:textColor="#000"
android:textSize="15dp" />
<TextView
android:id="@+id/body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="body"
android:textColor="#000"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
package com.example.mostafa.jsonretrofit;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface JsonplaceHolderApi {
// create one method that return Call Object
/**
* this is what we want to get back from this car
* a list of posts which is a json array of posts
* json objects that we saw
*/
//@GET("posts") // posts is relative URL from here (https://jsonplaceholder.typicode.com/posts)
//Call<List<Post>>getPosts();
@GET("posts") // posts is relative URL from here (https://jsonplaceholder.typicode.com/posts?=Number)
Call<List<Post>> getPosts(@Query("userId")int userId);
}
package com.example.mostafa.jsonretrofit;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private TextView textviewResult;
private EditText editText;
private int useridnumber;
private List<Post> posts ;
private Adabterpost adabter;
RecyclerView recyclerMain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textviewResult = findViewById(R.id.text_view_result);
recyclerMain=findViewById(R.id.recycale);
recyclerMain.setLayoutManager(new LinearLayoutManager(this));
recyclerMain.setHasFixedSize(true);
}
public void getposts(){ // to executr our network request
editText = findViewById(R.id.EdittextView);
useridnumber =Integer.parseInt(editText.getText().toString());
//Call<List<Post>> call = jsonplaceHolderApi.getPosts(useridnumber);
Call<List<Post>> call = RetrofitClient.getInstance().getApi().getPosts(useridnumber);
call.enqueue(new Callback<List<Post>>() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
// check respons is successful
if (!response.isSuccessful()) {
textviewResult.setText("Code: " + response.code());
return;
}
// here actuly Data that we want from web serves
posts = response.body();
if(posts == null){
Toast.makeText(getApplicationContext(),"its null list",Toast.LENGTH_SHORT).show();
}
try {
adabter = new Adabterpost(getApplicationContext(),posts);
} catch (ParseException e) {
e.printStackTrace();
}
recyclerMain.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
recyclerMain.setAdapter(adabter);
// here we will display this data in textview
/*
for(Post post : posts){
String content = "";
content+= "ID: "+ post.getId()+"\n";
content+= "User ID: "+ post.getUserId()+"\n";
content+= "Title: "+ post.getTitle()+"\n";
content+= "Body: "+ post.getText()+"\n\n";
textviewResult.append(content);
*/
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textviewResult.setText(t.getMessage());
}
});
}
public void getData(View view){
getposts();
}
public void Delete(View view){
//ToDo
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mostafa.jsonretrofit">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.example.mostafa.jsonretrofit;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Post {
// here name of json value
private int userId ;
private int id;
private String title;
private List<Post> post;
public List<Post> getPost() {
return post;
}
@SerializedName("body")
private String text;
// Getter methods
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getText() {
return text;
}
}
package com.example.mostafa.jsonretrofit;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static final String BASURL="https://jsonplaceholder.typicode.com/";
private Retrofit retrofit;
private static RetrofitClient mInstance;
public RetrofitClient() {
// below we will execute our actual get request
// this retrofit instance we can now create our json placeholder api
retrofit = new Retrofit.Builder()
.baseUrl(BASURL)
// this is how we define that we want to use json to a pass the response
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetrofitClient getInstance(){
if(mInstance == null){
mInstance = new RetrofitClient();
}
return mInstance;
}
public JsonplaceHolderApi getApi(){
return retrofit.create(JsonplaceHolderApi.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment