1

как получить ссылку на ресурс в адаптере, или как это сделать при отправке? Код получения данных из JSON (фрагмент)

    private static final String NOTE_ID = "itemID" ;
private static final String NOTE_TITLE = "title" ;
private static final String NOTE_TAGS = "tag" ;
private static final String NOTE_IMAGE = "image" ;
private final String TAG_FRAGMENT = "tag_fragment";
private JSONAdapter noteAdapter;
private RecyclerView recyclerView;
private LinearLayoutManager mLLM;
private JSON note;
private JSONObject jsonObject;
private JSONArray jsonArray;
private String mJson;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View rv = inflater.inflate(
            R.layout.fragment_list, container, false);
    //recyclerview///
    noteAdapter = new JSONAdapter();
    recyclerView = (RecyclerView) rv.findViewById(R.id.recyclerview);
    recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));


    mLLM = new LinearLayoutManager(recyclerView.getContext());
    recyclerView.setLayoutManager(mLLM);
    recyclerView.setAdapter(noteAdapter);
    try {
        loadNotes();
    } catch (JSONException e) {
        e.printStackTrace();
    }


    return rv;
}

private void loadNotes() throws JSONException {
    jsonArray = new JSONArray(getJSONString());
    for(int i=0; i < jsonArray.length(); i++){
        jsonObject = jsonArray.getJSONObject(i);
        note = new JSON(jsonObject.getString(NOTE_TITLE),  jsonObject.getString(NOTE_TAGS),  jsonObject.getString(NOTE_ID), jsonObject.getString(NOTE_IMAGE));
        noteAdapter.addNote(note);

    }
    noteAdapter.notifyDataSetChanged();
}

private String getJSONString(){

    if(getArguments() != null){
        mJson = getArguments().getString(TAG_FRAGMENT);
    }

    if(mJson == null || mJson.isEmpty() || mJson.equals("")) return null;

    String json = null;

    try {

        InputStream is = getContext().getAssets().open(mJson); // go to main/asset directory to see notes.json

        int size = is.available();

        byte[] buffer = new byte[size];

        is.read(buffer);

        is.close();

        json = new String(buffer, "UTF-8");


    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;

}

и отправляются в адаптер . Нужно чтобы адаптер уже получал ссылку на ресурс Пример!

Glide.with(holder.mImageView.getContext())
                .load(holder.mBoundImage = notes.get(position).getImage())
                .fitCenter()
                .into(holder.mImageView);

сам note json

   {
    "title" : "TITLE OF NOTE",
    "tag" : "tag t",
    "itemID" : "1",
    "image" : "R.drawable.cheese_1"
  },

или как это сделать через getResources().getIdentifier(res, "drawable", packageName); и я могу изменить "image" : "R.drawable.cheese_1" на "image" : "cheese_1"

1 ответ 1

1

При помощи рефлексии это делается так:

public static int getResId(String resName, Class<?> c) { 
    try { 
        Field idField = c.getDeclaredField(resName); 
        return idField.getInt(idField); 
    } catch (Exception e) { 
        e.printStackTrace(); 
        return -1; 
     }
 }

Использование выглядит так:

getResId("icon", R.drawable.class);

Метод который Вы упоминаете getIdentifier, так же использует рефлексию, но делает это дважды.

9
  • можешь подсказать что не так, он ругается в логе holder.mBoundImage = getResId(notes.get(position).getImage(), Drawable.class);
    – djo
    22 мая 2016 в 12:12
  • @djo имя ресурса нужно указывать без "R.drawable." 22 мая 2016 в 12:17
  • да я так и делал, он -1 выводит даже на чистом листе попробовал (в принципе неважно уже(я через Bitmap , но для интерес метод узнать)
    – djo
    22 мая 2016 в 12:59
  • Странно, имя ресурса точно указано без ошибок? 22 мая 2016 в 13:00
  • имя ресурса просто строка и без формата файла? так делал ну как в примере точно так
    – djo
    22 мая 2016 в 13:04

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.