刷新android中的主片段

时间:2016-03-16 07:26:50

标签: android

我将创建一个4片段页面。如果我移动到主片段意味着,片段应该刷新。如果在另一个片段中进行的任何更改意味着它将在主片段中更新。任何一个帮助我刷新主片段

public class HomeFragment extends Fragment {

    ImageButton explore,chat;

    //Facebook Declaration
    private CallbackManager callbackManager;
    private LoginButton FbLoginButton;

    String fb_call = "fb";

    ListView recyclerView;
    RelativeLayout emptyView;
    private boolean mLoading = false;

    //Check Facebook
    Boolean Check_activity = false;
    List<String> fb_friends_list= new ArrayList<String>();

    private List<FeedItem> feedsList= new ArrayList<FeedItem>();
    CustomHomeFragmentAdapter adapter;

    String LiveUrl,userID,Facebook_Token;

    protected static final String TAG = "HomeFragment";

    public static final String MY_PREFS_NAME = "MyPrefsFile";
    boolean loading = true;
    int pastVisiblesItems, visibleItemCount, totalItemCount;

    //Progresswheel
    ProgressWheel pw;
    ResetPasswordActivity obj=new ResetPasswordActivity();


    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FacebookSdk.sdkInitialize(getContext());
        callbackManager = CallbackManager.Factory.create();

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        LiveUrl= sharedPreferences.getString("liveurl3", null);
        System.out.println("Liveurl1" + LiveUrl);

