不更新片段中的回收站视图

Posted

技术标签:

【中文标题】不更新片段中的回收站视图【英文标题】:Not update recycler view in fragment 【发布时间】:2019-07-25 14:07:42 【问题描述】:

我想通过 MainActivity Access 访问 Fragment 方法,该方法当然可以回答,但在该方法中,我想更改 RecyclerView 的那一项但它没有改变我的麻烦在哪里?

在 updatefrag_app 方法中我得到了一个日志,所以我想我在这里工作但是 RecyclerView 没有更新。

MainActivity:

public class MainActivity extends BaseActivity
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    db = new DBManager(this);     


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Result_buy_image) 

        if (resultCode == Activity.RESULT_OK) 
            String result = data.getStringExtra("result");

            String price = null,link = null,type = null,position = null;

            try 
                JSONObject jsonObject = new JSONObject(result);

                type = jsonObject.getString("type").toString();
                price = jsonObject.getString("price").toString();
                link = jsonObject.getString("link").toString();
                position = jsonObject.getString("position").toString();

             catch (JSONException e) 
                e.printStackTrace();
            

            int money = SSSP.getInstance(this).getInt("money", 0);

            int NewMoney = money - (Integer.parseInt(price));

            SSSP.getInstance(this).putInt("money", NewMoney);
            navUsername.setText(NewMoney + "");

            db.open();
            db.insert_purchased(price, link);
            db.close();


            // call Fragment method
            Frag_Post_App fragment = (Frag_Post_App) getSupportFragmentManager().
                findFragmentByTag("Frag_Post_App");
            fragment.updatefrag_app(position);

            if (resultCode == Activity.RESULT_CANCELED) 

            
        
    

和片段:

public class Frag_Post_App extends BaseFragment 


private String TAG = "Frag_Post_App";

private List<Holder> arrayList = new ArrayList<>();
private RecyclerView recyclerView;
private Adapter_App mAdapter;
private View view;
private String cat_id, file_php = "";
private LinearLayout ll_pBar_ring_post;
private int counter = -1;
private boolean checkExistItem = true;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 

    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.frag_post_category_app, container, false);


    Bundle bundle = this.getArguments();
    if (bundle != null) 
        cat_id = bundle.getString("id", "favorite");
        file_php = bundle.getString("filephp", "");

        Log.d(TAG, "file_php: " + file_php);
    

    ll_pBar_ring_post = (LinearLayout) view.findViewById(R.id.ll_pBar_ring_post);

    new DownloadFilesTask(cat_id, "1").execute();


    return view;


@Override
protected int getFragmentLayout() 
    return 0;




private void recycler() 


    counter = 1;

    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_appp_post);


    mAdapter = new Adapter_App(arrayList, getActivity(), "post");
    recyclerView.setHasFixedSize(true);


    StaggeredGridLayoutManager gridLayoutManager =
            new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);


    RecyclerView.LayoutManager mLayoutManager =
            new LinearLayoutManager(getActivity().getApplicationContext());

    recyclerView.setLayoutManager(gridLayoutManager);

    DefaultItemAnimator animator = new DefaultItemAnimator() 
        @Override
        public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) 
            return true;
        
    ;
    recyclerView.setItemAnimator(animator);


    recyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();


    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() 
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) 
            super.onScrollStateChanged(recyclerView, newState);

            if (!recyclerView.canScrollVertically(1)) 


                if (checkExistItem) 
                    counter = ++counter;
                    new DownloadFilesTask(cat_id, counter + "").execute();
                
            
        
    );





