-3

I am making classified marketplace android app. So, I have to show ads or post done by people on my home page, all is working and I am getting all my post on postman but not on my recycleview.

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() method is not called as i am not able to see any post but init() method is working and showing all the post when clicking on search button. And both methods are using same code, the only difference of the query that I am making, do not know why welcome() method is not showing any post.

halfer
  • 19,824
  • 17
  • 99
  • 186

3 Answers3

0

Actually, Your method is called from onCreate() but your condition (!currentuser.equals("") is return false.

  • i tried removing (!currentuser.equals("") condition but then also i am not getting any result – Vishal Sharma May 14 '18 at 12:01
  • use debugger and check where is the issue. –  May 14 '18 at 12:05
  • onResponse: server response: Response{protocol=http/1.1, code=401, message=Unauthorized, url=http://35.188.133.114//elasticsearch/posts/post/_search?default_operator=AND&q=*} – Vishal Sharma May 14 '18 at 14:03
0

This is issue with Firbase issue, Please check the firebase instance is configured and initialized properly in your application class. Then you should not able to get currentUser == "".

Firebase will return 401/410 error code incase of invalid user token / authentication with invalid user information.

RajeshVijayakumar
  • 10,281
  • 11
  • 57
  • 84
0

See the value of currentuser = FirebaseAuth.getInstance().getUid();
Only if you authenticate the user,then you will have this as not null else it will be empty or null.

Koustuv Ganguly
  • 897
  • 7
  • 21