        SharedPreferences prefs1 = getContext().getSharedPreferences(MY_PREFS_NAME, getContext().MODE_PRIVATE);
        userID= prefs1.getString("userid", null);
        System.out.println("userid" + userID);


    }

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

        View v = inflater.inflate(R.layout.fragment_home, container, false);
        FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), "arial.ttf");
        fontChanger.replaceFonts((ViewGroup) v);

        // Inflate the layout for this fragment

        System.out.println("Home");

        pw=(ProgressWheel)v.findViewById(R.id.pw_spinner);
        obj.styleRandom(pw, v.getContext());

        emptyView=(RelativeLayout)v.findViewById(R.id.empty_view);
        recyclerView=(ListView)v.findViewById(R.id.recycler_view);


        adapter=new CustomHomeFragmentAdapter(getContext(),feedsList,HomeFragment.this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        getHomePosts();

        recyclerView.setRecyclerListener(new AbsListView.RecyclerListener() {
            @Override
            public void onMovedToScrapHeap(View view) {
                VideoView videoView = (VideoView) view.findViewById(R.id.post_video);
                videoView.stopPlayback();
            }
        });



        explore= (ImageButton) v.findViewById(R.id.explore_page);
        chat= (ImageButton) v.findViewById(R.id.edit_page);

        chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent chat=new Intent(getContext(),ChatActivity.class);
                startActivity(chat);
            }
        });

        FbLoginButton = (LoginButton) v.findViewById(R.id.fb_login_button);
        FbLoginButton.setBackgroundResource(R.drawable.rounded_button);
        FbLoginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        FbLoginButton.setCompoundDrawablePadding(0);
        FbLoginButton.setPadding(0, 0, 0, 0);
        FbLoginButton.setText("Find People to follow");
        FbLoginButton.setTextColor(Color.WHITE);
        List<String> permissions = new ArrayList<>();
        permissions.add("user_friends");
        FbLoginButton.setReadPermissions(permissions);
        FbLoginButton.setFragment(this);

        FbLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //FbLoginButton.setEnabled(false);
            }
        });
        FbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                Facebook_Token = loginResult.getAccessToken().getToken();

                new GraphRequest(
                        AccessToken.getCurrentAccessToken(),
                        "/me/friends",
                        null,
                        HttpMethod.GET,
                        new GraphRequest.Callback() {
                            public void onCompleted(GraphResponse response) {
                                LoginManager.getInstance().logOut();

                                System.out.println("response for friends" + response.toString());
                                JSONObject obj = response.getJSONObject();
                                System.out.println("obj" + obj);
                                JSONArray arr;
                                try {
                                    arr = obj.getJSONArray("data");
                                    System.out.println("array value" + arr);
                                    if (arr.length() != 0) {

                                        for (int i = 0; i < arr.length(); i++) {
                                            JSONObject fbfriends = arr.getJSONObject(i);
                                            String id = fbfriends.getString("id");
                                            fb_friends_list.add(id);
                                            System.out.println("facebook friends list" + fb_friends_list);
                                            String ids = fb_friends_list.toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(" ", "");

                                            Intent intent = new Intent(getContext(), FacebookFriendsActivity.class);
                                            intent.putExtra("friendslist", ids);
                                            intent.putExtra("fb_call", fb_call);
                                            startActivity(intent);

                                        }
                                    } else {
                                        Toast.makeText(getContext(), "No Friends are using Hotfuse", Toast.LENGTH_SHORT).show();
                                    }


                                } catch (JSONException e) {
                                    System.out.println("inside exception");
                                    e.printStackTrace();
                                }

                            }
                        }
                ).executeAsync();
            }


            @Override
            public void onCancel() {
                Toast.makeText(getActivity(), "Login cancelled by user!", Toast.LENGTH_LONG).show();
                System.out.println("Facebook Login failed!!");

            }

            @Override
            public void onError(FacebookException e) {
                Toast.makeText(getActivity(), "Login unsuccessful!", Toast.LENGTH_LONG).show();
                System.out.println("Facebook Login failed!!");
            }
        });

        explore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getChildFragmentManager()
                        .beginTransaction()
                        .replace(
                                R.id.homefragment,
                                new ExploreFragment(),
                                ExploreFragment.TAG)
                        .addToBackStack(null)
                        .commit();
            }
        });

        return v;

    }


    //Call Facebook StartActivity
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    public void getHomePosts()
    {
        pw.setVisibility(View.VISIBLE);
        pw.startSpinning();
        //String url=LiveUrl+"followingactivities?user_id="+userID;
        String url=LiveUrl+"post_data/?user_id="+userID;
        System.out.println("URL IS" + url);
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                pw.setVisibility(View.GONE);
                                pw.stopSpinning();
                                JSONObject suggested_jsonobj = response.getJSONObject(i);
                                FeedItem movie = new FeedItem();
                                System.out.println("user_id value" +suggested_jsonobj.optString("user_id"));
                                if (!suggested_jsonobj.optString("user_id").isEmpty())
                                {
                                    movie.setTitle(suggested_jsonobj.optString("username"));
                                    movie.setId(suggested_jsonobj.optString("user_id"));
                                    movie.setPostID(suggested_jsonobj.optString("id"));
                                    movie.setVideoID(suggested_jsonobj.optString("video_src"));
                                    movie.setVideoImage(suggested_jsonobj.optString("image_thumb"));
                                    movie.setThumbnail(suggested_jsonobj.optString("profile_image"));
                                    movie.setDate(suggested_jsonobj.optString("created"));
                                    movie.setVotecount(suggested_jsonobj.optString("votecount"));
                                    movie.setPost(suggested_jsonobj.optString("resize1"));
                                    movie.setPrivacyStatus(suggested_jsonobj.optString("privacy_status"));
                                    movie.setLikedStatus(suggested_jsonobj.optString("like_status"));
                                    movie.setLikedCount(suggested_jsonobj.optString("like_count"));
                                    movie.setLikeduserID(suggested_jsonobj.optString("like_user_id1"));
                                    movie.setLikedUserName(suggested_jsonobj.optString("like_username1"));
                                    movie.setCommentCount(suggested_jsonobj.optString("comment_count"));
                                    movie.setCaption(suggested_jsonobj.optString("caption"));
                                    movie.setCaptionUserName(suggested_jsonobj.optString("captionusername"));
                                    movie.setTagCount(suggested_jsonobj.optString("tag_count"));
                                    if (!suggested_jsonobj.optString("image_tag").matches("null")) {
                                        final JSONArray arr = new JSONArray(suggested_jsonobj.optString("image_tag"));
                                        final JSONObject jObj = arr.optJSONObject(0);
                                        movie.setx1Tag(jObj.optString("x1"));
                                        movie.sety1Tag(jObj.optString("y1"));
                                        movie.setx1userName(jObj.optString("name1"));
                                        movie.setx1userID(jObj.optString("user_id1"));
                                        movie.setx2Tag(jObj.optString("x2"));
                                        movie.sety2Tag(jObj.optString("y2"));
                                        movie.setx2userName(jObj.optString("name2"));
                                        movie.setx2userID(jObj.optString("user_id2"));
                                        movie.setx3Tag(jObj.optString("x3"));
                                        movie.sety3Tag(jObj.optString("y3"));
                                        movie.setx3userName(jObj.optString("name3"));
                                        movie.setx3userID(jObj.optString("user_id3"));
                                        movie.setx4Tag(jObj.optString("x4"));
                                        movie.sety4Tag(jObj.optString("y4"));
                                        movie.setx4userName(jObj.optString("name4"));
                                        movie.setx4userID(jObj.optString("user_id4"));

                                    }if (!suggested_jsonobj.optString("comment").isEmpty()) {
                                    final JSONArray arr = new JSONArray(suggested_jsonobj.optString("comment"));

                                    final JSONObject jObj = arr.optJSONObject(0);
                                    //Comment 1
                                    movie.setCommentID(jObj.optString("id"));
                                    movie.setCommentuserName(jObj.optString("username"));
                                    movie.setCommentProPic(jObj.optString("image"));
                                    movie.setCommentText(jObj.optString("comment"));

                                    //Comment 2
                                    final JSONObject jObj1 = arr.optJSONObject(1);
                                    if(jObj1!=null) {
                                        movie.setCommentID2(jObj1.optString("id"));
                                        movie.setCommentuserName2(jObj1.optString("username"));
                                        movie.setCommentProPic2(jObj1.optString("image"));
                                        movie.setCommentText2(jObj1.optString("comment"));
                                    }

                                    //Comment 3
                                    final JSONObject jObj2 = arr.optJSONObject(2);
                                    if(jObj2!=null) {
                                        movie.setCommentID3(jObj2.optString("id"));
                                        movie.setCommentuserName3(jObj2.optString("username"));
                                        movie.setCommentProPic3(jObj2.optString("image"));
                                        movie.setCommentText3(jObj2.optString("comment"));
                                    }
                                }
                                    feedsList.add(movie);
                                }
                                else
                                {
                                    recyclerView.setVisibility(View.GONE);
                                    emptyView.setVisibility(View.VISIBLE);
                                }





                            } catch (JSONException e) {
                                pw.setVisibility(View.GONE);
                                pw.stopSpinning();
                                e.printStackTrace();
                            }

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(error instanceof NoConnectionError) {
                    pw.setVisibility(View.GONE);
                    pw.stopSpinning();
                    Toast.makeText(getContext(), "Sorry we couldn't complete your request.Please try again in a moment", Toast.LENGTH_SHORT).show();
                }

                VolleyLog.d(TAG, "Error: " + error.getMessage());


            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
        movieReq.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    /* public void switchContent(int id,String id1) {
         getChildFragmentManager()
                 .beginTransaction()
                 .replace(id, ParallaxProfileActivity.newInstance(id1), ParallaxProfileActivity.TAG)
                 .commit();
     }*/
