简体   繁体   English

在 RecyclerView 的新活动中打开项目(来自 json 的数据)

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

Hello i'm new to android studio and i have code which is showing recycler view list from json data.您好,我是 android 工作室的新手,我有代码显示来自 json 数据的回收商视图列表。 Now i want to open items in new activity.I want to open item from recyclerview and show image and some text in new activity.现在我想在新活动中打开项目。我想从 recyclerview 打开项目并在新活动中显示图像和一些文本。 I need solution code.我需要解决方案代码。

I have tried some ways but it doesn't work.我尝试了一些方法,但它不起作用。

This is my code:这是我的代码:

public class MainActivity extends AppCompatActivity {公共 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();
        }

    }

}

} }

I expect to open item from recyclerview list in new activity and show image item and some text.我希望在新活动中从 recyclerview 列表中打开项目并显示图像项目和一些文本。

You can archive this by passing an instance of the interface in your adapter class and implement that interface in your activity.您可以通过在适配器 class 中传递接口的实例来归档它,并在您的活动中实现该接口。

refer this to get insights link参考此以获得见解链接

Sample Snippets示例片段

Declare interface:声明接口:

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

Pass interface instance via setup your adapter in activity.通过在活动中设置您的适配器来传递接口实例。

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

In your adapter constructor在您的适配器构造函数中

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

define click listener in a holder and inside a method call callback.onFishCall(selectedItem);在持有者和方法调用中定义点击监听器 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.

相关问题 从 RecyclerView 打开一个项目作为新活动并显示来自 JSON 的某些数据 - Open an item as new activity from the RecyclerView and display certain data from JSON 如何通过单击来自recyclerview的项目来打开新活动 - How to open new activity from clicking an item from recyclerview 如何将数据从recyclerview中的单击项传递到ViewModel并打开新活动? - How to pass data from clicked item in recyclerview to viewmodel and open new activity? 单击项目时将数据从 recyclerView 传递到新活动 Kotlin - Pass data from recyclerView to new activity when an item is clicked Kotlin 如何从 recyclerview 项目打开活动? - How to open an activity from a recyclerview item? 从包含卡片的Recyclerview中打开新活动 - Open new activity from Recyclerview containing cards 如何在RecyclerView中使用不同的数据和照片在项目单击上打开新的活动 - How to open new Activity on item click with different data and photo in RecyclerView 单击RecyclerView中包含在片段中的项目以打开带有传递数据的新活动 - Click On An Item In RecyclerView Contained In A Fragment To Open New Activity With Passed Data 单击viewList中的项目。用数据库android中的数据打开新活动 - click on item in viewList .. open new activity with data from database android 从具有条件的详细活动回收器视图中打开新活动的方法 - Method to open new activity from detail activity recyclerview with conditions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM