Android import Transformer for using that for Loader - android

in this link i read that to using RxJava on phone rotation and save state, but i have simple problem on import Transformer on this class:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import org.reactivestreams.Subscription;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;
public class RxLoader<T> extends Loader<T> {
private final Observable<T> observable;
private final BehaviorSubject<T> cache = BehaviorSubject.create();
private Subscription subscription;
private RxLoader(Context context, Observable<T> observable) {
super(context);
this.observable = observable;
}
public static <T> Observable.Transformer<T, T> compose(AppCompatActivity activity, int id) {
return observable -> create(activity, id, observable);
}
public static <T> Observable<T> create(AppCompatActivity activity, int id,
Observable<T> observable) {
LoaderManager loaderManager = activity.getSupportLoaderManager();
CreateLoaderCallback<T> createLoaderCallback =
new CreateLoaderCallback<>(activity, observable);
loaderManager.initLoader(id, null, createLoaderCallback);
RxLoader<T> rxLoader = (RxLoader<T>) loaderManager.getLoader(id);
return rxLoader.cache.asObservable();
}
#Override
protected void onStartLoading() {
super.onStartLoading();
subscription = observable.subscribe(cache::onNext);
}
#Override
protected void onReset() {
super.onReset();
subscription.unsubscribe();
}
private static class CreateLoaderCallback<T>
implements LoaderManager.LoaderCallbacks<T> {
private final Context context;
private final Observable<T> observable;
public CreateLoaderCallback(Context context, Observable<T> observable) {
this.context = context;
this.observable = observable;
}
#Override
public Loader<T> onCreateLoader(int id, Bundle args) {
return new RxLoader<>(context, observable);
}
#Override
public void onLoadFinished(Loader<T> loader, T data) { }
#Override
public void onLoaderReset(Loader<T> loader) { }
}
}
problem is in this part of class:
public static <T> Observable.Transformer<T, T> compose( ...

The code you have imported most possibly is implemented with RxJava 1.
You have two options:
Import RxJava 1 instead of RxJava 2
Convert existing code to RxJava 2's ObserverTransformer

Related

How to make NEW Networking Calls in MVVM?

I'm trying to implement pull to refresh with MVVM (and a recyclerview) yet I don't understand how I'm supposed to fetch new data. Inital load up of the app is fine as I'm just observing the livedata from the view model when it's created, but how do I query for more data?
MainActivity.java
package com.example.simplenews;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.simplenews.adapters.NewsArticleAdapter;
import com.example.simplenews.adapters.RecyclerItemClickListener;
import com.example.simplenews.models.Article;
import com.example.simplenews.models.NewsResponse;
import com.example.simplenews.repositories.NewsAPI;
import com.example.simplenews.repositories.NewsRepository;
import com.example.simplenews.viewmodels.NewsViewModel;
import com.victor.loading.rotate.RotateLoading;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import timber.log.Timber;
public class MainActivity extends AppCompatActivity {
private RecyclerView newsRecyclerView;
private NewsArticleAdapter newsAdapter;
private NewsAPI NewsAPI;
private ArrayList<Article> newsArticles = new ArrayList<>();
private RotateLoading rotateLoadingIndicator;
private SwipeRefreshLayout swipeRefreshLayout;
private NewsViewModel newsViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Planting timber debug tree here because this joint refuses to work when planted in the application class
Timber.plant(new Timber.DebugTree());
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
newsRecyclerView = findViewById(R.id.newsRecyclerView);
rotateLoadingIndicator = findViewById(R.id.rotate_loading_indicator);
// Getting and setting up the viewmodel
newsViewModel = new ViewModelProvider(this).get(NewsViewModel.class);
newsViewModel.initNewsViewModel();
// Setting up the observer
newsViewModel.getNewsRepositoryQuery().observe(this, newsResponse -> {
ArrayList<Article> freshNewsArticles = (ArrayList<Article>) newsResponse.getArticles();
newsArticles.addAll(freshNewsArticles);
newsAdapter.notifyDataSetChanged();
});
initReyclerView();
// This is not the way to do recyclerview click listeners but this will suffice for now
newsRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, newsRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Article article = newsArticles.get(position);
Uri uri = Uri.parse(article.getUrl());
Intent webIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(webIntent);
}
#Override
public void onLongItemClick(View view, int position) {
}
})
);
// Configure the refreshing colors
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
newsViewModel.getNewHeadlines().observe(MainActivity.this, new Observer<NewsResponse>() {
#Override
public void onChanged(NewsResponse newsResponse) {
if (newsResponse.getArticles() != null) {
refreshNewsRecyclerView(newsResponse.getArticles());
swipeRefreshLayout.setRefreshing(false);
}
swipeRefreshLayout.setRefreshing(false);
Timber.d("the articles in the refresh callback were null");
}
});
}
});
}
/*
* Helper method that refreshes topHeadlinesRecyclerView with new articles
* #param: list of new article objects from a network request
* */
private void refreshNewsRecyclerView(List<Article> freshArticles) {
newsRecyclerView.setVisibility(View.INVISIBLE);
showLoadingIndicator();
newsAdapter.clearNewsArticles();
newsAdapter.addAll(freshArticles);
newsRecyclerView.setVisibility(View.VISIBLE);
hideLoadingIndicator();
newsAdapter.notifyDataSetChanged();
}
/*
* Helper method to show the loading indicator
* */
private void showLoadingIndicator() {
rotateLoadingIndicator.setVisibility(View.VISIBLE);
rotateLoadingIndicator.start();
}
/*
* Helper method to hide loading indicator
* */
private void hideLoadingIndicator() {
rotateLoadingIndicator.stop();
rotateLoadingIndicator.setVisibility(View.GONE);
}
/*
* Helper method to setup the recyclerView
* */
private void initReyclerView() {
if (newsAdapter == null) {
showLoadingIndicator();
newsAdapter = new NewsArticleAdapter(newsArticles, this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
newsRecyclerView.setLayoutManager(layoutManager);
newsRecyclerView.setAdapter(newsAdapter);
hideLoadingIndicator();
} else {
newsAdapter.notifyDataSetChanged();
}
}
}
NewsViewModel
public class NewsViewModel extends ViewModel {
private MutableLiveData<NewsResponse> mutableLiveData;
private NewsRepository newsRepository;
// When a viewmodel object is created fetch the data needed for the activitiy
public void initNewsViewModel() {
if (mutableLiveData != null) {
return;
}
newsRepository = NewsRepository.getInstance();
mutableLiveData = newsRepository.getTopHeadlines();
}
public MutableLiveData<NewsResponse> getNewsRepositoryQuery() {
return mutableLiveData;
}
public MutableLiveData<NewsResponse> getNewHeadlines() {
MutableLiveData<NewsResponse> response = newsRepository.getTopHeadlines();
return response;
}
}
News Repository
public class NewsRepository {
private static NewsRepository newsRepository;
private NewsAPI newsAPI;
private List<Article> freshArticles;
public static NewsRepository getInstance() {
if (newsRepository == null) {
newsRepository = new NewsRepository();
}
return newsRepository;
}
/*
* Private constructor because nobody should be creating this object direcly
* */
private NewsRepository() {
newsAPI = RetrofitClient.getRetrofitInstance().create(NewsAPI.class);
}
public MutableLiveData<NewsResponse> getTopHeadlines() {
MutableLiveData<NewsResponse> topHeadlines = new MutableLiveData<>();
newsAPI.getRootJSONObject().enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
if (response.isSuccessful()) {
topHeadlines.setValue(response.body());
Timber.d("Network call was succesful here is the response code " + response.code());
} else {
Timber.d("Network call was unsuccesful " + response.code());
}
}
#Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
Timber.d("Network call completely failed lol");
topHeadlines.setValue(null);
}
});
return topHeadlines;
}
}
You can simply make a function which reset value of MutableLiveData
For example on swipe call viewmodel.resetNewsHeadlines() and in resetNewsHeadlines() method simple set value to null and recall mutableLiveData = newsRepository.getTopHeadlines(); again

