Как в андроид реализовать обновление страницы?
Прочитал статью, что можно через SwipeRefreshLayout, сделал все как по инструкции, но почему-то программа завершается, в Logcat ничего не пишется (первый раз такое вижу).
Разметка:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="true"
android:orientation="vertical"
tools:context=".fragments.HomeFragment">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipeRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="UselessParent">
<TextView
android:id="@+id/textWelcome"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textColor="@color/black"
android:textSize="20sp"
android:layout_marginVertical="10dp"
android:layout_marginHorizontal="10dp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/news_recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/gray_white"
tools:itemCount="1"
tools:listitem="@layout/item_news_cardview" />
</LinearLayout>
</ScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
Код HomeFragment:
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
View view;
RecyclerView recyclerView;
TextView welcomeText;
private SwipeRefreshLayout mSwipeRefresh;
ArrayList<String> img_ns = new ArrayList<>();
String nowTime = new SimpleDateFormat("HH", Locale.getDefault()).format(new Date());
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_home, container, false);
welcomeText = view.findViewById(R.id.textWelcome);
if ((Integer.parseInt(nowTime) >= 4) && (Integer.parseInt(nowTime) < 12)) {
welcomeText.setText("Доброе утро!");
} else if ((Integer.parseInt(nowTime) >= 12) && (Integer.parseInt(nowTime) < 18)) {
welcomeText.setText("Добрый день!");
} else if ((Integer.parseInt(nowTime) >= 18) && (Integer.parseInt(nowTime) < 24)) {
welcomeText.setText("Добрый вечер!");
} else welcomeText.setText("Доброй ночи!");
NewsRecyclerView(container);
return view;
}
public void NewsRecyclerView(@NonNull ViewGroup container) {
recyclerView = view.findViewById(R.id.news_recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(container.getContext().getApplicationContext());
linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
recyclerView.setLayoutManager(linearLayoutManager);
JSONObject jsonObject;
try {
jsonObject = new JSONObject(Objects.requireNonNull(JsonDataFromAsset("exampleNews.json")));
JSONArray jsonArray = jsonObject.getJSONArray("exampleNews");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject userData = jsonArray.getJSONObject(i);
img_ns.add(userData.getString("image_news"));
}
} catch (JSONException e) {
e.printStackTrace();
}
NewsAdapter newsAdapter = new NewsAdapter(img_ns, HomeFragment.this.getContext());
recyclerView.setAdapter(newsAdapter);
}
@Nullable
private String JsonDataFromAsset(String fileName) {
String json;
try {
InputStream inputStream = requireContext().getAssets().open(fileName);
int sizeOfFile = inputStream.available();
byte[] bufferData = new byte[sizeOfFile];
inputStream.read(bufferData);
inputStream.close();
json = new String(bufferData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSwipeRefresh = view.findViewById(R.id.swipeRefresh);
//Настраиваем выполнение OnRefreshListener для данной activity:
mSwipeRefresh.setOnRefreshListener(this);
}
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override public void run() {
//Останавливаем обновление:
mSwipeRefresh.setRefreshing(false)
;}}, 5000);
}
}
ОБНОВЛЕНИЕ: Обновил вот эту часть кода и все заработало, единственное обновление идет бесконечно) Кака его остановить? onRefresh почему-то не работает
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new SwipeRefreshLayout(this.requireContext());
}