Using RecyclerView and getting information from Web services but not displaying answers and I’m not getting any errors WHY?

Tags: , ,



public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<BookData>> {
    private static final String GOOGLEBOOKURL = "https://www.googleapis.com/books/v1/volumes?q=search+terms";
    private static final String TAG = "Mainactivity";
  private   RecyclerView recyclerview;
    private RecyclerAdapter recyclerAdapter;
    private static final int BOOK_LOADER_ID = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<BookData> arrayList = new ArrayList<>();
        recyclerAdapter = new RecyclerAdapter(this,arrayList);
        recyclerview = (RecyclerView)findViewById(R.id.recyclerView);
       recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.setAdapter(recyclerAdapter);

        LoaderManager loaderManager = getSupportLoaderManager();
        Log.i(TAG, "Now calling initLoader");
        loaderManager.initLoader(BOOK_LOADER_ID, null, this);


        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        recyclerview.addItemDecoration(dividerItemDecoration);


    }

    @NonNull
    @Override
    public Loader<List<BookData>> onCreateLoader(int id, @Nullable Bundle args) {
        Log.i(TAG,"Problem with onCreateloader");
        return new BookLoader(MainActivity.this,GOOGLEBOOKURL);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<BookData>> loader, List<BookData> data) {
        recyclerAdapter.clear();
        if (data != null && !data.isEmpty()) {
            recyclerAdapter.addAll(data);
        }
    }

    @Override
    public void onLoaderReset(@NonNull Loader<List<BookData>> loader) {
        recyclerAdapter.clear();
        Log.i(TAG, "Now loader is resetting");
    }
}

Adapter

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    ArrayList<BookData> mArrayList;
    Context mContext;

    public RecyclerAdapter(Context context, ArrayList<BookData> arrayList) {
        mArrayList = arrayList;
        mContext = context;

    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ViewHolder viewHolder;
        LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
       View v = layoutInflater.inflate(R.layout.rowrepresent,parent,false);
       viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BookData currentPosition = mArrayList.get(position);
      //  holder.authorname.setText(currentPosition.getAuthorName());
        holder.titlename.setText(currentPosition.getTitleName());
      //  holder.mImageView.setImageResource(Integer.parseInt(currentPosition.getImage()));
    }

    @Override
    public int getItemCount() {
        return mArrayList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{

        ImageView mImageView;
        TextView titlename,authorname;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
          //  mImageView = (ImageView)itemView.findViewById(R.id.bookImage);
           titlename=(TextView)itemView.findViewById(R.id.titleName);
          //  authorname=(TextView)itemView.findViewById(R.id.authorName);
        }
    }
    public void clear() {
        if (mArrayList != null && !mArrayList.isEmpty()) {
            int size = mArrayList.size();
            mArrayList.clear();
            notifyItemRangeRemoved(0, size);
        }
    }

    public void addAll(List<BookData> data){
          mArrayList.addAll(data);
    }
}

Network

public class Network {
    private static final String TAG = "Network";

    public static ArrayList<BookData> extractbooksfromurl(String requesturl){
        ArrayList<BookData> BookDetails;
        URL url = createUrl(requesturl);

        String jsonresponse = null;
        try {
            jsonresponse = makeHttprequest(url);
        } catch (IOException e) {
            Log.e(TAG, "Error closing input stream", e);
        }

        BookDetails = extractInfojson(jsonresponse);
        return BookDetails;
    }

    private static URL createUrl(String requestUrl) {
        URL url = null;
        try {
            url = new URL(requestUrl);
        } catch (MalformedURLException e) {
            Log.e(TAG, "The problem with URL", e);
        }
        return url;
    }