private class DownloadFilesTask extends AsyncTask<Void, Integer, String> 


    String cat_id;
    String page;

    public DownloadFilesTask(String cat_id, String page) 

        this.cat_id = cat_id;
        this.page = page;

    

    protected String doInBackground(Void... urls) 

        String parsedString = "";

        try 

            URL url = new URL(file_php);
            URLConnection conn = url.openConnection();


            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setReadTimeout(50000);
            httpConn.setConnectTimeout(50000);
            httpConn.setUseCaches(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("POST");
            httpConn.setChunkedStreamingMode(0);
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            httpConn.setRequestProperty("Accept-Encoding", "identity");

            conn.setDoInput(true);
            conn.setDoOutput(true);

            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("cat_id", cat_id)
                    .appendQueryParameter("page", page);
            String query = builder.build().getEncodedQuery();

            OutputStream os = new BufferedOutputStream(conn.getOutputStream());

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();


            try 
                httpConn.connect();

                InputStream inputStream = null;

                if (httpConn.getResponseCode() >= 400) 
                    inputStream = new BufferedInputStream(httpConn.getErrorStream());
                 else 
                    inputStream = new BufferedInputStream(httpConn.getInputStream());
                




                parsedString = StreamToString(inputStream);

             finally 
                httpConn.disconnect();
            


         catch (Exception e) 
            e.printStackTrace();

        

        return parsedString;
    

    protected void onProgressUpdate(Integer... progress) 

    

    protected void onPostExecute(String result) //            showDialog("Downloaded " + result + " bytes");
        Log.d(TAG, "result: " + result);

        if (result != null) 

            ll_pBar_ring_post.setVisibility(View.GONE);
            pars(result);

         else 

            Log.d(TAG, "resultIsNull: " + result);

        


    


private void pars(String res) 

    Log.d(TAG, "pars: " + res);

    try 

        JSONArray jsonarray = new JSONArray(res);

        if (jsonarray.length() > 0) 

            checkExistItem = true;

            SSSP.getInstance(getActivity()).putString(spResult, res);

            for (int i = 0; i < jsonarray.length(); i++) 
                JSONObject jsonobject = jsonarray.getJSONObject(i);
                String post_id = jsonobject.getString("ID");
                String post_link = jsonobject.getString("post_link");
                String post_link_low = jsonobject.getString("post_link_low");
                String like = jsonobject.getString("like");
                String composer = jsonobject.getString("composer");
                String price = jsonobject.getString("price");
                String post_title = jsonobject.getString("post_title");
                String thumbnail_url = jsonobject.getString("thumbnail_url");
                String the_content = jsonobject.getString("the_content");
                String advertise = jsonobject.getString("advertise");
                String advertise_link = jsonobject.getString("advertise_link");

                arrayList.add(new Holder(the_content, post_title + "", post_link + "", post_link_low + ""
                        , thumbnail_url + "", like + "", advertise, advertise_link, price + ""));
            

         else 
            checkExistItem = false;
            Log.d(TAG, "checkExistItem is false: ");
        

     catch (JSONException e) 
        e.printStackTrace();
    

    recycler();





public void updatefrag_app(String position) 
    Log.d(TAG, "updatefrag_app: " + position);

    mAdapter.notifyItemChanged(Integer.parseInt(position));

适配器是:

public class Adapter_App extends RecyclerView.Adapter<RecyclerView.ViewHolder> 

private List<Holder> holder_s;
private Activity context;

private String TAG = "Adapter_App_log";

private String layout = "";

private DBManager db;
private int pos = -1;

public Adapter_App(List<Holder> holder_s, Activity context, String layout) 
    this.holder_s = holder_s;
    this.context = context;
    this.layout = layout;
    db = new DBManager(context);






public class viewHolderPost extends RecyclerView.ViewHolder 


    private SSTextView number_like, title_app, link_google, content_app, price;

    private LinearLayout ll_item_recy;

    private ImageView img, dowload_app, like;

    viewHolderPost(View itemView) 
        super(itemView);

        number_like = (SSTextView) itemView.findViewById(R.id.number_like_app);
        price = (SSTextView) itemView.findViewById(R.id.price_app);
        title_app = (SSTextView) itemView.findViewById(R.id.title_app);
        link_google = (SSTextView) itemView.findViewById(R.id.link_google);
        content_app = (SSTextView) itemView.findViewById(R.id.content_app);

        ll_item_recy = (LinearLayout) itemView.findViewById(R.id.ll_item_recy_app);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;

        ll_item_recy.getLayoutParams().width = width / 2;
        ll_item_recy.getLayoutParams().height = height / 2;

        img = (ImageView) itemView.findViewById(R.id.img_app);
        dowload_app = (ImageView) itemView.findViewById(R.id.dowload_app);
        like = (ImageView) itemView.findViewById(R.id.like_app);
    



@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 


    RecyclerView.ViewHolder viewHolder = null;
    Log.d(TAG, "onCreateViewHolder: ");




            viewHolder = new viewHolderPost(LayoutInflater.from(context)
                    .inflate(R.layout.list_item_app, parent, false));


    

    return viewHolder;




@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) 

    final Holder holder_ = holder_s.get(position);






            final viewHolderPost holderPOST = (viewHolderPost) holder;


            holderPOST.title_app.setText(holder_.getTitle());


            holderPOST.number_like.setText(holder_.getlike());
            holderPOST.content_app.setText(holder_.getid()); // this content in id

            String link = holder_.get_image_link().replace("http://localhost", "http://192.168.43.8");


            Picasso.get().load(link).into(holderPOST.img);

            holderPOST.dowload_app.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v) 

                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(holder_.getUrl()));
                    context.startActivity(browserIntent);

                
            );

            holderPOST.link_google.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v) 


                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(holder_.getUrl_low()));
                    context.startActivity(browserIntent);

                
            );

            File file1 = StringtoFile(holder_.getUrl());

            if (Integer.parseInt(holder_.getprice()) > 0) 


                db.open();




                Boolean exist = db.CheckItemExist(
                        OpenHelper.TBL_PURCHASED
                        , OpenHelper.LINK_PURCHASE, holder_.getUrl()
                );

                Log.d(TAG, "exist : " + exist);
                Log.d(TAG, "link : " + holder_.getUrl());

                if (!exist) 
                    holderPOST.price.setVisibility(View.VISIBLE);
                    holderPOST.price.setText(holder_.getprice() + " T");
                    holderPOST.dowload_app.setVisibility(View.GONE);
                 else 

                    holderPOST.price.setVisibility(View.GONE);

                    if (file1.exists()) 
                        try 
                            holderPOST.price.setVisibility(View.GONE);

                         catch (Exception e) 
                            e.printStackTrace();
                        
                     else 

                        holderPOST.dowload_app.setVisibility(View.VISIBLE);
                    


                
                db.close();
            


            if (file1.exists()) 
                holderPOST.dowload_app.setVisibility(View.VISIBLE);

            







            holderPOST.price.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View v) 



                    int money = SSSP.getInstance(context).getInt("money", 0);

                    int price = Integer.parseInt(holder_.getprice());

                    if (money >= price) 


                        JSONObject object = new JSONObject();
                        try 
                            object.put("type", "app");
                            object.put("price", holder_.getprice());
                            object.put("link", holder_.getUrl());
                            object.put("position", holderPOST.getLayoutPosition());
                         catch (JSONException e) 
                            e.printStackTrace();
                        

                        Intent intent = new Intent(context, SSDialog.class);

                        intent.putExtra("STRING_I_NEED", object.toString());
                        intent.putExtra("tv_inDate", "alert");
                        intent.putExtra("msg", "Do you sure want to buy?");
                        intent.putExtra("yes", "Yes");
                        intent.putExtra("no", "No");
                        context.startActivityForResult(intent, Result_buy_image);

                     else 
                        SSToast(context, "Inventory is not enough");
                    

                
            );


    





@Override
public int getItemCount() 
    return holder_s.size();

【问题讨论】:

没有人知道Adapter_App 是什么,以及它是如何工作的 我也没有看到您在更新后从数据库中检索更新的数据 我把适配器... 【参考方案1】:

好的,我知道这是什么原因导致的,扔掉你的代码,我找不到你在哪里更改recyclerView的数据连接。

【讨论】:

@dariushkiany 在您的片段中,您列出的数据仅来自网络...尝试更改活动结果中的数据。 我没看懂,我想从 MainActivity Order 到 Fragment 更新 Recycler

以上是关于不更新片段中的回收站视图的主要内容,如果未能解决你的问题,请参考以下文章

回收站视图仅在我从房间数据库中删除后重新打开活动时更新

在不重新加载活动的情况下更新回收站视图中的内容

片段在我的回收站视图中表现得很奇怪

OnClick 用于片段中的 2/3 回收器视图(其本身托管/放置在另一个片段上)不起作用

回收站视图未显示在片段中

RecyclerView 项目中的片段替换