Which is the correct LifeCycleOwner to be used to observe LiveData in AppWidgetProvider

I need to observe some LiveData in AppWidgetProvider (During onUpdate). I was wondering, which of the following is a more appropriate LifeCycleObserver to be used?
ForeverStartLifecycleOwner (Custom)
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.support.annotation.NonNull;
public enum ForeverStartLifecycleOwner implements LifecycleOwner {
INSTANCE;
private final LifecycleRegistry mLifecycleRegistry;
ForeverStartLifecycleOwner() {
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
#NonNull
#Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
Or, should I use ProcessLifecycleOwner.get()?
Both works fine. But, which one is more appropriate?
Finally, I stick with the following solution. It works fine so far as I don't see any live crash report, or receiving complains from customers. However, if you know a better way, please let me know.
ForeverStartLifecycleOwner
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.support.annotation.NonNull;
public enum ForeverStartLifecycleOwner implements LifecycleOwner {
INSTANCE;
private final LifecycleRegistry mLifecycleRegistry;
ForeverStartLifecycleOwner() {
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
#NonNull
#Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
Usage
public static <T> void ready(LiveData<T> liveData, LifecycleOwner lifecycleOwner, Callable<T> callable) {
T t = liveData.getValue();
if (t != null) {
callable.call(t);
return;
}
liveData.observe(lifecycleOwner, new Observer<T>() {
#Override
public void onChanged(#Nullable T t) {
liveData.removeObserver(this);
callable.call(t);
}
});
}
public static void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
MediatorLiveData<Result> resultLiveData = getResultLiveData(appWidgetId);
ready(resultLiveData, ForeverStartLifecycleOwner.INSTANCE, result -> onUpdate(context, appWidgetManager, result.stickyNoteConfig, result.note));
}

How do I use dagger inject with Mockito?

I am trying to write unit tests for Android app that uses dagger for ViewModel injection. I don't seem to get injection working for the JUnitTest. Retrofit is returning null call request when I inject the gapiService using #Mock here:
final MutableLiveData<GissuesResponse> lData = new MutableLiveData<>();
Call<List<Issue>> callRequest = gapiService.getIssues(owner, repo);
My whole project is at http://github.com/CodingWords/Gissues
Not sure how to properly setup the ViewModel for injection in JUnitTest. Thanks!
Here is my JUnitTest
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import com.codingwords.sobrien.gissues.api.GAPIService;
import com.codingwords.sobrien.gissues.model.SearchIssuesModel;
import com.codingwords.sobrien.gissues.repo.IssueRepository;
import com.codingwords.sobrien.gissues.vm.GissuesViewModel;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import javax.inject.Inject;
public class GissuesUnitTest {
#Mock //Mock annotation tells Mockito to give a mocked object
GissuesScreen gissuesScreen;
#Mock
GAPIService gapiService;
//class that is being tested
#Inject
ViewModelProvider.Factory viewModelFactory;
IssueRepository gissuesRepo;
GissuesViewModel gissuesViewModel;
final String dummyOwner = "ethereum";
final String dummyRepo = "solidity";
#Before
public void setupGissuesViewModel(){
//this function will be called before all tests are run
// call this function to init all objects annotated with #mock
MockitoAnnotations.initMocks(this);
gissuesRepo = new IssueRepository();
gissuesRepo.setGapiService(gapiService);
gissuesViewModel = new GissuesViewModel(gissuesRepo);
gissuesViewModel.setGissuesScreen(gissuesScreen);
SearchIssuesModel sim = new SearchIssuesModel();
gissuesViewModel.setSearchModel(sim);
//we create an instance of the class to be tested by passing the mocked objec
}
#Test
public void requestIssuesWithEmptyOwner_showsOwnerError(){
gissuesViewModel.getSearchModel().setOwner("");
gissuesViewModel.pullIssues();
//use mockito to verify that the showOwnerError() method is called in the screen object
Mockito.verify(gissuesScreen).showOwnerError();
}
#Test
public void requestIssuesWithEmptyRepo_showsRepoError(){
gissuesViewModel.getSearchModel().setOwner("ethereum");
gissuesViewModel.getSearchModel().setRepo("");
gissuesViewModel.pullIssues();
Mockito.verify(gissuesScreen).showRepoError();
}
#Test
public void requestIssuesWithEmptyList_showsIssuesNotFound(){
gissuesViewModel.getSearchModel().setOwner("ethereum");
gissuesViewModel.getSearchModel().setRepo("ethereum");
gissuesViewModel.pullIssues();
Mockito.verify(gissuesScreen).showIssuesNotFound();
}
}
Here is IssueRepo
public class IssueRepository implements IssueRepo {
#Inject
public IssueRepository() {
}
#Inject
GAPIService gapiService;
#Override
public LiveData<GissuesResponse> receiveIssues(String owner, String repo) {
final MutableLiveData<GissuesResponse> lData = new MutableLiveData<>();
// callRequest is returned as null because gapiService was mock object?
Call<List<Issue>> callRequest = gapiService.getIssues(owner, repo);
callRequest.enqueue(new Callback<List<Issue>>() {
#Override
public void onResponse(Call<List<Issue>> call, Response<List<Issue>> response) {
lData.setValue(new GissuesResponse(response.body()));
}
#Override
public void onFailure(Call<List<Issue>> call, Throwable t) {
lData.setValue(new GissuesResponse(t));
}
});
return lData;
}
public GAPIService getGapiService() {
return gapiService;
}
public void setGapiService(GAPIService gapiService) {
this.gapiService = gapiService;
}
}
Here is View Model
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MediatorLiveData;
import android.arch.lifecycle.ViewModel;
import android.support.annotation.NonNull;
import com.codingwords.sobrien.gissues.GissuesScreen;
import com.codingwords.sobrien.gissues.entity.GissuesResponse;
import com.codingwords.sobrien.gissues.model.SearchIssuesModel;
import com.codingwords.sobrien.gissues.repo.IssueRepo;
import javax.inject.Inject;
/**
* Created by Administrator on 2/19/2018.
*/
public class GissuesViewModel extends ViewModel {
private IssueRepo issueRepository;
private MediatorLiveData<GissuesResponse> gapiResponse;
private SearchIssuesModel searchModel;
private GissuesScreen gissuesScreen;
#Inject
public GissuesViewModel(IssueRepo repository) {
this.issueRepository = repository;
this.gapiResponse = new MediatorLiveData<GissuesResponse>();
}
public MediatorLiveData<GissuesResponse> getGapiResponse() {
return gapiResponse;
}
public void pullIssues(){
if (getSearchModel() != null){
if ((getSearchModel().getOwner() == null) || (getSearchModel().getOwner().length() < 2)){
gissuesScreen.showOwnerError();
} else if ((getSearchModel().getRepo() == null) || (getSearchModel().getRepo().length() < 2)) {
gissuesScreen.showRepoError();
} else {
pullIssues(getSearchModel().getOwner(), getSearchModel().getRepo());
}
}
}
public void pullIssues(#NonNull String user, String repo) {
LiveData<GissuesResponse> issuesSource = issueRepository.receiveIssues(user, repo);
gapiResponse.addSource(
issuesSource,
gapiResponse -> {
if (this.gapiResponse.hasActiveObservers()) {
this.gapiResponse.removeSource(issuesSource);
}
this.gapiResponse.setValue(gapiResponse);
}
);
}
public SearchIssuesModel getSearchModel() {
return searchModel;
}
public void setSearchModel(SearchIssuesModel searchModel) {
this.searchModel = searchModel;
}
public GissuesScreen getGissuesScreen() {
return gissuesScreen;
}
public void setGissuesScreen(GissuesScreen gissuesScreen) {
this.gissuesScreen = gissuesScreen;
}
}

Is there a method that executes after Observable's onSuccess() or onError()?

It is very often that I need to show some loading behavior in my app and I want to dismiss it once the work is done - no matter if the result of the work is success or an error. Therefore, I end up with code like that:
addDisposable(router.launchHomepage()
.compose(loadingView.show()))
.subscribe(
{ loadingView.dismiss() },
{ loadingView.dismiss() }
)
)
Is there a way to dismiss the loading view in a single method? Like onComplete() but called no matter if the result is success or error?
create class
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import io.reactivex.FlowableTransformer;
import io.reactivex.ObservableTransformer;
import io.reactivex.SingleTransformer;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
public class RxShowDialogUtil {
private ProgressDialog dialog;
private final Context context;
private final Consumer SUBSCRIBE_ACTION = new Consumer() {
#Override
public void accept(#NonNull Object o) throws Exception {
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
}
};
private final Action UN_SUBSCRIBE_ACTION = new Action() {
#Override
public void run() throws Exception {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = null;
}
};
private RxShowDialogUtil(Context context) {
this.context = context;
}
public static RxShowDialogUtil createInstance(Context context) {
return new RxShowDialogUtil(context);
}
public static RxShowDialogUtil createInstance(Fragment fragment) {
return new RxShowDialogUtil(fragment.getActivity());
}
public <T> SingleTransformer<T, T> applyDialogForSingle() {
createDialog(context);
return upstream -> upstream.doOnSubscribe(SUBSCRIBE_ACTION).doFinally(UN_SUBSCRIBE_ACTION);
}
public <T> ObservableTransformer<T, T> applyDialogForObservable() {
createDialog(context);
return upstream -> upstream.doOnSubscribe(SUBSCRIBE_ACTION).doFinally(UN_SUBSCRIBE_ACTION);
}
public <T>FlowableTransformer<T,T> applyDialogForFlowable(){
createDialog(context);
return upstream -> upstream.doOnSubscribe(SUBSCRIBE_ACTION).doFinally(UN_SUBSCRIBE_ACTION);
}
private Dialog createDialog(final Context context) {
if (dialog == null) {
dialog = DialogUtils.getInstance().getProgressDialog(context);
}
return dialog;
}
}
And Use
addDisposable(router.launchHomepage()
.compose(RxShowDialogUtil.createInstance(this).applyDialogForObservable())
.subscribe(
{ },
{ }
)
)

How to load data from json in expandable listview using retrofit?

I want to load question and answer in expandable listview from json using retrofit library. I dont know how to do this. Find me a solution.
Here is the two model class i am using.
public class QuestionResult {
boolean IsSuccess;
List<QuestionsModel> question;
public boolean isSuccess() {
return IsSuccess;
}
public List<QuestionsModel> getQuestion() {
return question;
}
}
And
public class QuestionsModel {
private int q_id;
private int category_id;
private String question;
private String answer;
public int getQ_id() {
return q_id;
}
public int getCategory_id() {
return category_id;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
}
Here is my Activity
public class QuestionBank extends AppCompatActivity {
#InjectView(R.id.ques_type_spinner)
Spinner courseSpinner;
#InjectView(R.id.home_btn_qbank)
Button homeButton;
#InjectView(R.id.no_questions)
TextView textView;
#InjectView(R.id.ques_ans_listview)
ExpandableListView listView;
List<String> courseNames;
ArrayAdapter<String> courseAdapter;
ExpandableListAdapter listAdapter;
List<QuestionResult> resultList;
ProgressDialog progress;
int selectedPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_bank);
ButterKnife.inject(this);
StatusBarTheme.setStatusBarColor(this);
showCourseCategory();
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
courseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedPosition = courseSpinner.getSelectedItemPosition() + 1;
Log.d("cat_id ", " " + selectedPosition);
loadQuestions(selectedPosition);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void loadQuestions(final int selectedPosition) {
ApiInterface apiInterface = ApiClient.getClient(this).create(ApiInterface.class);
Call<QuestionResult> call = apiInterface.loadQuesAndAnswers(selectedPosition);
call.enqueue(new Callback<QuestionResult>() {
#Override
public void onResponse(Call<QuestionResult> call, Response<QuestionResult> response) {
List<QuestionsModel> questionsModelList = response.body().getQuestion();
if (questionsModelList != null) {
listAdapter = new ExpandListAdapter(QuestionBank.this, questionsModelList, selectedPosition);
listView.setAdapter(listAdapter);
} else {
listView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
}
}
#Override
public void onFailure(Call<QuestionResult> call, Throwable t) {
}
});
}
private void showCourseCategory() {
ApiInterface apiInterface = ApiClient.getClient(this).create(ApiInterface.class);
Call<CategoryResult> call = apiInterface.loadCourseTitle();
progress = new ProgressDialog(QuestionBank.this);
progress.setMessage("Loading.. Please wait");
progress.show();
call.enqueue(new Callback<CategoryResult>() {
#Override
public void onResponse(Call<CategoryResult> call, Response<CategoryResult> response) {
if (progress.isShowing()) {
progress.dismiss();
}
if (response.body().isSuccess() && response.body().getCategory() != null) {
response.body().getCategory();
courseNames = new ArrayList<>();
for (CourseType courseType : response.body().getCategory()) {
courseNames.add(courseType.getCategory_title());
}
loadSpinner(courseNames);
}
}
#Override
public void onFailure(Call<CategoryResult> call, Throwable t) {
}
});
}
private void loadSpinner(List<String> educationTypeList) {
courseAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, educationTypeList);
courseAdapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
courseSpinner.setAdapter(courseAdapter);
}
}
Here is the complete code. Change it for your purposes. If anything will happen you can write comment i will answer.
Application.class
public class Application extends Application{
private static Application instance;
private I_Requests iWebEndpoint;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static Application i() {
return instance;
}
public I_Requests w() {
if(this.iWebEndpoint == null){
initRetrofit();
}
return iWebEndpoint;
}
private void initRetrofit(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient
.Builder()
.addInterceptor(interceptor)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.connectTimeout(1, TimeUnit.MINUTES)
.build();
client.readTimeoutMillis();
this.iWebEndpoint = new Retrofit.Builder()
.baseUrl(I_Requests.address)
.client(client)
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(I_Requests.class);
}
}
JacksonConverterFactory.class
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* A {#linkplain Converter.Factory converter} which uses Jackson.
* <p>
* Because Jackson is so flexible in the types it supports, this converter assumes that it can
* handle all types. If you are mixing JSON serialization with something else (such as protocol
* buffers), you must {#linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add this
* instance} last to allow the other converters a chance to see their types.
*/
public final class JacksonConverterFactory extends Converter.Factory {
/** Create an instance using a default {#link ObjectMapper} instance for conversion. */
public static JacksonConverterFactory create() {
return create(new ObjectMapper());
}
/** Create an instance using {#code mapper} for conversion. */
public static JacksonConverterFactory create(ObjectMapper mapper) {
return new JacksonConverterFactory(mapper);
}
private final ObjectMapper mapper;
private JacksonConverterFactory(ObjectMapper mapper) {
if (mapper == null) throw new NullPointerException("mapper == null");
this.mapper = mapper;
}
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
JavaType javaType = mapper.getTypeFactory().constructType(type);
ObjectReader reader = mapper.reader(javaType);
return new JacksonResponseBodyConverter<>(reader);
}
#Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
JavaType javaType = mapper.getTypeFactory().constructType(type);
ObjectWriter writer = mapper.writerWithType(javaType);
return new JacksonRequestBodyConverter<>(writer);
}
}
JacksonRequestBodyConverter.class
import com.fasterxml.jackson.databind.ObjectWriter;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;
final class JacksonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private final ObjectWriter adapter;
JacksonRequestBodyConverter(ObjectWriter adapter) {
this.adapter = adapter;
}
#Override public RequestBody convert(T value) throws IOException {
byte[] bytes = adapter.writeValueAsBytes(value);
return RequestBody.create(MEDIA_TYPE, bytes);
}
}
JacksonResponseBodyConverter.class
import com.fasterxml.jackson.databind.ObjectReader;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter;
final class JacksonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final ObjectReader adapter;
JacksonResponseBodyConverter(ObjectReader adapter) {
this.adapter = adapter;
}
#Override public T convert(ResponseBody value) throws IOException {
try {
return adapter.readValue(value.charStream());
} finally {
value.close();
}
}
}
I_Request.interface
import java.util.ArrayList;
import manqaro.com.projectz.ServerSide.Response.TestData;
import manqaro.com.projectz.ServerSide.Response.TestResponse;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface I_Requests {
//PUT HERE YOUR SERVER MAIN ADDRES
String address = "http://goto.xcodes.club";
//SAMPLE EXAMPLE OF POST TYPE , YOU SHOULD CHANGE EVERYTHING YOU WANT.
//IN THIS EXAMPLE YOU WILL GET JSON DATA WHICH WILL BE CONVERTED TO JAVA OBJECT.
#FormUrlEncoded
//Here YOU HAVE TO GIVE ADDRESS TO SPECIFIC CALL
#GET("/api/v1/objects/")
Call<TestResponse<ArrayList<TestData>>> login(
);
#FormUrlEncoded
#POST("/api/v1/objects/")
Call<TestResponse<ArrayList<TestData>>> register(
);
}
TestResponse.class
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by ArsenSench on 11/9/2016.
*/
public class TestResponse<T> {
#JsonProperty("status")
public int status;
#JsonProperty("message")
public String message;
#JsonProperty("data")
public T data;
}
TestData.class
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by ArsenSench on 11/9/2016.
*/
public class TestData extends {
#JsonProperty("id")
public int id;
#JsonProperty("name")
public String name;
#JsonProperty("description")
public String description;
#JsonProperty("avatar")
public String avatar;
#JsonProperty("rate")
public int rate;
}
ServerCalls.class
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import manqaro.com.projectz.ServerSide.Application.Tickle_Application;
import manqaro.com.projectz.ServerSide.Response.TestData;
import manqaro.com.projectz.ServerSide.Response.TestResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by ArsenSench on 11/9/2016.
*/
public class ServerCalls {
Context context;
public ServerCalls(Context context){
this.context = context;
}
public void testCallBack(){
Tickle_Application.i().w().login().enqueue(new Callback<TestResponse<ArrayList<TestData>>>() {
#Override
public void onResponse(Call<TestResponse<ArrayList<TestData>>> call, Response<TestResponse<ArrayList<TestData>>> response) {
if(response.code()==200){
if(response.body().status==200){
Toast.makeText(context, response.body().data.get(0).name, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "No Name", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(context, "No Connection", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<TestResponse<ArrayList<TestData>>> call, Throwable t) {
Toast.makeText(context, t.getCause().getMessage(), Toast.LENGTH_SHORT).show();
Log.e("jex", "onFailure: " + t.getCause().getMessage() );
}
});
}
}
TestActivity.activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import manqaro.com.projectz.R;
import manqaro.com.projectz.ServerSide.Main.ServerCalls;
public class TestActivity extends AppCompatActivity {
ServerCalls sc = new ServerCalls(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
public void clickThatShit(View view){
sc.testCallBack();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="your.package.name">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".Application"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon">
<activity
android:name=".TestActivity">
</activity>
</application>
</manifest>
build.gradle(module app)
Include these dependencies in yourdependencies
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
Include this lines in your android{} block
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
}

Categories

Resources