Итак, у меня есть этот проект для java android, и я все перепробовал. Буквально я прочитал все темы об этом и перепробовал все, но, кажется, ничего не работает. Элементы в RecyclerView просто не будут отображаться.
Я скоро создаю компанию. Если вы сможете решить эту проблему, я буду заинтересован в найме ваших услуг в будущем.
Итак, вот мой код:
Активность:
package com.android.neto.myproject.activity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
import android.widget.SearchView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.android.neto.myproject.R;
import com.android.neto.myproject.config.FirebaseConfig;
import com.android.neto.myproject.fragment.UserInterestsFragment;
import com.android.neto.myproject.fragment.UserAppointmentsFragment;
import com.android.neto.myproject.fragment.UserFriendsFragment;
import com.android.neto.myproject.model.User;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class UserActivity extends AppCompatActivity {
private User user;
private BottomNavigationView navView;
private SearchManager searchManager;
private SearchView search;
private Fragment currentFragment;
private int currentNavigation;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
user = (User)getIntent().getSerializableExtra("user");
initializeComponents();
}
@Override
protected void onStart() {
super.onStart();
}
private void initializeComponents() {
progressBar = findViewById(R.id.progressBar);
navView = findViewById(R.id.nav_view);
currentNavigation = R.id.navigation_user_friends;
currentFragment = new UserFriendsFragment();
loadFragment();
setTitle(R.string.title_user_friends);
navView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override public boolean onNavigationItemSelected(@NonNull MenuItem item) {
if (!search.getQuery().toString().isEmpty()) {
search.setQuery("", false);
if (!search.isIconified()) {
search.setIconified(true);
} else {
UserActivity.super.onBackPressed();
}
} else {
search.setIconified(true);
}
currentNavigation = item.getItemId();
switch (currentNavigation) {
case R.id.navigation_user_friends:
setTitle(R.string.title_user_friends);
currentFragment = new UserFriendsFragment();
break;
case R.id.navigation_user_interests:
setTitle(R.string.title_user_interests);
currentFragment = new UserInterestsFragment();
break;
case R.id.navigation_user_appointments:
setTitle(R.string.title_user_appointments);
currentFragment = new UserAppointmentsFragment();
break;
}
return loadFragment();
}});
}
private boolean loadFragment() {
if (currentFragment != null) {
Bundle bundle = new Bundle();
bundle.putSerializable("user", user);
currentFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction();
fragmentTransaction
.replace(R.id.nav_host_fragment, currentFragment)
.commit();
return true;
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_user, menu);
searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) menu.findItem(R.id.searchBar).getActionView();
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (currentFragment != null) {
switch (currentNavigation) {
case R.id.navigation_user_friends:
break;
}
}
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.signOut:
FirebaseConfig.getAuth().signOut();
finish();
break;
case R.id.update:
notifyDatasetChanged();
break;
}
return super.onOptionsItemSelected(item);
}
public void notifyDatasetChanged() {
if (currentFragment != null) {
switch (currentNavigation) {
case R.id.navigation_user_friends:
runOnUiThread(new Runnable() {
@Override public void run() {
RecyclerView friendsRecyclerView = currentFragment
.getView().findViewById(R.id.friendsRecyclerView);
friendsRecyclerView.getAdapter().notifyDataSetChanged();
}});
break;
case R.id.navigation_user_interests:
break;
case R.id.navigation_user_appointments:
break;
}
}
}
@Override
public void onBackPressed() {
}
}
Фрагмент
package com.android.neto.myproject.fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.neto.myproject.DAO.FriendDAO;
import com.android.neto.myproject.R;
import com.android.neto.myproject.activity.UserActivity;
import com.android.neto.myproject.adapter.UserFriendsRecyclerViewAdapter;
import com.android.neto.myproject.config.FirebaseConfig;
import com.android.neto.myproject.model.Hobby;
import com.android.neto.myproject.model.Friend;
import com.android.neto.myproject.model.User;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class UserFriendsFragment extends Fragment {
private View root;
private UserActivity userActivity;
private User user;
private List<Hobby> hobbys;
private List<Friend> friends;
private String search = "";
private RecyclerView friendsRecyclerView;
private UserFriendsRecyclerViewAdapter userFriendsRecyclerViewAdapter;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@SuppressLint("StaticFieldLeak")
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_user_friends, null);
user = (User)this.getArguments().getSerializable("user");
hobbys = new ArrayList<>();
friends = new ArrayList<>();
initializeComponents();
searchHobbys(new AsyncTask<Void, Void, Void>() {
@Override protected Void doInBackground(Void... voids) {
searchFriends(new AsyncTask<Void, Void, Void>() {
@Override protected Void doInBackground(Void... voids) {
Log.d("Friends", String.valueOf(friends.size()));
Log.d("Hobbys", String.valueOf(hobbys.size()));
Log.d("Activity", userActivity.toString());
userActivity.notifyDatasetChanged();
return null;}});return null;}});
return root;
}
@SuppressLint("StaticFieldLeak")
private void searchHobbys(final AsyncTask<Void, Void, Void> asyncTask) {
FirebaseConfig.getDatabaseReference().child("hobbys")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
DataSnapshot current = iterator.next();
Hobby hobby = new Hobby();
hobby.setKey(current.getKey());
hobby.setValue((String)current.getValue());
hobby.setChecked(true);
hobbys.add(hobby);
}
asyncTask.execute();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void initializeComponents() {
friendsRecyclerView = root.findViewById(R.id.friendsRecyclerView);
RecyclerView.LayoutManager layoutManager =
new LinearLayoutManager(userActivity);
friendsRecyclerView.setLayoutManager(layoutManager);
friendsRecyclerView.setHasFixedSize(true);
userFriendsRecyclerViewAdapter = new UserFriendsRecyclerViewAdapter(
friends, hobbys, userActivity);
userActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
friendsRecyclerView.setAdapter(userFriendsRecyclerViewAdapter);
}
});
}
@SuppressLint("StaticFieldLeak")
private void searchFriends(final AsyncTask<Void, Void, Void> asyncTask) {
new FriendDAO().getAll(new AsyncTask<List<Friend>, Void, Void>() {
@Override protected Void doInBackground(List<Friend>... lists) {
friends = lists[0];
asyncTask.execute();
return null;
}});
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
userActivity = (UserActivity)context;
}
}
RecyclerViewAdapter:
package com.android.neto.myproject.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.neto.myproject.R;
import com.android.neto.myproject.model.Hobby;
import com.android.neto.myproject.model.Friend;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserFriendsRecyclerViewAdapter
extends RecyclerView.Adapter<UserFriendsRecyclerViewAdapter
.UserFriendsRecyclerViewViewHolder> {
private List<Friend> friends;
private List<Hobby> hobbysFromDatabase;
private Context context;
private Map<String, String> hobbysReference;
public UserFriendsRecyclerViewAdapter(List<Friend> friends,
List<Hobby> hobbysFromDatabase, Context context) {
this.friends = friends;
this.hobbysFromDatabase = hobbysFromDatabase;
this.context = context;
hobbysReference = new HashMap<>();
for(Hobby hobby : hobbysFromDatabase) {
hobbysReference.put(hobby.getKey(), hobby.getValue());
}
}
public class UserFriendsRecyclerViewViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
ImageView friendImageView;
TextView friendNameTextView;
TextView friendNameThreeDotsTextView;
TextView friendDistanceTextView;
TextView hobbysTextView;
TextView hobbysThreeDotsTextView;
public UserFriendsRecyclerViewViewHolder(@NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
friendImageView = itemView.findViewById(R.id.friendImageView);
friendNameTextView = itemView.findViewById(R.id.friendNameTextView);
friendNameThreeDotsTextView = itemView.findViewById(R.id.friendNameThreeDotsTextView);
friendDistanceTextView = itemView.findViewById(R.id.friendDistanceTextView);
hobbysTextView = itemView.findViewById(R.id.hobbysTextView);
hobbysThreeDotsTextView = itemView.findViewById(R.id.hobbysThreeDotsTextView);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
Friend friend = friends.get(position);
Toast.makeText(context, friend.getNickName(), Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
}
@NonNull
@Override
public UserFriendsRecyclerViewViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View item = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_friends, parent, false);
return new UserFriendsRecyclerViewViewHolder(item);
}
@Override
public void onBindViewHolder(@NonNull UserFriendsRecyclerViewViewHolder holder, int position) {
Friend friend = friends.get(position);
Picasso.get().load(friend.getRoundedProfileImageUri())
.into(holder.friendImageView);
holder.friendNameTextView.setText(friend.getNickName());
if (holder.friendNameTextView.getLineCount() >
holder.friendNameTextView.getMaxLines()) {
holder.friendNameThreeDotsTextView.setVisibility(View.VISIBLE);
}
holder.friendDistanceTextView.setText("1,6 km");
StringBuilder hobbysText = new StringBuilder();
List<Hobby> hobbys = friend.getHobbys();
for (int i = 0; i < hobbys.size(); i++) {
Hobby hobby = hobbys.get(i);
if (hobbysReference.containsKey(hobby.getKey())) {
hobbysText.append(hobbysReference.get(hobby.getKey()));
if (i != hobbys.size() - 1) {
hobbysText.append(", ");
}
}
}
holder.hobbysTextView.setText(hobbysText.toString());
if (holder.hobbysTextView.getLineCount() >
holder.hobbysTextView.getMaxLines()) {
holder.hobbysThreeDotsTextView.setVisibility(View.VISIBLE);
}
}
@Override
public int getItemCount() {
return friends.size();
}
}
Вид деятельности:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.UserActivity">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/user_bottom_nav_menu" />
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:menu="@menu/user_bottom_nav_menu" />
<ProgressBar
android:id="@+id/progressBar"
android:visibility="gone"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Просмотр фрагмента:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.UserFriendsFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/friendsRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="4dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Просмотр ViewHolder:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:padding="4dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp">
<ImageView
android:id="@+id/friendImageView"
android:layout_width="88dp"
android:layout_height="88dp"
android:layout_marginEnd="8dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_person_primary_color_24dp"
android:layout_gravity="center"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="@+id/friendNameTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/friendDistanceTextView"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginEnd="8dp"
android:maxLines="1"
android:ellipsize="end"
android:textStyle="bold"
android:textSize="16sp"/>
<TextView
android:id="@+id/friendNameThreeDotsTextView"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:text="..."
android:background="@android:color/white"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="@id/friendNameTextView"/>
<TextView
android:id="@+id/friendDistanceTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="100,6 km"
android:textSize="16sp"
android:textColor="@color/colorPrimaryDark"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hobbys:"
android:textSize="16sp"
android:textColor="@color/colorPrimaryDark"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/hobbysTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:scrollbars="horizontal"
android:textSize="12sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<TextView
android:id="@+id/hobbysThreeDotsTextView"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="..."
android:background="@android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/hobbysTextView"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Если вы, ребята, можете мне помочь, это было бы замечательно Заранее спасибо.