Не обновлять вид рециркулятора во фрагменте - PullRequest
0 голосов
/ 04 марта 2019

Я хочу пройти через MainActivity Access к методу фрагмента, который, конечно, отвечает, но в этом методе я хочу изменить этот элемент 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();
}

1 Ответ

0 голосов
/ 04 марта 2019

хорошо, я знаю, по какой причине это произойдет, бросьте свой код, я не могу найти, где вы меняете соединение для передачи данных recyclerView.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...