If i complete those edit text with what i want,it will show the info to my fire data base but in the recycler view never show the third holder(holder.textViewZ.setText(model.getWhy). Do you have any idea why is this happening?
This is my main activity
package com.example.incercarefirebase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.graphics.ColorSpace;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.SuccessContinuation;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.net.IDN;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private Button btnSaveRecycler;
private EditText etNAME, etSurrname, etZ;
private FirebaseRecyclerOptions<Model> options;
private DatabaseReference rootDatabaseref;
private FirebaseRecyclerAdapter<Model, MyViewHolder> adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNAME = findViewById(R.id.etNAME);
etSurrname = findViewById(R.id.etSurrname);
etZ = findViewById(R.id.etZ);
btnSaveRecycler = findViewById(R.id.btnSaveRecycler);
recyclerView = findViewById(R.id.recyclerviewID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
rootDatabaseref = FirebaseDatabase.getInstance().getReference().child("Users");
btnSaveRecycler.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int id = Integer.parseInt(etNAME.getText().toString());
String name = etSurrname.getText().toString();
String why = etZ.getText().toString();
String key = rootDatabaseref.push().getKey();
rootDatabaseref.child(key).child("ID").setValue(id);
rootDatabaseref.child(key).child("Name").setValue(name);
rootDatabaseref.child(key).child("Why").setValue(why);
}
});
options = new FirebaseRecyclerOptions.Builder<Model>().setQuery(rootDatabaseref, Model.class).build();
adapter = new FirebaseRecyclerAdapter<Model, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull Model model) {
holder.textviewName.setText(model.getName());
holder.textviewID.setText(model.getID());
holder.textViewZ.setText(model.getWhy());
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_view_layout, parent, false);
return new MyViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
}
This is my viewHolder
package com.example.incercarefirebase;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textviewID, textviewName, textViewZ;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
textviewID = itemView.findViewById(R.id.textViewID);
textviewName = itemView.findViewById(R.id.textViewName);
textViewZ = itemView.findViewById(R.id.textViewZ);
}
}
This is my model
package com.example.incercarefirebase;
public class Model {
private int ID;
private String Name;
private String Why;
public Model() {
}
public Model(int ID, String name, String why) {
this.ID = ID;
Name = name;
Why = why;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getWhy() {
return Why;
}
public void setWhy(String why) {
Why = why;
}
}
This is the single_view_layout
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textViewID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="123"
android:textSize="30dp" />
<TextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name..."
android:textSize="30dp" />
<TextView
android:id="#+id/textViewZ"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="aaaaa"
android:textSize="30dp" />
</LinearLayout>
This is the main 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"
tools:context=".MainActivity">
<EditText
android:id="#+id/etNAME"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="ID"
android:inputType="textPersonName" />
<EditText
android:id="#+id/etSurrname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Name"
android:inputType="textPassword" />
<EditText
android:id="#+id/etZ"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="#+id/btnSaveRecycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewID"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Related
When using a custom adapter in Firebase, I ran into a problem that everything works, but the pictures in the sheet are not displayed. Something incomprehensible is highlighted, but not her. It is necessary that they be in a normal sheet and they can be seen. I think it's because of the context in Picasso. The guide I followed had a wish(mContext) method that I can't use now. Please help, I don't understand what is the problem. I am attaching the image_item.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="20sp" />
<ImageView
android:id="#+id/image_view_upload"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
activity_images
<?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=".ImagesActivity">
<ProgressBar
android:id="#+id/progress_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
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.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
}
}
}
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ImagesActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
mUploads.add(upload);
}
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
}
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
i'm just setup my RecyclerView but there's not appear in my emulator & there is error "E/RecyclerView: No adapter attached; skipping layout" Could you guys help me to find my failure?
This is my application layout :
Click here to see my application layout view
StockContent.Java (Fragment) :
package com.example.psmandroidapps;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.Toolbar;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class StockContent extends Fragment {
RecyclerView StockRecyclerView;
List<ModalClass> mList;
CustomAdapter customAdapter;
public StockContent() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View stockview = inflater.inflate(R.layout.stock_content, container, false);
StockRecyclerView = stockview.findViewById(R.id.StockRecyclerView);
customAdapter = new CustomAdapter(mList,getContext());
StockRecyclerView.setAdapter(customAdapter);
StockRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return stockview;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//just for sample only
mList = new ArrayList<>();
mList.add(new ModalClass(R.drawable.profilepicture,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logodetail,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logo,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.profilepicture,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logodetail,"Mitsubishi S-N50"));
mList.add(new ModalClass(R.drawable.logo,"Mitsubishi S-N50"));
}
}
StockContent.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3FFFC">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/StockRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
Stock_CardView.XML (for recyclerview content) :
<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="15dp"
android:layout_margin="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
android:layout_width="100dp"
android:layout_height="100dp"
app:cardCornerRadius="30dp"
android:layout_margin="15dp"
android:layout_weight="0.1">
<ImageView
android:id="#+id/img_goodspicture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/profilepicture"
android:scaleType="centerCrop"/>
</androidx.cardview.widget.CardView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:layout_marginTop="10dp"
android:layout_marginRight="15dp"
>
<TextView
android:id="#+id/txt_goodsname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mitsubishi S-N10 (220V)"
android:textColor="#000000"
android:fontFamily="#font/sarabun_bold"
android:textSize="21dp"
android:layout_marginBottom="0dp"/>
<TextView
android:id="#+id/txt_goodstype"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Jenis : Contactor"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp" />
<TextView
android:id="#+id/txt_goodsstock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stok : 105 pcs"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp"/>
<TextView
android:id="#+id/txt_dateofgoodsentry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tanggal masuk : 29/07/2020"
android:textColor="#000000"
android:fontFamily="#font/sarabun_regular"
android:textSize="12.5dp"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
ModalClass.Java :
package com.example.psmandroidapps;
public class ModalClass {
int image;
String text;
public ModalClass(int image, String text) {
this.image = image;
this.text = text;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
CustomAdapter.Java :
package com.example.psmandroidapps;
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 java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
List<ModalClass> mList;
Context context;
public CustomAdapter(List<ModalClass> mList, Context context) {
this.mList = mList;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.stock_cardview,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.imageView.setImageResource(mList.get(position).getImage());
holder.textView.setText(mList.get(position).getText());
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView textView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.img_goodspicture);
textView=itemView.findViewById(R.id.txt_goodsname);
}
}
}
Thats the code of mine.. the result is nothing, nothing showing in my emulator.. Thank you for read this question, hope you guys can help me to solve my problem here. Thank you guys! have a nice day
I have an app with a bottom navigation view that changes between 4 fragments and I'm trying to make it so that those fragments are displayed with data from firebase using FirebaseRecyclerView Adapter.
I have everything set up but the layout that the FirebaseRecyclerView Adapter inflates is not appearing.
My MainAcitivity.java
package com.pap.diogo.pilltrack;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class MainActivity extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new HomeFragment();
break;
case R.id.navigation_pills:
selectedFragment = new PillsFragment();
break;
case R.id.navigation_appointment:
selectedFragment = new AppointsFragment();
break;
case R.id.navigation_account:
selectedFragment = new AccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
Intent VerifyLogin = new Intent(MainActivity.this, Launcher.class);
VerifyLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(VerifyLogin);
}
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
};
My AccountFragment.java
package com.pap.diogo.pilltrack;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class AccountFragment extends Fragment {
private RecyclerView AccountUsers;
private View mMainView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_account, container, false);
AccountUsers = mMainView.findViewById(R.id.accountlist);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
AccountUsers.setLayoutManager(linearLayoutManager);
AccountUsers.setHasFixedSize(true);
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String userid = user.getUid();
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
FirebaseRecyclerOptions<Account> AccountQ = new FirebaseRecyclerOptions.Builder<Account>().setQuery(ref, Account.class).setLifecycleOwner(this).build();
FirebaseRecyclerAdapter<Account, AccountInfo> AccountAdapter = new FirebaseRecyclerAdapter<Account, AccountInfo>(AccountQ){
#NonNull
#Override
public AccountInfo onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new AccountInfo(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.account, viewGroup, false));
}
#Override
protected void onBindViewHolder(#NonNull final AccountInfo holder, int position, #NonNull final Account model) {
ref.child(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final String name = dataSnapshot.child("name").getValue().toString();
final String age = dataSnapshot.child("idade").getValue().toString();
holder.setName(name);
holder.setAge(age);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
};
AccountUsers.setAdapter(AccountAdapter);
}
public static class AccountInfo extends RecyclerView.ViewHolder{
View AccountL;
public AccountInfo(#NonNull View itemView) {
super(itemView);
AccountL = itemView;
}
public void setName(String name){
TextView AccountName = AccountL.findViewById(R.id.AccountName0);
AccountName.setText(name);
}
public void setAge(String age){
TextView AccountAge = AccountL.findViewById(R.id.AccountAge0);
AccountAge.setText(age);
}
}
}
My account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/AccountUser"
android:layout_width="match_parent"
android:layout_height="163dp"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="15dp"
android:background="#drawable/edit_bg"
android:padding="15dp">
<RelativeLayout
android:id="#+id/AccountImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/AccountInfos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/AccountImage"
android:layout_toEndOf="#id/AccountImage"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp">
<TextView
android:id="#+id/AccountName0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Nome1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/AccountAge0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountName0"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Idade1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="#+id/AccountChangePass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountAge0"
android:text="Mudar Palavra-Passe"
android:textColor="#color/colorWhite"
android:textSize="18sp"
android:textStyle="bold"
android:textAllCaps="false"
android:padding="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/custom_button"/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountUser">
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:src="#drawable/ic_add"
android:padding="5dp"
android:background="#drawable/add_button"/>
</RelativeLayout>
</RelativeLayout>
My fragment_account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/accountlist">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
GitHub of my APP
I fixed it.
All I had to do was to remove this line of code:
AccountUsers.setHasFixedSize(true);
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);