recyclerview not show multiple data from Json - java

my recyclerview show one data but i receive multiple data in logcat in the form of json
Here is main file
Stitle.java
package com.desktop.app;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Stitle extends AppCompatActivity {
EditText searchtitle;
private RequestQueue requestQueue ;
private List<list> productList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerView.Adapter listAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stitle);
searchtitle = findViewById(R.id.searchtitle);
searchtitle.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
foji();
setContentView(R.layout.activity_smain);
listAdapter = new listAdapter(Stitle.this,productList);
recyclerView = (RecyclerView) findViewById(R.id.recylcerView);
recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(Stitle.this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(listAdapter);
return true;
}
return false;
}
});
}
public void foji(){
RequestQueue requestQueue=Volley.newRequestQueue(this);
Uri.Builder builder=new Uri.Builder();
builder.scheme("http")
.authority("192.168.0.136")
.appendPath("fyp")
.appendPath("stitle.php")
.appendQueryParameter("Title",searchtitle.getText().toString());
StringRequest stringRequest=new StringRequest(Request.Method.POST, builder.build().toString(), new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("Info",response.toString());
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("search");
for(int i=0;i<jsonArray.length();i++){
JSONObject product=jsonArray.getJSONObject(i);
boolean add = productList.add(new list(
product.getLong("isbn"),
product.getString("title"),
product.getString("authors"),
product.getInt("accession"),
product.getString("publisher"),
product.getInt("pubyear"),
product.getInt("pages"),
product.getInt("rak"),
product.getInt("hr"),
product.getInt("vr"),
product.getLong("barcode")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Stitle.this, "Foji Error", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
}
}
Here is file for setter and getter
list.java
package com.desktop.app;
import java.io.Serializable;
public class list implements Serializable {
private long isbn;
private String title;
private String authors;
private int accession;
private String publisher;
private int pubyear;
private int pages;
private int rak;
private int hr;
private int vr;
private long barcode;
public list(long isbn, String title, String authors, int accession, String publisher, int pubyear, int pages, int rak, int hr, int vr, long barcode) {
this.isbn = isbn;
this.title = title;
this.authors = authors;
this.accession = accession;
this.publisher = publisher;
this.pubyear = pubyear;
this.pages = pages;
this.rak = rak;
this.hr = hr;
this.vr = vr;
this.barcode = barcode;
}
public long getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public String getAuthors() {
return authors;
}
public int getAccession() {
return accession;
}
public String getPublisher() {
return publisher;
}
public int getPubyear(){
return pubyear;
}
public int getPages(){
return pages;
}
public int getRak(){
return rak;
}
public int getHr(){
return hr;
}
public int getVr(){
return vr;
}
public long getBarcode() {
return barcode;
}
public void setIsbn(long isbn) {
this.isbn = isbn;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public void setAccession(int accession) {
this.accession = accession;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public void setPubyear(int pubyear) {
this.pubyear = pubyear;
}
public void setPages(int pages) {
this.pages = pages;
}
public void setRak(int rak) {
this.rak = rak;
}
public void setHr(int hr) {
this.hr = hr;
}
public void setVr(int vr) {
this.vr = vr;
}
public void setBarcode(long barcode) {
this.barcode = barcode;
}
}
Here is file of lisAdapter
listAdapter.java
package com.desktop.app;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
public class listAdapter extends RecyclerView.Adapter<listAdapter.ProductViewHolder> {
RequestOptions options ;
private Context mCtx;
private List<list> pdata;
listAdapter(Context mCtx, List productList) {
this.mCtx = mCtx;
this.pdata = productList;
}
#Override
public ProductViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View view ;
LayoutInflater inflater = LayoutInflater.from(mCtx);
view = inflater.inflate(R.layout.slist,parent,false);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder( ProductViewHolder holder, final int position) {
list product = pdata.get(position);
holder.textviewisbn.setText(String.valueOf(product.getIsbn()));
holder.textviewtitle.setText(product.getTitle());
holder.textviewauthors.setText(product.getAuthors());
holder.textviewacc.setText(String.valueOf(product.getAccession()));
holder.textviewpublisher.setText(product.getPublisher());
holder.textviewpubyear.setText(String.valueOf(product.getPubyear()));
}
#Override
public int getItemCount() {
return pdata.size();
}
public static class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textviewisbn, textviewtitle, textviewauthors, textviewacc, textviewpublisher, textviewpubyear;
public ProductViewHolder(View itemView) {
super(itemView);
textviewisbn = itemView.findViewById(R.id.textviewisbn);
textviewtitle = itemView.findViewById(R.id.textviewtitle);
textviewauthors = itemView.findViewById(R.id.textviewauthors);
textviewacc = itemView.findViewById(R.id.textviewacc);
textviewpublisher = itemView.findViewById(R.id.textviewpublisher);
textviewpubyear = itemView.findViewById(R.id.textviewpubyear);
}
}
}
slist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/textviewisbn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_above="#id/textviewtitle"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewauthors"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewtitle"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small" />
<TextView
android:id="#+id/textviewacc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewauthors"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpublisher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewacc"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpubyear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewpublisher"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
recylerview xml file
activity_smain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.desktop.app.listactivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="745dp"
tools:layout_editor_absoluteY="-51dp" >
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Recyclerview show one data but i receive multiple data in logcat in the form of json
I/Info: {"status":true,"search":[{"isbn":195472462,"title":"Oxford Practice Grammer","authors":"john Eastwood","accession":1,"publisher":"Ameena Saiyid Oxford University","pubyear":2014,"pages":432,"rak":1,"hr":1,"vr":1,"barcode":195472462},{"isbn":9694946719,"title":"High School English Grammer ","authors":"Wren, martin","accession":4,"publisher":"Paramount Publishing","pubyear":2010,"pages":418,"rak":1,"hr":1,"vr":4,"barcode":9694946719}]}
this data recieve as json but only one record show in list image show's that only one record on list

You can see the data on scroll because you have set the list item height to
match_parent.. you just need to set it to wrap_content
slist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/textviewisbn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_above="#id/textviewtitle"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#000000" />
<TextView
android:id="#+id/textviewauthors"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewtitle"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small" />
<TextView
android:id="#+id/textviewacc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewauthors"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small.Inverse"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpublisher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewacc"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
<TextView
android:id="#+id/textviewpubyear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/textviewpublisher"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>

Related

keep getting error "Unresolved reference: valueOf"

In in the notes portion of my app i get the error "Unresolved reference: valueOf" in my EquipmentTrackerAllnotes.kt file.
the way my app operates is when you open the app initially it opens up to the dashboard the main home screen, then there is a navigation drawer on the side. One of the fragments in the navigation drawer is my "EquipmentTracker" aka the area where you can make notes of equipment the user may have. In side there you can add notes, delete and edit.
I'm open ears to any recommendations on possible changes i should make as well. But for now my main focus is fixing this error listed above.
EquipmentTracker.kt
package com.example.mechanicsapp
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.mechanicsapp.Model.noteModel
import com.example.mechanicsapp.database.MySqliteHelper
import com.example.mechanicsapp.databinding.FragmentEquipmentTrackerBinding
class EquipmentTracker : Fragment() {
private var _binding: FragmentEquipmentTrackerBinding? = null
private val binding get() = _binding!!
var intent = Intent(requireContext(), EquipmentTracker::class.java)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
//return inflater.inflate(R.layout.sign_in_fragment, container, false)
// Inflate the layout for this fragment
_binding = FragmentEquipmentTrackerBinding.inflate(inflater, container, false)
binding.root
val helper = MySqliteHelper(requireContext())
binding.btnDisplay.setOnClickListener(View.OnClickListener {
intent = Intent(activity, FragmentEquipmentTrackerBinding::class.java)
startActivity(intent)
return#OnClickListener
})
binding.btnSave.setOnClickListener(View.OnClickListener {
val model = noteModel()
model.bumpernumber = binding.bumpernumber.text.toString()
model.description = binding.description.text.toString()
model.nsn = binding.nsn.text.toString()
model.serialnumber = binding.serialnumber.text.toString()
model.date = binding.date.text.toString()
if (model.bumpernumber.isEmpty()) {
binding.bumpernumber.error = "Enter bumper number"
return#OnClickListener
}
if (model.description.isEmpty()) {
binding.description.error = "Enter description"
return#OnClickListener
}
if (model.nsn.isEmpty()) {
binding.nsn.error = "Enter nsn"
return#OnClickListener
}
if (model.serialnumber.isEmpty()) {
binding.serialnumber.error = "Enter serial number"
return#OnClickListener
}
if (model.date.isEmpty()) {
binding.date.error = "Enter date"
return#OnClickListener
}
val r = helper.saveNote(model)
if (r) {
Toast.makeText(context, "note is saved", Toast.LENGTH_SHORT)
.show()
} else {
Toast.makeText(context, "some thing want wrong", Toast.LENGTH_SHORT)
.show()
}
})
return binding.root
}
}
EquipmentTrackerAllnotes.kt
package com.example.mechanicsapp
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.mechanicsapp.Model.noteModel
import com.example.mechanicsapp.adapter.NoteAdapter
import com.example.mechanicsapp.database.MySqliteHelper
import com.example.mechanicsapp.databinding.ActivityEquipmentTrackerAllnotesBinding
#Suppress("NAME_SHADOWING")
class EquipmentTrackerAllnotes : AppCompatActivity() {
private var adapter: NoteAdapter? = null
private var binding: ActivityEquipmentTrackerAllnotesBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEquipmentTrackerAllnotesBinding.inflate(layoutInflater)
setContentView(binding!!.root)
fetchNotes()
}
private fun fetchNotes() {
val helper = MySqliteHelper(this)
adapter = NoteAdapter(this, helper.allNotes)
adapter!!.setOnNoteItemClickListener(object : NoteAdapter.OnNoteItemClickListener {
override
fun Onclick(model: noteModel) {
val builder = AlertDialog.Builder(this#EquipmentTrackerAllnotes)
builder.setTitle("Important")
builder.setMessage("Are your sure?")
builder.setPositiveButton("Yes" ) {
dialogInterface, _ ->
val helper = MySqliteHelper(this#EquipmentTrackerAllnotes)
val check = helper.delNoteById(String.valueOf(model.id))
if (check) {
fetchNotes()
Toast.makeText(this#EquipmentTrackerAllnotes, "Deleted", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(
this#EquipmentTrackerAllnotes,
"something went wrong",
Toast.LENGTH_SHORT
).show()
}
dialogInterface.dismiss()
}.setNegativeButton(
"No"
) { dialogInterface, _ -> dialogInterface.dismiss() }
builder.create().show()
}
override fun OnEdit(model: noteModel) {
val builder = AlertDialog.Builder(this#EquipmentTrackerAllnotes)
val view: View = LayoutInflater.from(this#EquipmentTrackerAllnotes)
.inflate(R.layout.edit_note, null, false)
val bm = view.findViewById<EditText>(R.id.bumpernumber)
val des = view.findViewById<EditText>(R.id.description)
val nsn = view.findViewById<EditText>(R.id.nsn)
val sn = view.findViewById<EditText>(R.id.serialnumber)
val date = view.findViewById<EditText>(R.id.date)
val btnUpdate = view.findViewById<Button>(R.id.btnUpdate)
bm.setText(model.bumpernumber)
des.setText(model.description)
nsn.setText(model.nsn)
sn.setText(model.serialnumber)
date.setText(model.date)
builder.setView(view)
val alertDialog = builder.create()
btnUpdate.setOnClickListener {
val model1 = noteModel()
model1.id = model.id
model1.bumpernumber = bm.text.toString()
model1.description = des.text.toString()
model1.nsn = nsn.text.toString()
model1.serialnumber = sn.text.toString()
model1.date = date.text.toString()
updateNote(model1)
alertDialog.dismiss()
}
alertDialog.show()
}
})
this.binding?.recyclerView?.setHasFixedSize(true)
this.binding?.recyclerView?.layoutManager = LinearLayoutManager(this)
this.binding?.recyclerView?.adapter = adapter
}
private fun updateNote(model: noteModel) {
val helper = MySqliteHelper(this#EquipmentTrackerAllnotes)
val check = helper.updateNoteById(model)
if (check) {
fetchNotes()
Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "something went wrong", Toast.LENGTH_SHORT).show()
}
}
}
in my adapter folder I have NoteAdapter.java
NoteAdapter.java
package com.example.mechanicsapp.adapter;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mechanicsapp.Model.noteModel;
import com.example.mechanicsapp.R;
import com.example.mechanicsapp.database.MySqliteHelper;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.viewHolder> {
List<noteModel> list;
Activity activity;
OnNoteItemClickListener listener;
public NoteAdapter(Activity activity,List<noteModel> list) {
this.list=list;
this.activity=activity;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.row_note,null,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
noteModel model=list.get(position);
holder.bumpernumber.setText(model.getBumpernumber());
holder.description.setText(model.getDescription());
holder.nsn.setText(model.getNsn());
holder.serialnumber.setText(model.getSerialnumber());
holder.date.setText(model.getDate());
holder.more.setOnClickListener(view -> {
PopupMenu menu=new PopupMenu(activity,holder.more);
menu.getMenuInflater().inflate(R.menu.more_menu,menu.getMenu());
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.edit:
listener.OnEdit(model);
break;
case R.id.delete:
listener.Onclick(model);
break;
}
return false;
}
});
menu.show();
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class viewHolder extends RecyclerView.ViewHolder{
TextView bumpernumber,description,nsn,serialnumber,date;
ImageView more;
public viewHolder(#NonNull View itemView) {
super(itemView);
bumpernumber=itemView.findViewById(R.id.bumpernumber);
description=itemView.findViewById(R.id.description);
nsn=itemView.findViewById(R.id.nsn);
serialnumber=itemView.findViewById(R.id.serialnumber);
date=itemView.findViewById(R.id.date);
more=itemView.findViewById(R.id.more);
}
}
public interface OnNoteItemClickListener{
void Onclick(noteModel model);
void OnEdit(noteModel model);
}
public void setOnNoteItemClickListener(OnNoteItemClickListener listener){
this.listener=listener;
}
}
in my database folder i have MySqliteHelper.java & TableSchema.java
MySqliteHelper.java
package com.example.mechanicsapp.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import com.example.mechanicsapp.Model.noteModel;
import java.util.ArrayList;
import java.util.List;
public class MySqliteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="note.db";
private static final int VERSION=1;
public MySqliteHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String table1="create table "+TableSchema.note.TABLE_NAME+"("+TableSchema.note.ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+TableSchema.note.BUMPERNUMBER+" TEXT, "+TableSchema.note.DESCRIPTION+" TEXT,"+TableSchema.note.NSN+" TEXT,"+TableSchema.note.SERIALNUMBER+" TEXT, "+TableSchema.note.DATE+" TEXT );";
sqLiteDatabase.execSQL(table1);
}
public boolean saveNote(noteModel model){
SQLiteDatabase database=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
cv.put(TableSchema.note.DESCRIPTION,model.getDescription());
cv.put(TableSchema.note.NSN,model.getNsn());
cv.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
cv.put(TableSchema.note.DATE,model.getDate());
long id= database.insert(TableSchema.note.TABLE_NAME,null,cv);
return id != -1;
}
public List<noteModel> getAllNotes(){
SQLiteDatabase database= this.getReadableDatabase();
String[] cols={TableSchema.note.ID,TableSchema.note.BUMPERNUMBER,TableSchema.note.DESCRIPTION,TableSchema.note.NSN,TableSchema.note.SERIALNUMBER,TableSchema.note.DATE};
Cursor cursor=database.query(TableSchema.note.TABLE_NAME,cols,null,null,null,null,TableSchema.note.ID+" DESC");
ArrayList<noteModel> list=new ArrayList<>();
while (cursor.moveToNext()){
noteModel model=new noteModel();
model.setId(cursor.getInt(cursor.getColumnIndexOrThrow(TableSchema.note.ID)));
model.setBumpernumber(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.BUMPERNUMBER)));
model.setDescription(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.DESCRIPTION)));
model.setNsn(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.NSN)));
model.setSerialnumber(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.SERIALNUMBER)));
model.setDate(cursor.getString(cursor.getColumnIndexOrThrow(TableSchema.note.DATE)));
list.add(model);
}
cursor.close();
database.close();
return list;
}
public boolean delNoteById(String id){
SQLiteDatabase database=this.getWritableDatabase();
int d_id=database.delete(TableSchema.note.TABLE_NAME,TableSchema.note.ID+"=?",new String[]{id});
if (d_id==-1){
database.close();
return false;
}
database.close();
return true;
}
public boolean updateNoteById(noteModel model){
SQLiteDatabase database=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(TableSchema.note.BUMPERNUMBER,model.getBumpernumber());
values.put(TableSchema.note.DESCRIPTION,model.getDescription());
values.put(TableSchema.note.NSN,model.getNsn());
values.put(TableSchema.note.SERIALNUMBER,model.getSerialnumber());
values.put(TableSchema.note.DATE,model.getDate());
int u_id=database.update(TableSchema.note.TABLE_NAME,values,TableSchema.note.ID+"=?",new String[]{String.valueOf(model.getId())});
if (u_id==-1){
database.close();
return false;
}
database.close();
return true;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
if (i<i1){
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TableSchema.note.TABLE_NAME);
}
}
}
TableSchema.java
package com.example.mechanicsapp.database;
public class TableSchema {
public static class note{
public static final String TABLE_NAME="tbl_note";
public static final String ID="id";
public static final String BUMPERNUMBER="bumpernumber";
public static final String DESCRIPTION="description";
public static final String NSN="nsn";
public static final String SERIALNUMBER="serialnumber";
public static final String DATE="date";
}
}
in my Model folder i have noteModel.java
//noteModel.java
package com.example.mechanicsapp.Model;
public class noteModel {
private int id;
private String bumpernumber;
private String description;
private String nsn;
private String serialnumber;
private String date;
public noteModel() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBumpernumber() {
return bumpernumber;
}
public void setBumpernumber(String bumpernumber) {
this.bumpernumber = bumpernumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getNsn() {
return nsn;
}
public void setNsn(String nsn) {
this.nsn = nsn;
}
public String getSerialnumber() {
return serialnumber;
}
public void setSerialnumber(String serialnumber) {
this.serialnumber = serialnumber;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
fragment_equipment_tracker.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EquipmentTracker">
<LinearLayout
android:layout_centerInParent="true"
android:padding="10dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/bumpernumber"
android:hint="Bumper Number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/description"
android:hint="Enter description"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/nsn"
android:hint="Enter nsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/serialnumber"
android:hint="Enter serial number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/date"
android:hint="Enter date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnSave"
android:text="Save"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnDisplay"
android:text="Display"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
activity_equipment_tracker_allnotes.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EquipmentTrackerAllnotes">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
edit_note.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EquipmentTracker">
<LinearLayout
android:padding="10dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/bumpernumber"
android:hint="Bumper Number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/description"
android:hint="Enter description"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/nsn"
android:hint="Enter nsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/serialnumber"
android:hint="Enter serial number"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/date"
android:hint="Enter date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/btnUpdate"
android:text="Update"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
//row_note.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_margin="10dp"
android:padding="10dp"
cardElevation="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/bumpernumber"
android:textSize="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/nsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/serialnumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<ImageView
android:id="#+id/more"
android:src="#drawable/baseline_more_vert_24"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
more_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/edit" android:title="edit"/>
<item android:id="#+id/delete" android:title="Delete"/>
</menu>

Android RecyclerView Changes text to Image when scroll

Can anyone please help me out here???
Problem statement: I am making a chat application that is almost ready in ChatActivity. Functionality is the user can send images and text together but while sending text it's fine. The problem starts when I am sending images. And after sending when I scroll up to my all the texts start to change into the recently sent image.
ChatActivity.xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/bg_light"
tools:context=".ChatActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/backArrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_back_arrow"
app:tint="#color/white" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginStart="5dp"
android:padding="5dp"
android:src="#drawable/avatar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/backArrow"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/userName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="13dp"
android:fontFamily="#font/roboto"
android:text=""
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageView7"
app:layout_constraintStart_toEndOf="#+id/profile_image"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/lastSeen"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="2dp"
android:fontFamily="#font/roboto_light"
android:text=""
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageView7"
app:layout_constraintStart_toEndOf="#+id/profile_image"
app:layout_constraintTop_toBottomOf="#+id/userName" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="-22dp" />
<androidx.constraintlayout.widget.Barrier
android:id="#+id/barrier2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="left"
tools:layout_editor_absoluteX="395dp" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_more"
app:tint="#color/white" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/chatRecyclerView"
android:layout_width="match_parent"
android:layout_height="611dp"
android:nestedScrollingEnabled="false">
</androidx.recyclerview.widget.RecyclerView>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="4dp">
<View
android:id="#+id/view14"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:background="#drawable/follow_active_btn"
app:layout_constraintBottom_toBottomOf="#+id/etMessage"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/etMessage" />
<EditText
android:id="#+id/etMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginBottom="4dp"
android:background="#color/transparent"
android:ems="10"
android:hint="Message"
android:inputType="textMultiLine"
android:maxLines="4"
android:minHeight="48dp"
android:paddingStart="4dp"
android:paddingLeft="4dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/sendMessageImage"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/sendMessage"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_marginEnd="8dp"
android:padding="4dp"
app:layout_constraintBottom_toBottomOf="#+id/etMessage"
app:layout_constraintEnd_toEndOf="#+id/view14"
app:layout_constraintTop_toTopOf="#+id/etMessage"
app:srcCompat="#drawable/comment"
app:tint="#color/purple_500" />
<ImageView
android:id="#+id/sendMessageImage"
android:layout_width="36dp"
android:layout_height="36dp"
android:padding="4dp"
app:layout_constraintBottom_toBottomOf="#+id/sendMessage"
app:layout_constraintEnd_toStartOf="#+id/sendMessage"
app:layout_constraintTop_toTopOf="#+id/sendMessage"
app:srcCompat="#drawable/clip"
app:tint="#color/black" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
ChatAdapter.java -
package com.codinggeekers.lmsbeta.Adapter;
import android.content.Context;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.codinggeekers.lmsbeta.Models.MessageModel;
import com.codinggeekers.lmsbeta.R;
import com.google.firebase.auth.FirebaseAuth;
import com.squareup.picasso.Picasso;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class ChatAdapter extends RecyclerView.Adapter {
ArrayList<MessageModel> list;
Context context;
int SENDER_VIEW_TYPE = 1;
int RECEIVER_VIEW_TYPE = 2;
public ChatAdapter(ArrayList<MessageModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == SENDER_VIEW_TYPE) {
View view = LayoutInflater.from(context).inflate(R.layout.sample_sender, parent, false);
return new SenderViewHolder(view);
}
else {
View view = LayoutInflater.from(context).inflate(R.layout.sample_receiver, parent, false);
return new ReceiverViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
MessageModel message = list.get(position);
Timestamp ts = new Timestamp(message.getTimestamp());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
String time = simpleDateFormat.format(ts.getTime());
RequestOptions requestOptions = new RequestOptions();
requestOptions = requestOptions.transforms(new CenterCrop(), new RoundedCorners(10));
if(holder.getClass() == SenderViewHolder.class) {
if (message.getMsgImg()!=null) {
((SenderViewHolder)holder).senderImageLayout.setVisibility(View.VISIBLE);
((SenderViewHolder)holder).senderTextLayout.setVisibility(View.GONE);
// Picasso.get().load(message.getMsgImg()).placeholder(R.drawable.placeholder).into(((SenderViewHolder)holder).senderImage);
Glide.with(((SenderViewHolder)holder).itemView.getContext()).load(message.getMsgImg()).apply(requestOptions)
.placeholder(R.drawable.placeholder).into(((SenderViewHolder)holder).senderImage);
} else {
((SenderViewHolder)holder).senderMsg.setText(message.getMessage());
((SenderViewHolder)holder).senderTime.setText(time);
}
}
else {
if (message.getMsgImg()!=null) {
((ReceiverViewHolder)holder).receiverImageLayout.setVisibility(View.VISIBLE);
// Picasso.get().load(message.getMsgImg()).placeholder(R.drawable.placeholder).into(((ReceiverViewHolder)holder).receiverImage);
Glide.with(((ReceiverViewHolder)holder).itemView.getContext()).load(message.getMsgImg()).apply(requestOptions)
.placeholder(R.drawable.placeholder).into(((ReceiverViewHolder)holder).receiverImage);
} else {
((ReceiverViewHolder)holder).receiverMsg.setText(message.getMessage());
((ReceiverViewHolder)holder).receiverTime.setText(time);
}
}
}
#Override
public int getItemViewType(int position) {
if(list.get(position).getuId().equals(FirebaseAuth.getInstance().getUid())) {
return SENDER_VIEW_TYPE;
}
else {
return RECEIVER_VIEW_TYPE;
}
}
#Override
public int getItemCount() {
return list.size();
}
public class ReceiverViewHolder extends RecyclerView.ViewHolder {
TextView receiverMsg, receiverTime;
ImageView receiverImage;
ConstraintLayout receiverImageLayout;
public ReceiverViewHolder(#NonNull View itemView) {
super(itemView);
receiverMsg = itemView.findViewById(R.id.receiverText);
receiverTime = itemView.findViewById(R.id.receiverTime);
receiverImage = itemView.findViewById(R.id.receiverImage);
receiverImageLayout = itemView.findViewById(R.id.imageConstraintLayoutReceiver);
}
}
public class SenderViewHolder extends RecyclerView.ViewHolder {
TextView senderMsg, senderTime;
ImageView senderImage;
ConstraintLayout senderImageLayout;
ConstraintLayout senderTextLayout;
public SenderViewHolder(#NonNull View itemView) {
super(itemView);
senderMsg = itemView.findViewById(R.id.senderText);
senderTime = itemView.findViewById(R.id.senderTime);
senderImage = itemView.findViewById(R.id.senderImage);
senderImageLayout = itemView.findViewById(R.id.imageConstraintLayoutSender);
senderTextLayout = itemView.findViewById(R.id.textConstraintLayoutSender);
}
}
}
ChatActivity.java -
package com.codinggeekers.lmsbeta;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import com.codinggeekers.lmsbeta.Adapter.ChatAdapter;
import com.codinggeekers.lmsbeta.Models.MessageModel;
import com.codinggeekers.lmsbeta.databinding.ActivityChatBinding;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Date;
public class ChatActivity extends AppCompatActivity {
ActivityChatBinding binding;
ProgressDialog dialog;
FirebaseAuth auth;
FirebaseDatabase database;
FirebaseStorage storage;
ActivityResultLauncher<String> galleryLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChatBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
storage = FirebaseStorage.getInstance();
dialog = new ProgressDialog(this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setTitle("Sending Image...");
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
// Sender and Receiver Ids
final String senderId = auth.getUid();
String receiveId = getIntent().getStringExtra("userId");
String userName = getIntent().getStringExtra("userName");
String profilePic = getIntent().getStringExtra("profilePic");
binding.userName.setText(userName);
Picasso.get().load(profilePic).placeholder(R.drawable.avatar).into(binding.profileImage);
binding.backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatActivity.this, UsersChatActivity.class);
startActivity(intent);
}
});
final ArrayList<MessageModel> messageModels = new ArrayList<MessageModel>();
final ChatAdapter chatAdapter = new ChatAdapter(messageModels, this);
binding.chatRecyclerView.setAdapter(chatAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
binding.chatRecyclerView.setHasFixedSize(true);
binding.chatRecyclerView.setLayoutManager(layoutManager);
final String senderRoom = senderId + receiveId;
final String receiverRoom = receiveId + senderId;
database.getReference().child("Chats")
.child(senderRoom)
.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageModels.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
MessageModel model = snapshot1.getValue(MessageModel.class);
messageModels.add(model);
}
chatAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
binding.sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = binding.etMessage.getText().toString();
if (message.matches("")) {
} else {
final MessageModel model = new MessageModel(senderId, message, "text");
model.setTimestamp(new Date().getTime());
binding.etMessage.setText("");
database.getReference().child("Chats")
.child(senderRoom)
.push()
.setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(#NonNull Void unused) {
database.getReference().child("Chats").child(receiverRoom).push().setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(#NonNull Void unused) {
}
});
}
});
}
}
});
binding.sendMessageImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryLauncher.launch("image/*");
}
});
galleryLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
dialog.show();
final StorageReference reference = storage.getReference().child("chats")
.child(senderRoom).child(new Date().getTime() + "");
reference.putFile(result).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final MessageModel model = new MessageModel(senderId, new Date().getTime(), uri.toString(), "image");
database.getReference()
.child("Chats")
.child(senderRoom)
.push()
.setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
database.getReference().child("Chats").child(receiverRoom).push().setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
dialog.dismiss();
binding.sendMessageImage.setImageURI(Uri.EMPTY);
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
});
}
});
}
});
}
});
binding.userName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatActivity.this, FriendsProfileActivity.class);
intent.putExtra("userName", userName);
intent.putExtra("userId", receiveId);
intent.putExtra("profilePic", profilePic);
startActivity(intent);
}
});
}
}
ItemViewType should start at 0.
Try to change them to this:
int SENDER_VIEW_TYPE = 0;
int RECEIVER_VIEW_TYPE = 1;

