不从onCreate调用方法

时间:2018-05-14 10:44:09

标签: android android-fragments recyclerview-layout

我正在制作分类市场Android应用程序。所以,我必须在我的主页上显示广告或发布的帖子,一切正常,我在邮递员上发布了所有帖子,但没有在我的回收视图上。

public class SearchFragment extends Fragment {

    private static final String TAG = "SearchFragment";
    private static final String BASE_URL = "http://35.188.133.114//elasticsearch/posts/post/";
    private static final int NUM_GRID_COLUMNS = 2;
    private static final int GRID_ITEM_MARGIN = 5;

    //widgets
    private ImageView mFilters;
    private EditText mSearchText;
    private FrameLayout mFrameLayout;

    //vars
    private String mElasticSearchPassword;
    private String mPrefCity;
    private String mPrefStateProv;
    //private String mPrefCountry;
    private String mPrefCollege;
    private ArrayList<Post> mPosts;
    private RecyclerView mRecyclerView;
    private PostListAdapter mAdapter;
    private ListView listView;
    private String currentuser;
    private String user;
    private ImageView filter;


    ArrayList<Card> list = new ArrayList<>();

    FloatingActionButton fab;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, container, false);
        mFilters = (ImageView) view.findViewById(R.id.ic_search);
        mSearchText = (EditText) view.findViewById(R.id.input_search);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mFrameLayout = (FrameLayout) view.findViewById(R.id.container);
        filter = (ImageView) view.findViewById(R.id.filter);

        currentuser = FirebaseAuth.getInstance().getUid();

        filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               Intent intent = new Intent(getActivity(),FiltersActivity.class);
               startActivity(intent);

            }
        });

        getElasticSearchPassword();

        welcome();

        init();

        return view;
    }

   private void setupPostsList(){

        RecyclerViewMargin itemDecorator = new RecyclerViewMargin(GRID_ITEM_MARGIN, NUM_GRID_COLUMNS);
        mRecyclerView.addItemDecoration(itemDecorator);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), NUM_GRID_COLUMNS);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mAdapter = new PostListAdapter(getActivity(), mPosts);
        mRecyclerView.setAdapter(mAdapter);

        // CustomListAdapter adapter = new CustomListAdapter(getActivity(), R.layout.card_layout_main, list);
    }

    private void welcome() {

        if (!currentuser.equals("")) {

            mPosts = new ArrayList<Post>();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);

            HashMap<String, String> headerMap = new HashMap<String, String>();
            headerMap.put("Authorization", Credentials.basic("user", mElasticSearchPassword));

            //  String searchString = "*";

       /* if(!mSearchText.equals("")){
            searchString = searchString + mSearchText.getText().toString() + "*";
        }*/
               /* if(!mPrefCity.equals("")){
                    searchString = searchString + " city:" + mPrefCity;
                }
                if(!mPrefStateProv.equals("")){
                    searchString = searchString + " state_province:" + mPrefStateProv;
                }*/
       /* if(!mPrefCollege.equals("")){
            searchString = searchString + " college:" + mPrefCollege;
        }*/
                /*if(!currentuser.equals("")){
                    searchString = searchString + " user_id:" + currentuser;
                }*/

            Call<HitsObject> call = searchAPI.search(headerMap, "AND", "*");

            call.enqueue(new Callback<HitsObject>() {
                @Override
                public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {

                    HitsList hitsList = new HitsList();
                    String jsonResponse = "";
                    try {
                        Log.d(TAG, "onResponse: server response: " + response.toString());

                        if (response.isSuccessful()) {
                            hitsList = response.body().getHits();
                        } else {
                            jsonResponse = response.errorBody().string();
                        }

                        Log.d(TAG, "onResponse: hits: " + hitsList);

                        for (int i = 0; i < hitsList.getPostIndex().size(); i++) {
                            Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
                            mPosts.add(hitsList.getPostIndex().get(i).getPost());
                        }

                        Log.d(TAG, "onResponse: size: " + mPosts.size());
                        //setup the list of posts
                        setupPostsList();

                    } catch (NullPointerException e) {
                        Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage());
                    } catch (IndexOutOfBoundsException e) {
                        Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage());
                    } catch (IOException e) {
                        Log.e(TAG, "onResponse: IOException: " + e.getMessage());
                    }
                }

                @Override
                public void onFailure(Call<HitsObject> call, Throwable t) {
                    Log.e(TAG, "onFailure: " + t.getMessage());
                    Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
                }
            });
        }

        // return false;
    }


    private void init(){
       mFilters.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mPosts = new ArrayList<Post>();

                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

                ElasticSearchAPI searchAPI = retrofit.create(ElasticSearchAPI.class);

                HashMap<String, String> headerMap = new HashMap<String, String>();
                headerMap.put("Authorization", Credentials.basic("user", mElasticSearchPassword));

                String searchString = "";

                if(!mSearchText.equals("")){
                    searchString = searchString + mSearchText.getText().toString() + "*";
                }
               /* if(!mPrefCity.equals("")){
                    searchString = searchString + " city:" + mPrefCity;
                }
                if(!mPrefStateProv.equals("")){
                    searchString = searchString + " state_province:" + mPrefStateProv;
                }*/
                if(!mPrefCollege.equals("")){
                    searchString = searchString + " college:" + mPrefCollege;
                }
                /*if(!currentuser.equals("")){
                    searchString = searchString + " user_id:" + currentuser;
                }*/

                Call<HitsObject> call = searchAPI.search(headerMap, "AND", searchString);

                call.enqueue(new Callback<HitsObject>() {
                    @Override
                    public void onResponse(Call<HitsObject> call, Response<HitsObject> response) {

                        HitsList hitsList = new HitsList();
                        String jsonResponse = "";
                        try{
                            Log.d(TAG, "onResponse: server response: " + response.toString());

                            if(response.isSuccessful()){
                                hitsList = response.body().getHits();
                            }else{
                                jsonResponse = response.errorBody().string();
                            }

                            Log.d(TAG, "onResponse: hits: " + hitsList);

                            for(int i = 0; i < hitsList.getPostIndex().size(); i++){
                                Log.d(TAG, "onResponse: data: " + hitsList.getPostIndex().get(i).getPost().toString());
                                mPosts.add(hitsList.getPostIndex().get(i).getPost());
                            }

                            Log.d(TAG, "onResponse: size: " + mPosts.size());
                            //setup the list of posts
                            setupPostsList();

                        }catch (NullPointerException e){
                            Log.e(TAG, "onResponse: NullPointerException: " + e.getMessage() );
                        }
                        catch (IndexOutOfBoundsException e){
                            Log.e(TAG, "onResponse: IndexOutOfBoundsException: " + e.getMessage() );
                        }
                        catch (IOException e){
                            Log.e(TAG, "onResponse: IOException: " + e.getMessage() );
                        }
                    }

                    @Override
                    public void onFailure(Call<HitsObject> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage() );
                        Toast.makeText(getActivity(), "search failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }

               // return false;

       });
    }

welcome()方法未调用,因为我无法看到任何帖子,但 init()方法正常工作,并在点击搜索按钮时显示所有帖子。并且这两种方法都使用相同的代码,我正在进行查询的唯一区别,不知道为什么welcome()方法没有显示任何帖子。

3 个答案:

答案 0 :(得分:0)

实际上,您的方法是从onCreate()调用的,但您的条件(!currentuser.equals("") false

答案 1 :(得分:0)

这是Firbase问题,请检查firebase实例是否已在应用程序类中正确配置和初始化。那你就不应该得到currentUser ==&#34;&#34;。

Firebase将返回401/410错误代码,包含无效的用户令牌/身份验证和无效的用户信息。

答案 2 :(得分:0)

查看currentuser = FirebaseAuth.getInstance().getUid();的值
只有当您对用户进行身份验证时,您才会将其设置为非null,否则它将为空或为空。