How to parse JSON API in android - java

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);
}

Related

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

recyclerview not show multiple data from Json

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>

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);

Android ListView TextView

I've been struggling to get a listview to display correctly.
To clarify, I need a scrollview above the listview which is why I haven't extended a listfragment.
I need title and description to be separate elements. I can see how I have put them into a class so I think I'm half way there. If someone could help me out that would be great.
PhotosFragment.java
package info.androidhive.slidingmenu;
import android.app.Fragment;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PhotosFragment extends Fragment {
ListView list;
TextView pm;
TextView sp;
ArrayList<HashMap<String, String>> mlist = new ArrayList<HashMap<String,String>>();
private static final String TAG_APPLE = "Apple";
private static final String TAG_PHONEMODEL = "PhoneModel";
private static final String TAG_SPECS = "specs";
JSONArray model = null;
public PhotosFragment(){}
ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_photos, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mListView = (ListView) getView().findViewById(R.id.mListView);
new RequestTask().execute("http://www.horwichadvertiser.co.uk/app/index.php?Type=8&catid=7&userid=4");
}
private static final String TAG = MainActivity.class.getSimpleName();
JSONObject obj;
JSONArray stories;
public class RequestTask extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pm = (TextView)getView().findViewById(R.id.phonemodel);
sp = (TextView)getView().findViewById(R.id.specification);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
//Log.d(TAG, responseString);
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
// Log.d(TAG, String.valueOf(e));
} catch (IOException e) {
//TODO Handle problems..
// Log.d(TAG, String.valueOf(e));
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
//Log.e(TAG, result);
try {
obj = new JSONObject(result);
stories = obj.getJSONArray("stories");
// initialize the items list
List<ListViewItem> mItems = new ArrayList<ListViewItem>();
for (int i = 0; i < stories.length(); i++) {
JSONObject storyObj = stories.getJSONObject(i);
if (!storyObj.has("Advert")) {
newsStories newsStories = new newsStories();
newsStories.setTitle(storyObj.getString("subject"));
newsStories.setBody(storyObj.getString("body"));
mItems.add(new ListViewItem(newsStories.getTitle(), newsStories.getBody(), ""));
}
else {
newsStories newsStories = new newsStories();
newsStories.setThumbnailUrl(storyObj.getString("Advert"));
mItems.add(new ListViewItem("", "", newsStories.getThumbnailUrl()));
}
}
ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.simple_list_item_1, mItems);
mListView.setTextFilterEnabled(true);
// ArrayAdapter<ListViewItem> adapter = new ArrayAdapter<ListViewItem>(getActivity(), android.R.layout.two_line_list_item, mItems);
//mListView.setAdapter(adapter);
mListView.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
public class newsStories {
private String name, thumbnailUrl, body;
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body.substring(0, 150);
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
//Check if thumbnail exists, if so take out spaces and replace with -
this.thumbnailUrl = thumbnailUrl;
}
}
}
public class ListViewItem{
public final String title; // the text for the ListView item title
public final String description; // the text for the ListView item description
public final String adUrl;
//public final Drawable image;
public ListViewItem(String title, String description, String Advert_Url) {
if (Advert_Url != null && !Advert_Url.isEmpty()) {
String Advert = "http://www.horwichadvertiser.co.uk/images/horwichadvertiserlogo.png?width=700&height=200";
this.title = "";
this.description = "";
this.adUrl = Advert;
} else {
this.title = title;
this.description = description;
this.adUrl = "";
}
}
#Override
public String toString() {
return this.title + ".\r\n" + Html.fromHtml(this.description);
}
}
}
Fragment_Photos.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="150dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button4" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button5" />
</LinearLayout>
</HorizontalScrollView>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:id="#+id/relativeLayout">
<TextView
android:id="#+id/body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="22px" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="13px" />
</RelativeLayout>
<ListView
android:id="#id/mListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="#+id/relativeLayout">
</ListView>
</RelativeLayout>
Your resource xml is incorrect.
1.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
android:orientation is used with LinearLayout, not RelativeLayout
2.
<ListView
android:id="#id/mListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_below="#+id/relativeLayout">
</ListView>
Incorrect use of android:layout_below - value should be an existing id: "#id/relativeLayout" (without + after #).
android:id="#id/mListView" incorrectly assigned id. If it is a new ID, then should be android:id="#+id/mListView"
Probably you'd like to use LinearLayouts instead of relative
fill_parent is obsolete until you develop for some API 7. Should be match_parent instead

Categories

Resources