    private static String makeHttprequest(URL url) throws IOException {
        String jsonresponse = "";
        if (url == null) {
            return jsonresponse;
        }
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(1000);
            urlConnection.setReadTimeout(1500);
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonresponse = readfromstream(inputStream);
            } else {
                Log.e(TAG, "Error response code:" + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(TAG, "problem with MakeHttprequest method", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonresponse;
    }

    private static String readfromstream(InputStream inputStream)throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream!= null){
            InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader bufferedReader = new BufferedReader(reader);
            try {
                String line = bufferedReader.readLine();
                while (line!=null ){
                    output.append(line);
                    line = bufferedReader.readLine();
                }

            } catch (IOException e) {
                Log.e(TAG,"Problem in readfromstream method",e);
            }
        } return output.toString();

    }
    public  static ArrayList<BookData> extractInfojson(String bookListData){
        if (TextUtils.isEmpty(bookListData)){
            return  null;
        }
        ArrayList<BookData> arrayListnew = new ArrayList<>();
        String authorsName = "";
        String title;
        String images;
        try {
            JSONObject jsonRootObject = new JSONObject(bookListData);
            JSONArray jsonArray = jsonRootObject.optJSONArray("item");
            if (jsonArray != null) {
                for (int i = 0; i<jsonArray.length(); i++){
                    JSONObject jsonObject = jsonArray.optJSONObject(i);
                    JSONObject volumeinfo = jsonObject.getJSONObject("volumeInfo");
                  /* JSONArray authors_list ;
                   if (volumeinfo.has("authors")){
                      authors_list = volumeinfo.getJSONArray("authors");
                       for (int y=0;y<authors_list.length();y++)
                           authorsName = authors_list.getString(y);
                   }else{
                       authorsName ="No Author";
                   }
                    title = volumeinfo.getString("title").toString();
                    JSONObject image = volumeinfo.getJSONObject("imageLinks");
                           images = image.getString("thumbnail").toString();*/
                   title = volumeinfo.getString("title").toString();
                    arrayListnew.add(new BookData(title));
                }
            }

        } catch (JSONException e) {
            Log.e(TAG,"problem in parsing the data",e);
        }
    return arrayListnew;
    }


}

Logcats

2020-11-21 11:27:29.407 12457-12457/com.example.booklistapp I/Mainactivity: Now calling initLoader
2020-11-21 11:27:29.407 12457-12457/com.example.booklistapp I/Mainactivity: Problem with onCreateloader
2020-11-21 11:27:29.412 12457-12457/com.example.booklistapp I/BookLoader: Now onStartLoading method
2020-11-21 11:27:29.417 12457-12472/com.example.booklistapp I/BookLoader: Now LoadinBackground method
2020-11-21 11:27:29.426 12457-12472/com.example.booklistapp D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2020-11-21 11:27:29.496 12457-12473/com.example.booklistapp I/OpenGLRenderer: Initialized EGL, version 1.4
2020-11-21 11:27:29.496 12457-12473/com.example.booklistapp D/OpenGLRenderer: Swap behavior 1
2020-11-21 11:27:29.496 12457-12473/com.example.booklistapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2020-11-21 11:27:29.496 12457-12473/com.example.booklistapp D/OpenGLRenderer: Swap behavior 0
2020-11-21 11:27:29.575 12457-12473/com.example.booklistapp D/EGL_emulation: eglCreateContext: 0x9b827520: maj 2 min 0 rcv 2
2020-11-21 11:27:29.688 12457-12473/com.example.booklistapp D/EGL_emulation: eglMakeCurrent: 0x9b827520: ver 2 0 (tinfo 0x9b89ad10)
2020-11-21 11:27:29.733 12457-12473/com.example.booklistapp D/EGL_emulation: eglMakeCurrent: 0x9b827520: ver 2 0 (tinfo 0x9b89ad10)

SomeBody help me in this one,I’m not getting any errors but Still answers not displaying ? why? Thank you.

Answer

In your Recyclerview adapter addAll method, after adding to the array make a call to notifyDataSetChanged()

like this:

public void addAll(List<BookData> data) {
      mArrayList.addAll(data);
      notifyDataSetChanged();
}

Update:

As per comments the code works when you use dummy data and this points to another issue in your network request logic. You can debug your application by placing various breakpoints in methods or on lines of code to help ascertain where your codes logic is not functioning as expected. https://developer.android.com/studio/debug Any other questions you have should be in a new question as this one is really solved.

Id also suggest using a library like Volley which will greatly simplify your network requests. Specifically see Making a standard request in Volley



Source: stackoverflow