Recycler View not getting Displayed (in Card View) for weather app. Tried solutions from Stack Overflow. Nothing is Working

I am trying to develop an application in android with the help of Geeks for Geeks tutorials. I am still learning how to develop android apps. It is a simple weather app where I need to display forecast in recycler view with the help of card view. The code is as shown from the video, but still the recycler view is not getting displayed. API url is also working. There is no error shown.
App Permissions - Location and Internet (Added in Manifest)
It was a request to please help me out with this issue.
Please do reply.
Main_Activity.java file is just a splash screen.
Main_Activity2.java
package com.androidp.wheatherapp;
import androidx.annotation.NonNull;
import androidx.appcompat.
app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private RelativeLayout rlayout;
private ProgressBar pbar;
private TextView cityNameiv;
private TextView temp;
private TextView condi;
private EditText editCity;
private ImageView IVsearch,ivicon,backIV;
private RecyclerView recyclerWeather;
private ArrayList<WeatherModal> weatherModalArrayList;
private weatherAdapter adapter;
private String cityName;
private LocationManager locationManager;
private int PERMISSION_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
rlayout = findViewById(R.id.rlayout);
pbar = findViewById(R.id.pbar);
cityNameiv = findViewById(R.id.cityName);
temp = findViewById(R.id.temp);
condi = findViewById(R.id.condi);
editCity = findViewById(R.id.editCity);
ivicon = findViewById(R.id.ivicon);
IVsearch = findViewById(R.id.IVsearch);
recyclerWeather = findViewById(R.id.recyclerWeather);
backIV = findViewById(R.id.backIV);
weatherModalArrayList = new ArrayList<>();
adapter = new weatherAdapter(this,weatherModalArrayList);
recyclerWeather.setAdapter(adapter);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity2.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_CODE);
}
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
cityName = getCityName(location.getLongitude(), location.getLatitude());
getweatherInfo(cityName);
IVsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city = editCity.getText().toString();
if(city.isEmpty()){
Toast.makeText(MainActivity2.this,"Please Enter City Name",Toast.LENGTH_SHORT).show();
}
else {
cityNameiv.setText(cityName);
getweatherInfo(city);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == PERMISSION_CODE){
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this,"Allow Permissions",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private String getCityName(double longitude, double latitude){
String cityName = "Not Found";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(latitude,longitude,10);
for (Address adr : addresses){
if(adr!= null){
String city = adr.getLocality();
if(city!= null && !city.equals("")){
cityName = city;
}
else {
Log.d("TAG","User City not found");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
private void getweatherInfo(String cityName){
String url="https://api.weatherapi.com/v1/forecast.json?key=deadad1688ef46f8929170126213010&q="+ cityName+"&days=1&aqi=no&alerts=no";
//cityNameiv.setText(cityName);
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity2.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pbar.setVisibility(View.GONE);
rlayout.setVisibility(View.VISIBLE);
//weatherModalArrayList.clear();
try {
String temperature = response.getJSONObject("current").getString("temp_c");
temp.setText(temperature + " °c");
int isDay = response.getJSONObject("current").getInt("is_day");
String condition = response.getJSONObject("current").getJSONObject("condition").getString("text");
String condiicon = response.getJSONObject("current").getJSONObject("condition").getString("icon");
Picasso.get().load("https:".concat(condiicon)).into(ivicon);
condi.setText(condition);
if(isDay==1){
Picasso.get().load("https://wallpaperaccess.com/full/929229.jpg").into(backIV);
}
else {
Picasso.get().load("https://wallpaperaccess.com/full/929229.jpg").into(backIV);
}
JSONObject forecastObj = response.getJSONObject("forecast");
JSONObject forecast0 = forecastObj.getJSONArray("forecastday").getJSONObject(0);
JSONArray hourarray = forecast0.getJSONArray("hour");
for(int i=0; i < hourarray.length();i++){
JSONObject hourobj = hourarray.getJSONObject(i);
String time = hourobj.getString("time");
String temp1 = hourobj.getString("temp_c");
String img = hourobj.getJSONObject("time").getString("icon");
String wind = hourobj.getString("wind_kph");
weatherModalArrayList.add(new WeatherModal(time,temp1,img,wind));
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,"Please enter valid city Name",Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pbar"
android:layout_centerInParent="true"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rlayout"
android:visibility="visible"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:id="#+id/backIV"
android:src="#color/black"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:gravity="center"
android:textColor="#color/white"
android:padding="20sp"
android:layout_marginTop="30dp"
android:textSize="18sp"
android:id="#+id/cityName"
android:text="City Name"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/idlin"
android:layout_below="#+id/cityName"
android:weightSum="5">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/editCity"
android:layout_margin="10sp"
android:layout_weight="4.5"
android:background="#color/white"
android:hint="Enter City"
android:padding="10dp"
app:hintTextColor="#color/purple_200"
/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:layout_margin="10dp"
android:tint="#color/white"
android:layout_gravity="center"
android:id="#+id/IVsearch"
android:src="#drawable/search"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/temp"
android:layout_margin="10dp"
android:gravity="center_horizontal"
android:padding="5dp"
android:textSize="70dp"
android:text="23"
android:textColor="#color/white"
android:layout_below="#id/idlin"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivicon"
android:layout_below="#id/temp"
android:src="#mipmap/ic_launcher"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/condi"
android:layout_margin="10dp"
android:gravity="center"
android:text="Condition"
android:textColor="#color/white"
android:textAlignment="center"
android:layout_below="#id/ivicon"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginBottom="10dp"
android:text="Today's Wheather Forecast"
android:layout_above="#id/recyclerWeather"
android:textColor="#color/white"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerWeather"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</RelativeLayout>
</RelativeLayout>
weatherAdapter.java
package com.androidp.wheatherapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class weatherAdapter extends RecyclerView.Adapter<weatherAdapter.ViewHolder> {
private Context context;
private ArrayList<WeatherModal> weatherModalArrayList;
public weatherAdapter(Context context, ArrayList<WeatherModal> weatherModalArrayList) {
this.context = context;
this.weatherModalArrayList = weatherModalArrayList;
}
#NonNull
#Override
public weatherAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.weather_rv,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull weatherAdapter.ViewHolder holder, int position) {
WeatherModal modal = weatherModalArrayList.get(position);
holder.idTemperature.setText(modal.getTemperature() + "°c");
Picasso.get().load("https:".concat(modal.getIcon())).into(holder.idCondition);
holder.wind.setText(modal.getWindSpeed()+"km/hr");
SimpleDateFormat input = new SimpleDateFormat("yyyy-mm-dd hh:mm");
SimpleDateFormat output = new SimpleDateFormat("hh:min aa");
try {
Date t = input.parse(modal.getTime());
holder.idTime.setText(output.format(t));
}catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return weatherModalArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView idTemperature, idTime, wind;
private ImageView idCondition;
public ViewHolder(#NonNull View itemView) {
super(itemView);
idCondition = itemView.findViewById(R.id.idCondition);
idTemperature = itemView.findViewById(R.id.idTemperature);
wind = itemView.findViewById(R.id.idTextview);
idTime = itemView.findViewById(R.id.idTime);
}
}
}
WeatherModal.java
package com.androidp.wheatherapp;
public class WeatherModal {
private String Time;
private String Temperature;
private String icon;
private String windSpeed;
public WeatherModal(String time, String temperature, String icon, String windSpeed) {
Time = time;
Temperature = temperature;
this.icon = icon;
this.windSpeed = windSpeed;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getTemperature() {
return Temperature;
}
public void setTemperature(String temperature) {
Temperature = temperature;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getWindSpeed() {
return windSpeed;
}
public void setWindSpeed(String windSpeed) {
this.windSpeed = windSpeed;
}
}
weather_rv.xml - Card View
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center"
app:cardElevation="6dp"
app:cardCornerRadius="10dp"
android:layout_margin="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/card_bag"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idTime"
android:gravity="center"
android:padding="4dp"
android:text="TIME"
android:textColor="#color/black"
android:textAlignment="center"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idTemperature"
android:gravity="center"
android:textSize="20sp"
android:text="20"
android:textAlignment="center"
android:layout_below="#+id/idTime"
android:textColor="#color/white"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#+id/idTemperature"
android:id="#+id/idCondition"
android:layout_centerHorizontal="true"
android:layout_margin="5dp"
android:padding="4dp"
android:src="#drawable/ic_launcher_foreground"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:layout_below="#id/idCondition"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/idTextview"
android:textColor="#color/white"
android:padding="3dp"
android:layout_margin="4dp"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
ScreenShot Of App
The recycler view is to be displayed below Today's Weather Forecast

How to parse JSON API in android

I am developing an app where I have a Json api and I need to populate it in recyclerview. Its a news api(not from newsapi.org). I am beginner to parsing json. However, I have tried to do but nothing came except an empty screen.
The Json api is
https://earnezy.in/android_shop/newsapi2.php
I have attached the code.
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonObject;
import com.news.newsapp.R;
import com.news.newsapp.adapters.Adapter;
import com.news.newsapp.model.News;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final String JSON_URL = "https://earnezy.in/android_shop/newsapi2.php";
private JsonArrayRequest jsonArrayRequest;
private RequestQueue requestQueue;
private List<News> newsList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.news);
jsonRequest();
}
private void jsonRequest() {
jsonArrayRequest = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i=0;i<response.length();i++){
try {
jsonObject = response.getJSONObject(i);
News news = new News();
news.setAuthor(jsonObject.getString("author"));
news.setDescription(jsonObject.getString("description"));
news.setTitle(jsonObject.getString("title"));
news.setPublishedAt(jsonObject.getString("publishedAt"));
newsList.add(news);
} catch (JSONException e) {
e.printStackTrace();
}
}
setUpRecyclerView(newsList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
private void setUpRecyclerView(List<News> newsList) {
Adapter adapter = new Adapter(MainActivity.this, newsList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="#000"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:text="Top Headlines"
android:textColor="#fff"
android:textSize="22dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/news"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.034" />
</androidx.constraintlayout.widget.ConstraintLayout>
Adapter.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.news.newsapp.R;
import com.news.newsapp.activities.Utils;
import com.news.newsapp.model.News;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder>{
private Context context;
private List<News> news;
public Adapter(Context context, List<News> news) {
this.context = context;
this.news = news;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.news_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
final MyViewHolder holders = holder;
News model = news.get(position);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(Utils.getRandomDrawbleColor());
requestOptions.error(Utils.getRandomDrawbleColor());
requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
requestOptions.centerCrop();
Glide.with(context)
.load(model.getUrlToImage())
.apply(requestOptions)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.progressBar.setVisibility(View.GONE);
return false;
}
})
.transition(DrawableTransitionOptions.withCrossFade())
.into(holder.imageView);
holder.author.setText(news.get(position).getAuthor());
holder.description.setText(news.get(position).getDescription());
holder.title.setText(news.get(position).getTitle());
holder.time.setText("\u2022" + Utils.DateToTimeFormat(model.getPublishedAt()));
holder.publishedAd.setText(Utils.DateFormat(model.getPublishedAt()));
}
#Override
public int getItemCount() {
return news.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView author, title, description, time, publishedAd;
ImageView imageView;
ProgressBar progressBar;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
Utils.java
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import org.ocpsoft.prettytime.PrettyTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
public class Utils {
public static ColorDrawable[] vibrantLightColorList =
{
new ColorDrawable(Color.parseColor("#ffeead")),
new ColorDrawable(Color.parseColor("#93cfb3")),
new ColorDrawable(Color.parseColor("#fd7a7a")),
new ColorDrawable(Color.parseColor("#faca5f")),
new ColorDrawable(Color.parseColor("#1ba798")),
new ColorDrawable(Color.parseColor("#6aa9ae")),
new ColorDrawable(Color.parseColor("#ffbf27")),
new ColorDrawable(Color.parseColor("#d93947"))
};
public static ColorDrawable getRandomDrawbleColor() {
int idx = new Random().nextInt(vibrantLightColorList.length);
return vibrantLightColorList[idx];
}
public static String DateToTimeFormat(String oldstringDate){
PrettyTime p = new PrettyTime(new Locale(getCountry()));
String isTime = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
Locale.ENGLISH);
Date date = sdf.parse(oldstringDate);
isTime = p.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return isTime;
}
public static String DateFormat(String oldstringDate){
String newDate;
SimpleDateFormat dateFormat = new SimpleDateFormat("E, d MMM yyyy", new Locale(getCountry()));
try {
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(oldstringDate);
newDate = dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
newDate = oldstringDate;
}
return newDate;
}
public static String getCountry(){
Locale locale = Locale.getDefault();
String country = String.valueOf(locale.getCountry());
return country.toLowerCase();
}
}
News.java
public class News {
private String author;
private String title;
private String description;
private String url;
private String publishedAt;
private String urlToImage;
public News() {
}
public News(String author, String title, String description, String url, String publishedAt, String urlToImage) {
this.author = author;
this.title = title;
this.description = description;
this.url = url;
this.publishedAt = publishedAt;
this.urlToImage = urlToImage;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
}
news_item.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="11dp"
android:layout_marginRight="11dp"
android:layout_marginTop="7dp"
android:layout_marginBottom="7dp"
app:cardBackgroundColor="#000"
app:cardElevation="#dimen/cardview_default_elevation"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:transitionName="img"
tools:ignore="UnusedAttribute"/>
<ImageView
android:id="#+id/shadow_image"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_alignBottom="#+id/img"
android:src="#drawable/bottom_shadow"/>
<ProgressBar
android:id="#+id/progress_load_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
style="#android:style/Widget.ProgressBar.Small"/>
<TextView
android:id="#+id/author"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawablePadding="10dp"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#fff"
android:singleLine="true"
android:layout_marginRight="160dp"
android:layout_marginLeft="10dp"
android:text="Author"
android:gravity="bottom"
android:layout_alignLeft="#+id/title"
android:layout_alignStart="#+id/title"
android:layout_alignRight="#+id/layoutDate"
android:layout_alignTop="#+id/layoutDate"
android:layout_alignEnd="#+id/layoutDate"/>
<FrameLayout
android:id="#+id/layoutDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/img"
android:background="#fff"
android:padding="5dp"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="-50dp">
<ImageView
android:src="#drawable/ic_date"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/publishedAt"
android:textColor="#606060"
android:layout_marginLeft="27dp"
android:layout_marginRight="10dp"
android:text="01 January 1999"/>
</FrameLayout>
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/img"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:text="Title"
android:textColor="#fff"
android:textSize="17sp" />
<TextView
android:id="#+id/desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="5dp"
android:text="Desc"
android:textColor="#fff" />
<TextView
android:id="#+id/source"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="26dp"
android:text="Source"
android:textColor="#fff" />
<TextView
android:id="#+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="46dp"
android:text="Time"
android:textColor="#fff" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</FrameLayout>
The repsonse from the https://earnezy.in/android_shop/newsapi2.php is a JSON object not array. So use please below code to fetch news items correctly.
private void jsonRequest() {
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,JSON_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray articles = response.optJSONArray("articles")
JSONObject jsonObject = null;
for (int i=0;i<articles.length();i++){
try {
jsonObject = articles.getJSONObject(i);
News news = new News();
news.setAuthor(jsonObject.getString("author"));
news.setDescription(jsonObject.getString("description"));
news.setTitle(jsonObject.getString("title"));
news.setPublishedAt(jsonObject.getString("publishedAt"));
newsList.add(news);
} catch (JSONException e) {
e.printStackTrace();
}
}
setUpRecyclerView(newsList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonObjectRequest);
}

Fragment.java Error: No suitable method in found and cannot resolve method 'inflate(int, boolean)'

Good day everyone, i am currently study on parsing JSON and display with recyclerView and cardview. I could not able to inflate the suitable method for the fragment.java class. Does anyone faced this error before? Thanks
Messages Gradle Build:
D:\New folder\DrawerWithSwipeTabs\app\src\main\java\com\androidbelieve\drawerwithswipetabs\newsAdapter.java
Error:(41, 65) error: no suitable method found for inflate(int,boolean)
method LayoutInflater.inflate(int,ViewGroup) is not applicable
(argument mismatch; boolean cannot be converted to ViewGroup)
method LayoutInflater.inflate(XmlPullParser,ViewGroup) is not applicable
(argument mismatch; int cannot be converted to XmlPullParser)
listnews.java (Data)
package com.androidbelieve.drawerwithswipetabs;
/**
* Created by LENOVO on 21/2/2017.
*/
public class listnews {
public int id;
public String imagedescription, image, imagepath, imagetitle;
public listnews(int id, String imagedescription, String image, String imagepath, String imagetitle) {
this.id = id;
this.imagedescription = imagedescription;
this.image = image;
this.imagepath = imagepath;
this.imagetitle = imagetitle;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImagedescription() {
return imagedescription;
}
public void setImagedescription(String imagedescription) {
this.imagedescription = imagedescription;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public String getImagetitle() {
return imagetitle;
}
public void setImagetitle(String imagetitle) {
this.imagetitle = imagetitle;
}
}
NewsAdapter.java
package com.androidbelieve.drawerwithswipetabs;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
/**
* Created by LENOVO on 20/2/2017.
*/
public class newsAdapter extends RecyclerView.Adapter<newsAdapter.ViewHolder> {
private Context context;
private List<listnews> my_data;
public newsAdapter(Context context, List<listnews> my_data)
{
this.context = context;
this.my_data = my_data;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_news,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.description.setText(my_data.get(position).getImagedescription());
Glide.with(context).load(my_data.get(position).getImagepath()).into(holder.dataimage);
}
#Override
public int getItemCount() {
return 0;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView description;
public TextView imagetitle;
public ImageView dataimage;
public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.textView3);
imagetitle = (TextView) itemView.findViewById(R.id.textView4);
dataimage = (ImageView) itemView.findViewById(R.id.imageView4);
}
}
}
NewsFragment.java
package com.androidbelieve.drawerwithswipetabs;
import android.app.LauncherActivity;
import android.graphics.Movie;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Ratan on 7/29/2015.
*/
public class NewsFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private GridLayoutManager gridLayoutManager;
private newsAdapter nAdapter;
private List<listnews> data_list;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.news_layout,container,false);
mRecyclerView =(RecyclerView)view.findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
data_list = new ArrayList<>();
load_data_from_server(0);
gridLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(gridLayoutManager);
nAdapter = new newsAdapter(this,data_list);
mRecyclerView.setAdapter(nAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(gridLayoutManager.findLastCompletelyVisibleItemPosition() == data_list.size()-1)
{
load_data_from_server(data_list.get(data_list.size()-1).getId());
}
}
});
return view;
private void load_data_from_server(final int id)
{
AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.107.1/ibmcoe_la/selected.php?id="+id)
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for(int i=0; i<array.length(); i++)
{
JSONObject object = array.getJSONObject(i);
listnews data = new listnews(object.getInt("news_id"),object.getString("path_image")
,object.getString("news_title"),object.getString("news_image"),object.getString("news_description"));
data_list.add(data);
}
}catch (IOException e){
e.printStackTrace();
}catch (JSONException e){
System.out.println("End of content");
}
return null;
}
protected void onPostExecute(Void avoid){
nAdapter.notifyDataSetChanged();
}
};
task.execute(id);
}
#Override
public String toString()
{
return "NewsFragment";
}
}
news_layout.xml (fragment layout)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:textSize="30sp"
android:gravity="center"
android:id="#+id/textView"
android:layout_centerHorizontal="true"
android:textColor="#android:color/holo_blue_dark"
android:text="News\nFragment"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:textSize="15sp"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:text="androidbelieve.com"
android:textColor="#000"
android:layout_below="#+id/textView"
android:textStyle="italic"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:id="#+id/recyclerview"
android:clickable="true"
android:focusable="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
recycle_news.xml (cardview layout)
<android.support.v7.widget.CardView
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:android2="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="https://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android2:layout_marginTop="5dp"
android2:layout_marginLeft="5dp"
android2:layout_marginRight="5dp"
android2:layout_gravity="center|top"
card_view:cardPreventCornerOverlap="false"
card_view:cardCornerRadius="20dp"
android2:layout_width="match_parent"
android2:layout_height="wrap_content">
<FrameLayout
android2:layout_width="match_parent"
android2:layout_height="400dp"
app:cardElevation="0dp"
android2:background="#drawable/cardviewstring">
<LinearLayout
android2:orientation="vertical"
android2:layout_width="380dp"
android2:layout_height="match_parent"
android2:weightSum="1"
android2:layout_marginRight="20dp">
<LinearLayout
android2:orientation="vertical"
android2:layout_width="match_parent"
android2:layout_weight="1"
android2:layout_height="250dp">
<ImageView
android2:layout_width="match_parent"
android2:layout_height="match_parent"
app:srcCompat="#mipmap/ic_launcher"
android2:id="#+id/imageView4" />
</LinearLayout>
<LinearLayout
android2:orientation="vertical"
android2:layout_width="match_parent"
android2:layout_height="wrap_content"
android2:paddingTop="25dp">
<ScrollView
android2:layout_width="match_parent"
android2:layout_height="84dp"
android2:background="#drawable/screen_background_dark_transparent"
android2:layout_marginLeft="3dp">
<LinearLayout
android2:layout_width="match_parent"
android2:layout_height="wrap_content"
android2:orientation="vertical" >
<TextView
android2:text="TextView"
android2:layout_width="match_parent"
android2:layout_height="wrap_content"
android2:id="#+id/textView4" />
<TextView
android2:text="TextView"
android2:layout_width="match_parent"
android2:layout_height="35dp"
android2:id="#+id/textView3" />
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android2:orientation="vertical"
android2:layout_marginTop="10dp"
android2:layout_width="match_parent"
android2:layout_height="42dp"
android:layout_alignParentBottom="true">
<LinearLayout
android2:orientation="horizontal"
android2:layout_width="match_parent"
android2:layout_height="match_parent">
<ImageView
android2:layout_width="wrap_content"
android2:layout_height="wrap_content"
app:srcCompat="#drawable/ic_share"
android2:id="#+id/imageView3"
android2:layout_weight="1" />
<ImageView
android2:layout_width="wrap_content"
android2:layout_height="wrap_content"
app:srcCompat="#drawable/ic_like"
android2:id="#+id/imageView2"
android2:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
</android.support.v7.widget.CardView>
selected.php (Photo source)
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "ibmcoe1.4";
$con = mysqli_connect($host,$user,$pass,$db);
$query = "SELECT * FROM news order by news_timepost DESC";
$result = mysqli_query($con,$query);
$response = array();
while ($row = mysqli_fetch_array($result))
{
array_push($response,array('news_id'=>$row[0],'path_image'=>$row[1],'news_title'=>$row[2],'news_description'=>$row[3],'news_timepost'=>$row[5]));
}
mysqli_close($con);
echo json_encode(array('server_response'=>$response));
?>
This will work -
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_news, parent, false);
Second parameter suppose to be a ViewGroup which is parent here.
Reference
Add ViewGroup parent as second parameter
View itemView = LayoutInflater.from(context).inflate(R.layout.recycle_news,parent,false);
instead of
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_news,false);

Categories

Resources