У меня есть Activity в котором расположено несколько фрагментов. В HomeFragment я получаю список всех категорий в json формате
Теперь при нажатии на одну из категорий я хочу получить список всех материалов в новом фрагменте. Но для этого мне нужно передать id нажатой категории в новый фрагмент для того что бы можно было его подставить в url, и получить этот список. Пример
https://site.com/api/faucet/read_one_category?category_id=1
Вот мой Activity
public class MainActivity extends AppCompatActivity implements RecyclerViewInterface {
private ActivityMainBinding binding;
private static String CATEGORY_URL = "https://site.ru/appfaucetpayearning/rotator/api/category/read";
List<CategoryModel> categoryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
categoryList = new ArrayList<>();
GetData getData = new GetData();
getData.execute();
}
public class GetData extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(CATEGORY_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while(data != -1) {
current += (char) data;
data = isr.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
@Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("category");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
CategoryModel model = new CategoryModel();
model.setId(jsonObject1.getString("id"));
model.setName(jsonObject1.getString("name"));
model.setImg(jsonObject1.getString("img"));
categoryList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
PutDataIntoRecyclerView(categoryList);
}
}
private void PutDataIntoRecyclerView(List<CategoryModel> categoryList) {
CategoryAdapter categoryAdapter = new CategoryAdapter(this, categoryList, this);
binding.recyclerMain.setAdapter(categoryAdapter);
binding.recyclerMain.setLayoutManager(new LinearLayoutManager(this));
}
@Override
public void onItemClick(int position) {
Intent i = new Intent(MainActivity.this, TwoActivity.class);
startActivity(i);
i.putExtra("id", categoryList.get(position).getId());
i.putExtra("name", categoryList.get(position).getName());
i.putExtra("img", categoryList.get(position).getImg());
finish();
}
}
Вот мой адаптер категорий
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> {
private final RecyclerViewInterface recyclerViewInterface;
private Context context;
private List<CategoryModel> mData;
public CategoryAdapter(Context context, List<CategoryModel> mData, RecyclerViewInterface recyclerViewInterface) {
this.context = context;
this.mData = mData;
this.recyclerViewInterface = recyclerViewInterface;
}
@NonNull
@Override
public CategoryAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.category_item, parent, false);
return new CategoryAdapter.MyViewHolder(view, recyclerViewInterface);
}
@Override
public void onBindViewHolder(@NonNull CategoryAdapter.MyViewHolder holder, int position) {
holder.id.setText(mData.get(position).getId());
holder.name.setText(mData.get(position).getName());
Glide.with(context)
.load(mData.get(position).getImg())
.into(holder.img);
}
@Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView id, name;
ImageView img;
RecyclerViewInterface recyclerViewInterface;
public MyViewHolder(@NonNull View itemView, RecyclerViewInterface recyclerViewInterface) {
super(itemView);
this.recyclerViewInterface = recyclerViewInterface;
id = itemView.findViewById(R.id.id);
name = itemView.findViewById(R.id.category_name);
img = itemView.findViewById(R.id.category_image);
itemView.setOnClickListener(v -> {
if (recyclerViewInterface != null){
int pos = getAdapterPosition();
if(pos != RecyclerView.NO_POSITION) {
recyclerViewInterface.onItemClick(pos);
id.setText((int) getItemId());
}
}
});
}
}
}
Создал RecyclerViewInterface interface
public interface RecyclerViewInterface {
void onItemClick(int position);
}
Но при попытке передать с одной активности в другую, получаю пустые значения
@Override
public void onItemClick(int position) {
Intent i = new Intent(MainActivity.this, TwoActivity.class);
startActivity(i);
i.putExtra("id", categoryList.get(position).getId());
i.putExtra("name", categoryList.get(position).getName());
i.putExtra("img", categoryList.get(position).getImg());
finish();
}