Skip to content

Instantly share code, notes, and snippets.

@MostafaAtefsaber
Last active October 22, 2018 19:20
Show Gist options
  • Save MostafaAtefsaber/b5a7debb8a92a9537ac6ee919f9367f3 to your computer and use it in GitHub Desktop.
Save MostafaAtefsaber/b5a7debb8a92a9537ac6ee919f9367f3 to your computer and use it in GitHub Desktop.
Android fechData using Retrofit Application's screenshot at first comment
<?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">
<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>
json url (https://jsonplaceholder.typicode.com/posts)
from website( https://jsonplaceholder.typicode.com/ )
<?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>
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'
}
package com.example.mostafa.jsonretrofit;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
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();
}
package com.example.mostafa.jsonretrofit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private TextView textviewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textviewResult = findViewById(R.id.text_view_result);
// below we will execute our actual get request
// this retrofit instance we can now create our json placeholder api
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
// this is how we define that we want to use json to a pass the response
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonplaceHolderApi jsonplaceHolderApi = retrofit.create(JsonplaceHolderApi.class);
// to executr our network request
Call<List<Post>> call = jsonplaceHolderApi.getPosts();
call.enqueue(new Callback<List<Post>>() {
/**
* when we get a response back from the server
* but doesn't mean that our request was successful
* because the server code for EX: responds with a 404
* @param call
* @param response
*/
@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
List<Post> posts = response.body();
// 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);
}
}
/**
* Failure means that something went wrong in the communication with the
* server pr processing the response
*
* @param call
* @param t
*/
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textviewResult.setText(t.getMessage());
}
});
}
}
package com.example.mostafa.jsonretrofit;
import com.google.gson.annotations.SerializedName;
public class Post {
// here name of json value
private int userId ;
private int id;
private String title;
@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;
}
}
@MostafaAtefsaber
Copy link
Author

jsonimage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment