Получаю данные из json
и записываю их в БД Realm
, как мне их потом передать в RecyclerView
?
Feed.java
public class Feed extends Fragment {
private final String TAG = "log_tag";
private Realm realm;
private RealmResults<Article> art;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.feed_recycler_view, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
ResponseColumn();
}
});
Realm.init(getActivity());
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(config);
ResponseColumn();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new RecyclerViewAdapter(art)); //в этой строке показывает ошибку
return view;
}
private void ResponseColumn() {
Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaredClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}).create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://newsapi.org/v1/articles/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
EngadgetAPI engadgetAPI = retrofit.create(EngadgetAPI.class);
Call<EngadgetArticle> call = engadgetAPI.getArticle();
call.enqueue(new Callback<EngadgetArticle>() {
@Override
public void onResponse(Call<EngadgetArticle> call, Response<EngadgetArticle> response) {
realm = Realm.getDefaultInstance();
realm.beginTransaction();
//realm.deleteAll();
List<Article> article = realm.copyToRealmOrUpdate(response.body().getArticles());
realm.commitTransaction();
art = realm.where(Article.class).findAll();
Log.d(TAG, "onResponse: article = " + article.size());
Log.d(TAG, "onResponse: realm size = " + art.size());
Log.d(TAG, "onResponse: " + response.message());
}
@Override
public void onFailure(Call<EngadgetArticle> call, Throwable t) {
Log.d(TAG, "onFailure: " + t.getMessage());
}
});
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements RealmChangeListener<RealmResults<Article>> {
private final RealmResults<Article> articles;
public RecyclerViewAdapter(RealmResults<Article> articles) {
this.articles = articles;
this.articles.addChangeListener(this);//здесь тоже показывает ошибку
}
@Override
public void onChange(RealmResults<Article> element) {
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cardView;
ImageView imageView;
TextView tvTitle;
TextView tvDescription;
TextView tvPublished;
ViewHolder(View view) {
super(view);
cardView = (CardView) view.findViewById(R.id.card_view);
imageView = (ImageView) view.findViewById(R.id.imageView);
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
tvDescription = (TextView) view.findViewById(R.id.tvDescription);
tvPublished = (TextView) view.findViewById(R.id.tvPublished);
}
@Override
public void onClick(View view) {
}
}
@Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.tvTitle.setText(articles.get(position).getTitle());
holder.tvDescription.setText(articles.get(position).getDescription());
holder.tvPublished.setText(articles.get(position).getPublishedAt());
Picasso.with(holder.cardView.getContext())
.load(articles.get(position).getUrlToImage())
.error(android.R.drawable.ic_menu_report_image)
.into(holder.imageView);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
@Override
public int getItemCount() {
return articles.size();
}
}
UPD ошибка
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nikolai.engadgetnews, PID: 900
java.lang.NullPointerException: Attempt to invoke virtual method 'int io.realm.RealmResults.size()' on a null object reference
at com.example.nikolai.engadgetnews.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:85)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3416)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3252)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:636)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1167)
at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:852)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:871)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678)
at android.view.View.layout(View.java:16630)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.an
База данных Realm имеет свой собственный адаптер для RecyclerView
/ На вход адаптер принимает непосредственно выборку из БД - колллекцию класса OrderedRealmCollection
- абстрактный класс, реализации которого RealmResults
или RealmList
.
для импорта класса адаптера добавляем в файл build.gradle на уровене приложения следующее:
dependencies {
compile 'io.realm:android-adapters:1.4.0'
}
далее используем адаптер (без реализации переопределяемых методов адаптера для RecyclerView
):
class MyRealmAdapter extends RealmRecyclerViewAdapter<Data, MyRealmAdapter.MyViewHolder> {
private OrderedRealmCollection<Data> mData;
public MyRealmAdapter (OrderedRealmCollection<Data> data) {
super(data, true); //второй аргумент - флаг автообновления списка с обновлением данных.
mData = data;
}
class MyViewHolder extends RecyclerView.ViewHolder{
public MyViewHolder(View view) {
super(view);
}
}
Где Data - выборка из БД, объект типа RealmResults
или RealmList
PS: так же API Realm имеет методы для прямого преобразования JSON в записи БД RealmObject
- createObjectFromJson()
и createAllFromJson()
. Сама Realm проделает эту операцию быстрее, чем ваш кустарный способ.
Айфон мало держит заряд, разбираемся с проблемой вместе с AppLab
Перевод документов на английский язык: Важность и ключевые аспекты
Необходимо скопировать первую страницу pdf файла в word файл(doc,docx) с помощью ЯП Java
Доброго времени суток! Пишу программу похожую на MSPaint для проектаВот ссылка на репозиторий с полным проектом -> https://github
Здравствуйте, коллегиПытаюсь решить задачу, но, как всегда, мешает отсутствие опыта
Почему выводит результат true,false,false,true,true? По какой логике? Я так понимаю, if (example[i]) означает, что если данный элемент равен любому значению,...