Im trying to get data from onResponse method through Retrofit library.But now I have that respone==0.I neew to get code of my request,to build logic in my app.For example if code==200,start new activity is something else build error message.
I'm trying to build right POST method to vid.me servise.That service have open API,method what I need:
https://docs.vid.me/#api-Auth-Create
myFragment:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
String username_value,password_value;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button) rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize() {
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
username_value = username.getText().toString();
password_value = password.getText().toString();
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
SignInResults results = response.body();
Log.d("Response ==>> ", new GsonBuilder().setPrettyPrinting().create().toJson(results));
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
API interface:
public interface VideoApi {
#GET("/videos/featured")
Call<Videos> getFeaturedVideo();
#GET("/videos/new")
Call<Videos> getNewVideo();
#Headers("Content-Type:application/x-www-form-urlencoded")
#FormUrlEncoded
#POST("/auth/create")
Call<SignInResults>insertUser(#Field("email") String username,
#Field("password") String password
);
}
SignInResult class:
public class SignInResult {
public String getAuthorization() {
return authorization;
}
public void setAuthorization(String authorization) {
this.authorization = authorization;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#SerializedName("authorization")
#Expose
private String authorization;
#SerializedName("code")
#Expose
private String code;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#SerializedName("username")
#Expose
private String username;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
#SerializedName("user_id")
#Expose
private String user_id;
}
SignInResults class:
public class SignInResults {
public SignInResult signInResult;
public List<SignInResult> getSignInResults() {
return signInResults;
}
List<SignInResult> signInResults;
}
You have to change this code to handle results properly
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
if(response.isSuccessful()) {
SignInResults results = response.body();
Log.d("Response ==>> ", new GsonBuilder().setPrettyPrinting().create().toJson(results));
}
else {
// handle error
}
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
Related
I want to show Json result in textview using retrofit2, but I can't get the desired result.
json
{
"rows" : [ {
"playerId" : "f8a49812eb9c3e5c8e738c3664e0ebd1",
"nickname" : "Yuichuan",
"grade" : 89
} ]
}
Model.class
public class Model {
public String playerId;
public String nickname;
public int grade;
public String getPlayerId() {
return playerId;
}
public void setPlayerId(String playerId) {
this.playerId = playerId;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
PlayerModel.class
public class PlayerModel {
public List<Model> rows;
}
**RetrofitFactory.class**
public class RetrofitFactory {
private static String BASE_URL="https://api.neople.co.kr/";
public static RetrofitService create(){
Retrofit retrofit=new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonC`enter code here`onverterFactory.create()).build();
return retrofit.create(RetrofitService.class);
}
}
RetrofitService.interface
public interface RetrofitService {
#GET("cy/players/")
Call<PlayerModel> getlist(#Query("nickname") String nickname,
#Query("apikey") String apikey);
}
MainActivityt
public class MainActivity extends AppCompatActivity {
private static final String API_KEY = "8yTuVMwy2DirHl2sWaZ3C8IJLslOfTpQ";
private static final String TAG ="Main" ;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.test);
RetrofitService networkService=RetrofitFactory.create();
networkService.getlist("Yuichuan",API_KEY)
.enqueue(new Callback<PlayerModel>() {
#Override
public void onResponse(Call<PlayerModel> call, Response<PlayerModel> response) {
if(!response.isSuccessful()){
textView.setText(response.code());
return;
}
Log.d(TAG, "onResponse: ConfigurationListener::"+call.request().url());
}
#Override
public void onFailure(Call<PlayerModel> call, Throwable t) {
textView.setText(t.getMessage());
}
});
}
}
I want to print out these json files, but it doesn't work as I want, so I want you to give me some help or advice.It seems like a simple problem, but it is very difficult for me because I am not used to json.
The textView.setText(response.code()); give you a code of response. To get your data model you need a body of response response.body()
I'm new in retrofit, I'm trying to get single post from jsonplaceholder website, the problem is that I can't find getTitle, getBody, getId, and getUserId in onresponse method in callback. I typed (response.body.) , but getter methods doesn't appear.
MainActivity
public class MainActivity extends AppCompatActivity {
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvText=findViewById(R.id.tvText);
Retrofit retrofit= new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface= retrofit.create(ApiInterface.class);
Call<POST> call= apiInterface.getPost();
call.enqueue(new Callback<POST>() {
#Override
public void onResponse(Call<POST> call, Response<POST> response) {
response.body().
}
#Override
public void onFailure(Call<POST> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Interface
public interface ApiInterface {
#GET("posts/1")
Call<POST> getPost();
}
Post class for json keys
public class Post {
private int id;
private int userId;
private String title;
private String body;
public int getId() {
return id;
}
public int getUserId() {
return userId;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
}
Xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<TextView
android:id="#+id/tvText"
android:layout_width="324dp"
android:layout_height="92dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
.....................
you need to do small change, the Call type should be Post not POST, as your model class name is Post.
working code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
Retrofit retrofit= new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface= retrofit.create(ApiInterface.class);
Call<Post> call= apiInterface.getPost();
call.enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
Log.i("response_title",response.body().getTitle()+"");
Log.i("response_userId",response.body().getUserId()+"");
Log.i("response_id",response.body().getId()+"");
Log.i("response_body",response.body().getBody()+"");
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
}
public interface ApiInterface {
#GET("Posts/1")
Call<Post> getPost();
}
public class Post {
private int id;
private int userId;
private String title;
private String body;
public int getId() {
return id;
}
public int getUserId() {
return userId;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
}
}
I have some api that contains JSON with partner names.
I've set up interface and pojo model. I'll post below my code.
Here is my POJO model Partner:
public class Partner {
#SerializedName("name")
#Expose
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now here is my interface:
public interface APIService {
#GET("Partner")
Call<List<Partner>> getPartners();
}
And here is my APIHelper:
public class APIHelper {
public static final String PARTNERS_URL = "https://part-of-url.herokuapp.com/partners.json/";
public static APIService apiService;
public static APIService getApiService() {
if (apiService == null) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(PARTNERS_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(APIService.class);
}
return apiService;
}
}
And this is Fragment which contains Button where onClick method needs to get data from web.
public class DownloadMain extends Fragment implements Callback<Partner> {
private static final String TAG = DownloadMain.class.getSimpleName();
private Button dloadPartners;
private Call callPartners;
public DownloadMain() {}
public DownloadMain newInstance() { return new DownloadMain(); }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_main, container, false);
dloadPartners = (Button) view.findViewById(R.id.downloadPartners);
dloadPartners.setOnClickListener(btnListener);
callPartners = APIHelper.getApiService().getPartners();
return view;
}
Button.OnClickListener btnListener = (new Button.OnClickListener() {
#Override
public void onClick(View v) {
callPartners.clone().enqueue(DownloadMain.this);
}
});
#Override
public void onResponse(Call call, Response response) {
if(response.body() == null) {
try {
response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "No Partners!", Toast.LENGTH_SHORT).show();
} else {
List<String> partners = (List<String>) response.body();
Log.d(TAG, "Number of partners received: " + partners.size());
Toast.makeText(getActivity(), "Partners downloaded!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call call, Throwable t) {
}
}
This is all my code for getting Partners from web.
I'm getting this error on server side and can't resolve it:
No route matches [GET] "/partners.json/Partner"
QUESTION: Can someone look at this code and say what is wrong and why I'm not getting data from web and also how should I resolve this no route error?
change your get path like so
public interface APIService {
#GET("partners.json")
Call<List<Partner>> getPartners();
}
and remove that path from your base url.
public class APIHelper {
public static final String PARTNERS_URL = "https://part-of-url.herokuapp.com/";
public static APIService apiService;
public static APIService getApiService() {
if (apiService == null) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(PARTNERS_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(APIService.class);
}
return apiService;
}
}
Im trying to get username when I try to login to wev service.I need this username to check did I this right or no.But have NPE when try to get data,but when I just make Toast without data,it works!onResponse work,but I must to get code of this operation to build logic of my app.For example if my code==200,build new activity,else-build alertdialog or something else.
What I did wrong?
myFragment:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button)rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize(){
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
String username_value = username.getText().toString();
String password_value = password.getText().toString();
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT).show();
String response_value = response.body().signInResults.get(0).getUsername();
Log.d("FeedFragment",response_value);
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
my interface API:
public interface VideoApi {
#GET("/videos/featured")
Call<Videos> getFeaturedVideo();
#GET("/videos/new")
Call<Videos> getNewVideo();
#FormUrlEncoded
#POST("/auth/create")
Call<SignInResults>insertUser(#Field("username") String username,
#Field("password") String password
);
}
and error:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.vid_me_app.FeedFragment$2.onResponse(FeedFragment.java:59)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
SignInResults.java // Model class
clas SignInResults {
public Boolean status;
public Auth auth;
public User user;
}
User.java //User Model
public class User {
public String userId;
public String username;
public String avatar;
}
checkout this code in onResponse function
if (response.isSuccess()) {
SignInResults results = response.body();
if(results != null) {
String userName = results.user.username;
Log.d("User Name ==>> ", userName);
}
} else {
// Do whatever you want if API is unsuccessful.
}
I want to login in some service called vid.me,https://api.vid.me/oauth/authorize with POST.But when I try to get data from log I have NullPointerException.I tryed to make Toast and have this error too.I'm trying to get response code to see I did this right or no.
my API class:
public interface VideoApi {
#GET("/videos/featured")
Call<Videos> getFeaturedVideo();
#GET("/videos/new")
Call<Videos> getNewVideo();
#FormUrlEncoded
#POST("oauth/authorize")
Call<SignInResults>insertUser(#Field("name") String name,
#Field("password") String password
);
}
my fragment:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button)rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize(){
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
Call<SignInResults> call = videoApi.insertUser(username.getText().toString(),password.getText().toString());
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
Log.d("FeedFragment", "Status Code = " + response.body().signInResults.get(0).getCode());
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
Call<SignInResponse> call = videoApi.insertUser(username_value, password_value);
call.enqueue(new Callback<SignInResponse>() {
#Override
public void onResponse(Call<SignInResponse> call, Response<SignInResponse> response) {
SignInResponse results = response.body();
Log.d("Response ==>> ", new GsonBuilder().setPrettyPrinting().create().toJson(results));
}
#Override
public void onFailure(Call<SignInResponse> call, Throwable t) {
}
});
#Headers("Content-Type:application/x-www-form-urlencoded")
#FormUrlEncoded
#POST("/auth/create")
Call<SignInResponse> insertUser(#Field("email") String username,
#Field("password") String password
);