/*
    @Override
    public void onDetach() {
        super.onDetach();

        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }*/
    public class MyCustomLayoutManager extends LinearLayoutManager {
        private static final float MILLISECONDS_PER_INCH = 50f;
        private Context mContext;

        public MyCustomLayoutManager(Context context) {
            super(context);
            mContext = context;
        }

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView,
                                           RecyclerView.State state, final int position) {

            LinearSmoothScroller smoothScroller =
                    new LinearSmoothScroller(mContext) {

                        //This controls the direction in which smoothScroll looks
                        //for your view
                        @Override
                        public PointF computeScrollVectorForPosition
                        (int targetPosition) {
                            return MyCustomLayoutManager.this
                                    .computeScrollVectorForPosition(targetPosition);
                        }

                        //This returns the milliseconds it takes to
                        //scroll one pixel.
                        @Override
                        protected float calculateSpeedPerPixel
                        (DisplayMetrics displayMetrics) {
                            return MILLISECONDS_PER_INCH/displayMetrics.densityDpi;
                        }
                    };

            smoothScroller.setTargetPosition(position);
            startSmoothScroll(smoothScroller);
        }
    }

}

`

1 个答案:

答案 0 :(得分:0)

我在onCreate函数中添加了这个编码来刷新主片段,但它显示错误

Fragment frg = null;
frg = getSupportFragmentManager().findFragmentByTag("HomeFragment");
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();