У меня есть rest api в котором есть категории и материалы категорий. Есть CategoryActivity в котором с помощью JsonObject и JsonArray я получаю список категорий в приложение. Для того что бы получить материалы из каждой категории мне нужно сформировать запрос site.com/api/read_one_category.php?category_id=? где знак вопроса это id категории. В CategoryActivity я получаю id каждой категории. Мне нужно сделать что бы при нажатие на текст названия категории бралось id той категории и передавалось на другое Activity в котором сформировался соответствующий url запроса.
Вот код активности с категориями
public class FaucetCategoryActivity extends AppCompatActivity {
ActivityFaucetCategoryBinding binding;
private AdView mAdView;
private InterstitialAd mInterstitialAd;
private static String CATEGORY_URL = "https://site.ru/api/category/read.php";
List<CategoryModel> categoryList;
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityFaucetCategoryBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
//Ads init
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//Ad Banner
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//Back to MainActivity
binding.back.setOnClickListener(v -> {
Intent intentback = new Intent(FaucetCategoryActivity.this, MainActivity.class);
startActivity(intentback);
finish();
});
categoryList = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
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();
}
return current;
} 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("records");
for (int i = 0 ; i < jsonArray.length() ; i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
CategoryModel categoryModel = new CategoryModel();
categoryModel.setId(jsonObject1.getString("id"));
categoryModel.setName(jsonObject1.getString("name"));
categoryModel.setImg(jsonObject1.getString("img"));
categoryList.add(categoryModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
PutDataIntoRecyclerView(categoryList);
}
}
private void PutDataIntoRecyclerView(List<CategoryModel> categoryList) {
CategoryAdapter adapter = new CategoryAdapter(this, categoryList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
Я создал интерфейс с именем ICategorySelector и поместил
public interface ICategorySelector {
public void passData(CategoryModel category);
}
Далее заменил строку public class FaucetCategoryActivity extends AppCompatActivity
на public class FaucetCategoryActivity extends AppCompatActivity implements ICategorySelector
Потом создал метод в FaucetCategoryActivity
@Override
public void passData(CategoryModel category) {
CategoryAdapter adapter = new CategoryAdapter(this, categoryList, FaucetCategoryActivity.this);
}
Потом в CategoryAdapter создал конструктор
public CategoryAdapter(FaucetCategoryActivity faucetCategoryActivity, List<CategoryModel> categoryList, FaucetCategoryActivity faucetCategoryActivity1) {
}
Потом в MyViewHolder добавил
ICategorySelector selector;
CategoryAdapter(...,ICategorySelector selector){
this.selector=selector;
}
Что должно быть за месть ...?
Потом он не находит selector в holdere
Вот полный код adapter
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> {
private Context mContext;
private List<CategoryModel> mData;
public CategoryAdapter(Context mContext) {
this.mContext = mContext;
this.mData = mData;
}
public CategoryAdapter(FaucetCategoryActivity mContext, List<CategoryModel> categoryList, FaucetCategoryActivity faucetCategoryActivity) {
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v;
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
v = layoutInflater.inflate(R.layout.category_item, parent, false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.id.setText(mData.get(position).getId());
holder.name.setText(mData.get(position).getName());
//Using Glide library to display the image
Glide.with(mContext)
.load(mData.get(position).getImg())
.into(holder.img);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selector.passData(arrayOfCategories[position]);
}
});
}
@Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView name;
CircleImageView img;
ICategorySelector selector;
void CategoryAdapter(List<CategoryModel> categoryList, FaucetCategoryActivity faucetCategoryActivity, ICategorySelector selector){
this.selector=selector;
}
public MyViewHolder(@NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.id);
name = itemView.findViewById(R.id.category_name);
img = itemView.findViewById(R.id.category_image);
}
}
}