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.
Related
i want to call api request every x second using Runnable and read live response to multiple fragment on every api call.
i try bellow code but if start runnable from FragmentA then can't get response on FragmentB even if runnable already run api call in background.
when i run RunnableDemo(mContext, this, JsonRpc.Method.TELL_ACTIVE).run(); in fragmentA and start runnable however can get onDataSuccess in fragmentB.
and if i use RunnableDemo(mContext, this, JsonRpc.Method.TELL_ACTIVE).run(); in FragmentB then run two time API call for FragmentA and FragmentB.
so, how can i run api call every x second once and receive response on multiple fragments?
thank you,
RunnableDemo.java
public class RunnableDemo implements Runnable{
RunnableDemo.RunnableDemoListener listener;
public void run() {
if (myRunnable == null) {
myHandler.postDelayed(myRunnable = new Runnable() {
public void run() {
if(shouldRun) {
running = true;
//do something
loop();
}
myHandler.postDelayed(myRunnable, updateInterval);
}
}, updateInterval);
}
}
private void loop() {
...retrofit....
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response)
{
listener.onDataSuccess(response);
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t)
{
listener.onDataError("error");
}
});
}
public void stop() {
if (listener != null) {
listener.onStopped();
}
running = false;
shouldRun = false;
}
public final boolean isRunning() {
return running;
}
public final boolean safeStop() {
if (listener != null) {
listener.onStopped();
}
shouldRun = false;
running = false;
return true;
}
// Listener defined earlier
public interface RunnableDemoListener {
public void onDataError(String title);
public void onDataSuccess(Response<ResponseBody> responseBody);
public void onStopped();
}
}
FragmentA.java
public class FargmentA extends Fragment implements RunnableDemo.RunnableDemoListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
RunnableDemo runnableDemo = new RunnableDemo(mContext, this, JsonRpc.Method.TELL_ACTIVE);
if(!runnableDemo.isRunning()) {
runnableDemo.run();
}
}
#Override
public void onDataError(String title) {
Log.i("TEST", "TestRunnable onResponse receive error Files: "+ title);
}
#Override
public void onDataSuccess(Response<ResponseBody> responseBody) {
Log.i("TEST", "TestRunnable onResponse receive success Files: "+ responseBody.code());
}
#Override
public void onStopped() {
Log.i("TEST", "TestRunnable onResponse receive onStopped Files: ");
}
}
FragmentB.java
public class FargmentB extends Fragment implements RunnableDemo.RunnableDemoListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
RunnableDemo runnableDemo = new RunnableDemo(mContext, this, JsonRpc.Method.TELL_ACTIVE);
if(!runnableDemo.isRunning()) {
runnableDemo.run();
}
}
#Override
public void onDataError(String title) {
Log.i("TEST", "TestRunnable onResponse receive error Files: "+ title);
}
#Override
public void onDataSuccess(Response<ResponseBody> responseBody) {
Log.i("TEST", "TestRunnable onResponse receive success Files: "+ responseBody.code());
}
#Override
public void onStopped() {
Log.i("TEST", "TestRunnable onResponse receive onStopped Files: ");
}
}
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
}
}
}
public static void getAccuWeatherData( String appId, final InterfaceWeatherCallbackListener listener) {
InterfaceWeatherApi mWeatherApi = ApiService.getRetrofitInstance(BASE_DEV_URL_ACCU_WEATHER).create(InterfaceWeatherApi.class);
Call<List<AccuWeatherModel>> call = mWeatherApi.getAccuWeatherData(appId);
Log.d("call",""+call);
call.enqueue(new Callback<List<AccuWeatherModel>>() {
#Override
public void onResponse(Call<List<AccuWeatherModel>> call, Response<List<AccuWeatherModel>> response) {
Log.e("response",""+response);
if (response.body() != null) {
if (listener != null)
Log.e("Base Url","listener"+listener);
listener.getWeatherData(response.body().get(0), true, "");
}
}
#Override
public void onFailure(Call<List<AccuWeatherModel>> call, Throwable t) {
listener.getWeatherData(null, false, t.getMessage());
}
});
}
I am using MVVM pattern in which I am using SwipeRefresh layout to refresh recycler view in my layout.When I am pulling it then it continue to refresh even after method completed successfully.
Below is my code:
MainActivity.java
refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
userRepository.getUserList();
}
});
UserRepository.java
public void getUserList(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<User>> userList = apiService.getUser();
userList.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, final Response<List<User>> response) {
Completable.fromAction(new Action() {
#Override
public void run() throws Exception {
if(response.body() != null) {
List<User> list = response.body();
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).get_id();
String names = list.get(i).getName();
String age = list.get(i).getAge();
User user = new User(id,names,age);
userDb.userDao().Insert(user);
}
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new CompletableObserver() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onComplete() {
Toast.makeText(context,"Data inserted",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Throwable e) {
Toast.makeText(context,e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
Method fetching list is in another class UserRepository and I am calling method in another activity MainActivity.I am not getting any way how can I stop refreshing process.Someone please let me know a way to stop refreshing process.
Any help would be appreciated.
THANKS
To disable the progress dialog add this,
swipeLayout.setRefreshing(false);
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();
}
});