簡體   English   中英

在 RecyclerView 的新活動中打開項目(來自 json 的數據)

[英]Open item in new activity from RecyclerView (data from json)

您好,我是 android 工作室的新手,我有代碼顯示來自 json 數據的回收商視圖列表。 現在我想在新活動中打開項目。我想從 recyclerview 打開項目並在新活動中顯示圖像和一些文本。 我需要解決方案代碼。

我嘗試了一些方法,但它不起作用。

這是我的代碼:

公共 class MainActivity 擴展 AppCompatActivity {

public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFishPrice;
private AdapterFish mAdapter;
SwipeRefreshLayout mSwipeRefreshLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swifeRefresh);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new AsyncFetch().execute();
        }
    });
    new AsyncFetch().execute();
}

private class AsyncFetch extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {


            url = new URL("https://MYURL.com");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");

            // setDoOutput to true as we recieve data from json file
            conn.setDoOutput(true);

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        mSwipeRefreshLayout.setRefreshing(false);


        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        try {

            JSONArray jArray = new JSONArray(result);

            for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                DataFish fishData = new DataFish();
                fishData.fishImage= json_data.getString("fish_img");
                fishData.fishName= json_data.getString("fish_name");
                fishData.catName= json_data.getString("cat_name");
                fishData.sizeName= json_data.getString("size_name");
                fishData.price= json_data.getInt("price");
                data.add(fishData);
            }

            mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
            mAdapter = new AdapterFish(MainActivity.this, data);
            mRVFishPrice.setAdapter(mAdapter);
            mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

        } catch (JSONException e) {
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
        }

    }

}

}

我希望在新活動中從 recyclerview 列表中打開項目並顯示圖像項目和一些文本。

您可以通過在適配器 class 中傳遞接口的實例來歸檔它,並在您的活動中實現該接口。

參考此以獲得見解鏈接

示例片段

聲明接口:

public interface AdapterCallback {
   void onFishClick(DataFish item);
}

通過在活動中設置您的適配器來傳遞接口實例。

new AdapterFish(MainActivity.this, data, new AdapterCallback() {
    @Override
    void onfishClick(DataFish item) {
     // herer do your work
    }
});

在您的適配器構造函數中

private AdapterCallback callback;
AdapterFish(Context contex, data, AdapterCallback callback) {
   ...
   this.callback = callback;
}

在持有者和方法調用中定義點擊監聽器 callback.onFishCall(selectedItem);

   OnBindViewHolder(...) {
       holder.button.onClicklistener(new OnClickListener{
          ...
          if(callback != null) { // for null check
              callback.onFishClikc(item);
          }
       });
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM