I'm making a GET request:
public interface CheckUserInDBRequest {
#GET("api/checkUserInDB.php")
Call<ResponseBody> searchForUser(
#Query("login") String login,
#Query("pass") String pass
);
}
And I get the answer true || false in json, according to whether there is a user in the database or not.
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://kurusa.zhecky.net/").addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
CheckUserInDBRequest client = retrofit.create(CheckUserInDBRequest.class);
Call<ResponseBody> call = client.searchForUser (
UserLogin.getText().toString(),
UserPass.getText().toString()
);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t) {
Toast.makeText(MainActivity.this, "no ", Toast.LENGTH_SHORT).show();
}
});
Here is just the output of okHttp3. I do not understand how to get a normal answer.
First, create a class representing your JSON object
public class UserResult {
public boolean isSet;
}
Restructure your Retrofit call in this way
#GET("api/checkUserInDB.php")
Call<UserResult> searchForUser(
#Query("login") String login,
#Query("pass") String pass
);
Then in your code:
call.enqueue(new Callback<UserResult>() {
#Override
public void onResponse(#NonNull Call<UserResult> call, #NonNull Response<UserResult> response) {
if (response.isSuccesfull()) {
UserResult result = response.body();
//use the value result.isSet where you need it
} else {
//something is broken
}
}
#Override
public void onFailure(#NonNull Call<UserResult> call, #NonNull Throwable t) {
Toast.makeText(MainActivity.this, "no ", Toast.LENGTH_SHORT).show();
}
});
Related
So, I was bothering with this issue.
I have in my code value named
public String currentSong = "artist- title";
and I use it in code like this
private MetadataOutput getSongTime() {
return new MetadataOutput() {
#Override
public void onMetadata(Metadata metadata) {
final int length = metadata.length();
if (length > 0) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(existingURL.split("play")[0] + "currentsong").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
currentSong = response.body().toString();
}
});
Toast.makeText(RadioService.this, currentSong, Toast.LENGTH_SHORT).show();
}
}
};
}
But value in Toast is always behind the change (on second run it have value I expected on first run)
Is there any way to make it work correctly?
currentSong get the value on the onResponse, and its asynchronous
You must wait the response to show the Toast Message
#Override
public void onResponse(Call call, Response response) throws IOException {
currentSong = response.body().toString();
// you new a new Thread to show info in the screen beacausre the methos is asynchronous
Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// show toast here
}
}
}
To check whether youtube url is available I used retrofit, it works well but I want to use it as validation I got stuck, here's my code :
CheckUrlHelper.java
private static final String BASE_URL= "https://youtu.be/";
public void CheckUrl(String youtube_id)
{
retrofit=new Retrofit.Builder().baseUrl(BASE_URL+youtube_id).build();
Call<ResponseBody> call= retrofit.create(CheckUrlAvailable.class).checkUrl();
call.enqueue(new Callback<ResponseBody>()
{
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
//Log.d("","response : "+response);
if(response.code() == 200)
{
result = "true";
}
else
{
result = "false";
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
result = "false";
}
});
listener.getResult(result);
}
public interface callbackListener {
void getResult(String result);
}
I've tried using interface like code on above but caused error.
My expectation : to get result (if it possibly to get result from code whether 200, 500 or etc), so :
MyClass.java
private String error_message;
public void onClick(View v) {
String video_link = editVideoLink.getText().toString();
CheckUrlHelper curl = new CheckUrlHelper();
/* MY Expectation */
if(curl.CheckUrl(video_link) == 200){
Toast.makeText(getActivity(),"url available",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),"url not available",Toast.LENGTH_SHORT).show();
}
/**** Edit ****/
String video_link = editVideoLink.getText().toString();
if(TextUtils.is_empty(video_link){
error_message = "Link cannot be empty";
} else if(/* methodNamewhatever(video_link) == false*/ OR /* methodNamewhatever(video_link) == 404*/){
error_message = "Invalid Link";
}else{
// save
}
Toast.makeText(getActivity(),error_message,Toast.LENGTH_SHORT).show();
So when user put youtube id on editText and then click on submit, it could be give the result as validation.
please help me
Thanks
Well, you misplaced the listener's location. Instead of calling it out of all functions, you need to call it once in each method in order to get the result after the response is triggered in onResponse and onFailure callbacks.
So you have to change your code to be like this
private static final String BASE_URL= "https://youtu.be/";
public void CheckUrl(String youtube_id, callbackListener listener)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL+youtube_id).build();
Boolean result = false;
Call<ResponseBody> call= retrofit.create(CheckUrlAvailable.class).checkUrl();
call.enqueue(new Callback<ResponseBody>()
{
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
//Log.d("","response : "+response);
if(response.code() == 200)
{
result = true;
}
else
{
result = false;
}
listener.getResult(result);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
result = false;
listener.getResult(result);
}
});
}
public interface callbackListener {
void getResult(Boolean result);
}
I have created some code snippets for you just try to use to solve your issues.
CheckUrlHelper.java
private static final String BASE_URL= "https://youtu.be/";
public void CheckUrl(String youtube_id, callbackListener listener)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL+youtube_id).build();
Boolean result = false;
Call<ResponseBody> call= retrofit.create(CheckUrlAvailable.class).checkUrl();
call.enqueue(new Callback<ResponseBody>()
{
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
//Log.d("","response : "+response);
if(response.code() == 200)
{
result = true;
}
else
{
result = false;
}
listener.getResult(result);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
result = false;
listener.getResult(result);
}
});
}
public interface callbackListener {
void getResult(Boolean result);
}
And modify your click code in
MyClass.java
public void onClick(View v) {
String video_link = editVideoLink.getText().toString();
CheckUrlHelper curl = new CheckUrlHelper();
//curl.CheckUrl(video_link);
curl.CheckUrl(video_link, new callbackListener() {
#Override
public void getResult(Boolean result) {
if(result){
Toast.makeText(getActivity(),"url available",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),"url not available",Toast.LENGTH_SHORT).show();
}
}
});
Hopefully this will solve your problems.
I am using retrofit2 to enqueue multiple recyclerviews. It works great on one recyclerview but when i go to enqueue a second one with a different category it doesnt work.
I have tried making a second onresponse method, i cant think of any other way of doing it
Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY);//This one is working!
Call<MovieResponse> call1 = apiInterface.getNowPlayingMovies(API_KEY); //This is what i what to implement
Here is the code
Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statuscode =response.code();
List<Movie> movies = response.body().getResults();
recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext()));
recyclerView1.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext())); //this works but not with the NowPlayingMovies, tested to see if it was the other recyclerview
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
If you dont prefer to use RxJava then you can use following solution:
Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statuscode =response.code();
List<Movie> movies = response.body().getResults();
recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext()));
secondAPICall();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
public void secondAPICall(){
call1.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statuscode =response.code();
List<Movie> movies = response.body().getResults();
recyclerView1.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext()));
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I’m developing Android app that’s based on a WordPress website, so I need to get a token to login the user to the app using the JWT method.
When I send a request, I don’t get any response from the server; probably there something wrong with my code. I installed the wordpress-rest-api plugin and jwt-auth-plugin on the website.
My code contains userModel.java which contains getters and setters for the user id, email, and token.
retroFitInterface.java:
#POST ("Authorization: Bearer")
Call<User> login (#Body Login login);
#GET ("secretinfo")
Call<ResponseBody>getSecret(#Header("Authorization")String authToken);
Login.java:
private String email,password;
public Login (String email,String password) {
this.email = email;
this.password = password;
}
}
MainActivity.java
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://taqoh.com/wp-json/jwt-auth/v1/token").addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
RetroFitInterface retroFitInterface = retrofit.create(RetroFitInterface.class);
private Button button, button1;
private static String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.login_btn);
button1 = findViewById(R.id.get_token_btn);
}
private void login() {
Login login = new Login("isohunter1#hotmail.com", "qweqweqwe123");
Call<User>call = retroFitInterface.login(login);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, response.body().getEmail(), Toast.LENGTH_LONG).show();
token = response.body().getToken();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG).show();
}
});
}
private void getSecret() {
Call<ResponseBody>secret = retroFitInterface.getSecret(token);
secret.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.login_btn) {
login();
} else if (v.getId() == R.id.get_token_btn) {
getSecret();
}
}
I'm using retrofit authentication, and I have a timeoutexception. I saw many questions, but I can't solve this.
Here's the code
public class FragmentRegistration extends Fragment {
View mainView;
EditText username, email, password, name;
Button button;
ApiClient pentairAPIClient = ApiClient.getInstance();
SupportopObj supportopObj = new SupportopObj();
SupportopObjActivate supportopObjActivate = new SupportopObjActivate();
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mainView = inflater.inflate
(R.layout.registration, container, false);
username = mainView.findViewById(R.id.username);
email = mainView.findViewById(R.id.email);
password = mainView.findViewById(R.id.password);
name = mainView.findViewById(R.id.name);
button = mainView.findViewById(R.id.register);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//String s = name.getText().toString();
//String split[] = s.split(" ");
supportopObj.setFirstName("Tester");
supportopObj.setLastName("Testryan");
supportopObj.setUsername(username.getText().toString());
supportopObj.setEmail(email.getText().toString());
supportopObj.setPassword(password.getText().toString());
supportopObjActivate.setUsername(supportopObj.getUsername());
supportopObjActivate.setEmail(supportopObj.getEmail());
supportopObjActivate.setPassword(supportopObj.getPassword());
supportopObjActivate.setType("generic");
updateApp();
}
});
return mainView;
}
public void updateApp() {
Call<ResponseBody> call = pentairAPIClient.registration(supportopObj);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
activationCall();
} else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error...", Toast.LENGTH_SHORT).show();
}
});
}
public void activationCall() {
Call<ResponseBody> callActive = pentairAPIClient.activation(supportopObjActivate);
callActive.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String data = response.body().string();
JSONObject obj = new JSONObject(data);
String client_id = obj.getString("client_id");
String client_secret = obj.getString("client_secret");
tokenCall(client_id, client_secret);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error in activation",
Toast.LENGTH_SHORT).show();
}
});
}
public void tokenCall(String client_id, String client_secret) {
Call<ResponseBody> token = pentairAPIClient.get_token("password", client_id, client_secret,
supportopObj.getEmail(), supportopObj.getPassword());
token.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), String.valueOf(response.body()), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Something wrong.....", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "You're on failure", Toast.LENGTH_SHORT).show();
}
});
}
}
I have no error in retrofit, I'm doing debugging and I see all the process, so I getting client id and secret successfully, then I'm getting a timeoutexception in the last onfailure(),
#Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{
Toast.makeText(getContext(), "You're onfailure",Toast.LENGTH_SHORT).show();
}
watch the code, that's the last line. How to fix it? The app not crashes, but in debug he drops timeoutexception like this. t={SocketTimeoutException#830038722120}java.net.SocketTimeoutException: timeout . In OkHttpClient the
readTimeout(10, TimeUnit.SECONDS).connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS); all are 10, i tried to set it 100, not helps. Help me. Thanks.