I'm trying to pass list of custom object from onDataLoaded function (which is in MainActivity) to fragment, using Parcelable. But I get this error...
This is a MainActivity funkcion, onDataLoaded
#Override
public void onDataLoaded(List<Grad> gradovi, List<Ponuda> ponude) {
Spinner spinnerGradovi = (Spinner) findViewById(R.id.gradovi_spinner);
ArrayAdapter<String> adapterGradovi;
List<String> listaGradova = new ArrayList<>();
ArrayList<Ponuda> ponudaArrayList = new ArrayList<Ponuda>();
ponudaLista = ponude;
gradLista = gradovi;
for(Grad grad : gradovi ){
listaGradova.add(grad.getNaziv());
}
for(Ponuda ponuda : ponude){
ponudaArrayList.add(ponuda);
}
//here I want to get arguments which contains ArrayList
Fragment fragmentGet = svePonudeFragment;
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Ponuda", ponudaArrayList);
fragmentGet.setArguments(bundle);
adapterGradovi = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listaGradova);
spinnerGradovi.setAdapter(adapterGradovi);
}
And this is Fragment:
public class SvePonudeFragment extends Fragment {
private RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sve_ponude_fragment, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
Bundle data = getActivity().getIntent().getExtras();
ArrayList<Ponuda> listaPonuda= data.getParcelable("ponude");
for(Ponuda ponuda : listaPonuda){
System.out.println(ponuda.getNaziv());
}
initializeAdapter(listaPonuda);
return rootView;
}
private void initializeAdapter(List<Ponuda> preuzetePonude){
RVAdapter adapter = new RVAdapter(preuzetePonude);
rv.setAdapter(adapter);
}
}
This is object class
#Table(database = MainDatabase.class)
public class Ponuda extends BaseModel implements Parcelable{
#Column
#PrimaryKey int id;
#Column String tekstPonude;
#Column int cijena;
#Column int popust;
#Column int cijenaOriginal;
#Column String urlSlike;
#Column int usteda;
#Column String kategorija;
#Column String grad;
#Column String datumPonude;
public Ponuda() {
}
public Ponuda(int id,String tekstPonude, int cijena, int popust, int cijenaOriginal, String urlSlike, int usteda, String kategorija, String grad, String datumPonude){
this.id=id;
this.tekstPonude = tekstPonude;
this.cijena = cijena;
this.popust = popust;
this.cijenaOriginal = cijenaOriginal;
this.urlSlike = urlSlike;
this.usteda = usteda;
this.kategorija = kategorija;
this.grad = grad;
this.datumPonude = datumPonude;
}
public String getNaziv() {
return tekstPonude;
}
public String getCijena() {
return Integer.toString(cijena);
}
public String getURL() {
return urlSlike;
}
public void setCijena(int cijena) {
this.cijena = cijena;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTekstPonude() {
return tekstPonude;
}
public void setTekstPonude(String tekstPonude) {
this.tekstPonude = tekstPonude;
}
public int getPopust() {
return popust;
}
public void setPopust(int popust) {
this.popust = popust;
}
public int getCijenaOriginal() {
return cijenaOriginal;
}
public void setCijenaOriginal(int cijenaOriginal) {
this.cijenaOriginal = cijenaOriginal;
}
public String getUrlSlike() {
return urlSlike;
}
public void setUrlSlike(String urlSlike) {
this.urlSlike = urlSlike;
}
public int getUsteda() {
return usteda;
}
public void setUsteda(int usteda) {
this.usteda = usteda;
}
public String getKategorija() {
return kategorija;
}
public void setKategorija(String kategorija) {
this.kategorija = kategorija;
}
public String getGrad() {
return grad;
}
public void setGrad(String grad) {
this.grad = grad;
}
public String getDatumPonude() {
return datumPonude;
}
public void setDatumPonude(String datumPonude) {
this.datumPonude = datumPonude;
}
public static List<Ponuda> getAll(){
List<Ponuda> ponudaList;
ponudaList= new Select().from(Ponuda.class).queryList();
return ponudaList;
}
public Ponuda(Parcel in){
String[] data = new String[9];
in.readStringArray(data);
this.id = in.readInt();
this.tekstPonude = in.readString();
this.cijena = in.readInt();
this.popust = in.readInt();
this.cijenaOriginal = in.readInt();
this.urlSlike = in.readString();
this.usteda = in.readInt();
this.kategorija = in.readString();
this.grad = in.readString();
this.datumPonude = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(tekstPonude);
dest.writeInt(cijena);
dest.writeInt(popust);
dest.writeInt(cijenaOriginal);
dest.writeString(urlSlike);
dest.writeInt(usteda);
dest.writeString(kategorija);
dest.writeString(grad);
dest.writeString(datumPonude);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Ponuda createFromParcel(Parcel in) {
return new Ponuda(in);
}
public Ponuda[] newArray(int size) {
return new Ponuda[size];
}
};
}
I don't understand why I get null pointer exception
Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
Yes, you got this error. Why? because you have 2 errors:
Bundle data = getActivity().getIntent().getExtras();
-> you are trying to get bundle of your Activity, not your fragment. You should try to use getArguments() instead.
You will get another error because when your fragment's onCreateView() is called, there's no argument bundle in your fragment (your bundle is set in onDataLoaded from your activity). As my opinion you should make a reload data in your fragment like:
public void reloadData(){
//getArguments, parse and show in the list
}
//then in your onDataLoaded of MainActivity:
//here I want to get arguments which contains ArrayList
((YourFragment)fragmentGet).reloadData(); //call after set argument
You can achive this in this other way.
Getting the data from activity.
Add updateListInFragment() in your main java.
MainActivity.java
public ArrayList<Ponuda> updateListInFragment(){
return ponudaArrayList;
}
SvePonudeFragment.java
private ArrayList<Ponuda> mMyList;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sve_ponude_fragment, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
Bundle data = getActivity().getIntent().getExtras();
updateArrayList(); //Let's update here
for(Ponuda ponuda : mMyList){
System.out.println(ponuda.getNaziv());
}
initializeAdapter(listaPonuda);
return rootView;
}
// Update your mMyList from activity
public void updateArrayList(){
MainActivity activity = (MainActivity) activity;
mMyList = activity.updateListInFragment();
}
Related
I'm referring this tutorial ==> https://uniqueandrocode.com/add-to-favourites-and-display-favourites-in-recyclerview/ in my project I have bottom navigation...I am trying to add favourites in the first tab and displaying favourites in the second tab in the bottom navigation bar. I'm using Room library.
When activity loads favourites are all blank at first, but when I first row as favourite and go-to favourite tab it displays properly but when I came back to the first tab it fills all the favourites icon automatically (which I have not done I had only done the first row)
Really need help. Thanks in advance.
Dao:
#Dao
public interface FavoriteDao {
#Insert
public void addData(FavoriteList favoriteList);
#Query("select * from favoritelist")
public List<FavoriteList> getFavoriteData();
#Query("SELECT EXISTS (SELECT 1 FROM favoritelist WHERE id=:id)")
public int isFavorite(int id);
#Delete
public void delete(FavoriteList favoriteList);
}
Database:
#Database(entities={FavoriteList.class},version = 1)
public abstract class FavoriteDatabase extends RoomDatabase {
public abstract FavoriteDao favoriteDao();
}
FavoriteList:
#Entity(tableName="favoritelist")
public class FavoriteList {
#PrimaryKey
private int id;
#ColumnInfo(name = "source")
private String source;
#ColumnInfo(name = "author")
private String author;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "description")
private String description;
#ColumnInfo(name = "url")
private String url;
#ColumnInfo(name = "urlToImage")
private String urlToImage;
#ColumnInfo(name = "publishedAt")
private String publishedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
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 getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
}
News fragment:
public class news extends Fragment {
ImageView favbtn;
RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
EditText etQuery;
Button btnSearch;
Adapter adapter;
List<Articles> articles = new ArrayList<>();
public static FavoriteDatabase favoriteDatabase;
public news() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news, container, false);
swipeRefreshLayout = view.findViewById(R.id.swiprefresh);
etQuery = view.findViewById(R.id.etQuery);
btnSearch = view.findViewById(R.id.btnSearch);
favoriteDatabase= Room.databaseBuilder(getActivity(),FavoriteDatabase.class,"myfavdb").
allowMainThreadQueries().build();
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final String country = getCountry();
retrieveJson("", country, API_Key);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etQuery.getText().toString().equals("")) {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson(etQuery.getText().toString(), country, API_Key);
}
});
retrieveJson(etQuery.getText().toString(), country, API_Key);
} else {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
retrieveJson("", country, API_Key);
}
});
retrieveJson("", country, API_Key);
}
}
});
return view;
}
private void showChangeLanguageDialog() {
}
public void retrieveJson(String query, String country, String apiKey) {
swipeRefreshLayout.setRefreshing(true);
Call<Headlines> call;
if (!etQuery.getText().toString().equals("")) {
call = ApiClient.getInstance().getApi().getSpecifiedData(query, apiKey);
} else {
call = ApiClient.getInstance().getApi().getHeadLines(country, apiKey);
}
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if (response.isSuccessful() && response.body().getArticles() != null) {
swipeRefreshLayout.setRefreshing(false);
// articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(getContext(), articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getContext(), t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry() {
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final Adapter.ViewHolder holder, final int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
String url = a.getUrl();
holder.tvTitle.setText(a.getTitle());
Picasso.get().load(imageUrl).into(holder.imageView);
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(dateTime(a.getPublishedAt()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,DetailedActivity.class);
intent.putExtra("title",a.getTitle());
intent.putExtra("source",a.getSource().getName());
intent.putExtra("time",dateTime(a.getPublishedAt()));
intent.putExtra("desc",a.getDescription());
intent.putExtra("imageUrl",a.getUrlToImage());
intent.putExtra("url",a.getUrl());
context.startActivity(intent);
}
});
if (news.favoriteDatabase.favoriteDao().isFavorite(articles.get(position).getId())==1)
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
else
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FavoriteList favoriteList = new FavoriteList();
int id = articles.get(position).getId();
String source = articles.get(position).getSource().getName();
String author = articles.get(position).getAuthor();
String publishedAt = articles.get(position).getPublishedAt();
String description = articles.get(position).getDescription();
String title = articles.get(position).getTitle();
String url = articles.get(position).getUrl();
String urlToImage = articles.get(position).getUrlToImage();
favoriteList.setId(id);
favoriteList.setAuthor(author);
favoriteList.setDescription(description);
favoriteList.setSource(source);
favoriteList.setPublishedAt(publishedAt);
favoriteList.setTitle(title);
favoriteList.setUrl(url);
favoriteList.setUrlToImage(urlToImage);
favoriteList.setPublishedAt(dateTime(articles.get(position).getPublishedAt()));
if (news.favoriteDatabase.favoriteDao().isFavorite(id)!=1){
holder.bookmark.setImageResource(R.drawable.ic_bookmark);
news.favoriteDatabase.favoriteDao().addData(favoriteList);
}else {
holder.bookmark.setImageResource(R.drawable.ic_baseline_bookmark_border_24);
news.favoriteDatabase.favoriteDao().delete(favoriteList);
}
}
});
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle, tvSource, tvDate;
ImageView imageView;
ImageButton bookmark;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvId);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
bookmark = itemView.findViewById(R.id.favrr);
}
}
Steps to debug:
Add 2-3 items as Favs.
Restart the Application.
Check if it shows those items as fav after restarting application .
also add logs to those if conditions where you are changing the drawables.
After looking at your JSON it looks like id is what creating problems. Id is null for all your json items so when fav. one it shows fav. to all.
Solution : Use another field to check if the data is added to fav.list
Delete will not work either
Try
#Query("DELETE FROM favoritelist WHERE title = :title")
void deleteByUserId(String title);
To delete item
Also https://github.com/amitshekhariitbhu/Android-Debug-Database
check this library to debug your database
I have an array list of custom Song objects and I want to send the song name, artist name and the album cover image to another activity (Song Activity) when a particular song item of the listview is clicked. I have created a SongActivity for showing the now playing screen for the song that the user has selected.
(SONGS LIST ACTIVITY) This contains the songs list.
public class SongsListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs_list);
ArrayList<Song> songs = new ArrayList<Song>();
songs.add(new Song("Earthquake","Marshmello and TYNAN",R.mipmap.earthquake));
.....
final SongAdapter adapter = new SongAdapter(this, songs);
ListView listView = findViewById(R.id.list);
listView.setAdapter(adapter);
ListView listview = (ListView) findViewById(R.id.list);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(view.getContext(), SongActivity.class);
}
});
}
}
(SONG ACTIVITY) This activity starts when a particular song object is clicked by the user
import androidx.appcompat.app.AppCompatActivity;
public class SongActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song_activity);
ImageView songImage = findViewById(R.id.songImage);
TextView songName = findViewById(R.id.songName);
TextView artistName = findViewById(R.id.artistName);
Intent intent = getIntent();
songImage.setImageResource(intent.getIntExtra("image",0));
songName.setText(intent.getStringExtra("songName"));
artistName.setText(intent.getStringExtra("artistName"));
}
}
(SONG ADAPTER)
public class SongAdapter extends ArrayAdapter {
public SongAdapter(Activity context, ArrayList<Song> songs) {
super(context, 0, songs);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Song currentSong = (Song) getItem(position);
TextView nameTextView = (TextView) listItemView.findViewById(R.id.song_name);
nameTextView.setText(currentSong.getSongName());
TextView artistTextView = (TextView) listItemView.findViewById(R.id.artist_name);
artistTextView.setText(currentSong.getArtistName());
ImageView iconView = (ImageView) listItemView.findViewById(R.id.song_icon);
iconView.setImageResource(currentSong.getImageResourceId());
return listItemView;
}
}
Paracelize your modal like this
public class Student implements Parcelable {
private Integer rollno;
private String name;
private Integer age;
protected Student(Parcel in) {
age = in.readInt();
name = in.readString();
rollno = in.readInt();
}
public Student(Integer age, String name, Integer rollno) {
this.age = age;
this.name = name;
this.rollno = rollno;
}
public static final Creator<Student> CREATOR = new Creator<Student>() {
#Override
public Student createFromParcel(Parcel in) {
return new Student(in);
}
#Override
public Student[] newArray(int size) {
return new Student[size];
}
};
#Override
public int describeContents() {
return 0;
}
public Integer getRollno() {
return rollno;
}
public void setRollno(Integer rollno) {
this.rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static Creator<Student> getCREATOR() {
return CREATOR;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(age);
parcel.writeString(name);
parcel.writeInt(rollno);
}
}
And then set and get using intent
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, studentList)
intents.getParcelableArrayList<Student>(Intent.EXTRA_STREAM)
Your Song Model(Class) Should look like this
import android.os.Parcel;
import android.os.Parcelable;
public final class Songs implements Parcelable {
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
#Override
public Songs createFromParcel(final Parcel source) {
return new Songs(source);
}
#Override
public Songs[] newArray(final int size) {
return new Songs[size];
}
};
private String songName;
private String artistName;
private Integer imageId;
public Songs() {
}
public Songs(final String songName, final String artistName, final Integer imageId) {
this.songName = songName;
this.artistName = artistName;
this.imageId = imageId;
}
protected Songs(final Parcel in) {
this.songName = in.readString();
this.artistName = in.readString();
this.imageId = (Integer) in.readValue(Integer.class.getClassLoader());
}
public String getSongName() {
return songName;
}
public void setSongName(final String songName) {
this.songName = songName;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(final String artistName) {
this.artistName = artistName;
}
public Integer getImageId() {
return imageId;
}
public void setImageId(final Integer imageId) {
this.imageId = imageId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeString(this.songName);
dest.writeString(this.artistName);
dest.writeValue(this.imageId);
}
}
In your SongListActivity
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
Intent intent = new Intent(view.getContext(), SongActivity.class);
intent.putExtra("SONG_DATA", songList.get(position));
startActivity(intent);
}
});
And at last in onCreate() of your SongActivity you have to get the intent and get the data like
if (getIntent() != null) {
Song song = getIntent().getParcelableExtra("SONG_DATA");
// now you have got song object, You can do rest of operations
}
This question already has answers here:
Using context in a fragment
(31 answers)
Closed 3 years ago.
i try to make custom listview, then I get errors, and i don't know why.
there was an error at this, R.layout.list_events_item,listEvents
and the error message is:
EventsFragment.java
public class EventsFragment extends Fragment {
private View paramView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
paramView = inflater.inflate(R.layout.fragment_events,container,false);
ListView listView = (ListView) paramView.findViewById(R.id.listViewEvents);
List<Events> listEvents = new ArrayList<Events>();
Events events = new Events(1,"12:00","A1221",
"Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
listEvents.add(events);
events = new Events(2,"11:20","A1221",
"Error at the same place","1.2.3.4","1.2.4.3","A212","123",443,1234);
listEvents.add(events);
listView.setAdapter(new EventsAdapter(this, R.layout.list_events_item,listEvents));
return paramView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
}
EventsAdapter.java
public class EventsAdapter extends ArrayAdapter<Events> {
List<Events> listEvents;
Context context;
int layout;
public EventsAdapter(Context context, int layout, List<Events> listEvents){
super(context,layout,listEvents);
this.context=context;
this.layout=layout;
this.listEvents=listEvents;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
EventsHolder holder;
if (v == null){
LayoutInflater vi=((Activity)context).getLayoutInflater();
holder = new EventsHolder();
holder.time=(TextView) v.findViewById(R.id.time);
holder.signature = (TextView) v.findViewById(R.id.signatureId);
holder.sensor = (TextView) v.findViewById(R.id.sensor);
holder.attacker = (TextView) v.findViewById(R.id.attacker);
holder.attacked = (TextView) v.findViewById(R.id.attacked);
v.setTag(holder);
}else {
holder=(EventsHolder) v.getTag();
}
Events events = listEvents.get(position);
holder.time.setText(events.getTime());
holder.signature.setText(events.getSignature_id());
holder.sensor.setText(events.getSensor());
holder.attacker.setText(events.getAttacker_port());
holder.attacked.setText(events.getAttacked_port());
return v;
}
static class EventsHolder{
TextView time;
TextView signature;
TextView sensor;
TextView attacker;
TextView attacked;
}
}
my Events model
public class Events {
int id;
String time;
String signature_id;
String alert_message;
String ip_source;
String ip_destination;
String sensor;
String protocol;
int attacker_port;
int attacked_port;
public Events(int id, String time, String signature_id, String alert_message, String ip_source, String ip_destination, String sensor, String protocol, int attacker_port, int attacked_port) {
this.id = id;
this.time = time;
this.signature_id = signature_id;
this.alert_message = alert_message;
this.ip_source = ip_source;
this.ip_destination = ip_destination;
this.sensor = sensor;
this.protocol = protocol;
this.attacker_port = attacker_port;
this.attacked_port = attacked_port;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getSignature_id() {
return signature_id;
}
public void setSignature_id(String signature_id) {
this.signature_id = signature_id;
}
public String getAlert_message() {
return alert_message;
}
public void setAlert_message(String alert_message) {
this.alert_message = alert_message;
}
public String getIp_source() {
return ip_source;
}
public void setIp_source(String ip_source) {
this.ip_source = ip_source;
}
public String getIp_destination() {
return ip_destination;
}
public void setIp_destination(String ip_destination) {
this.ip_destination = ip_destination;
}
public String getSensor() {
return sensor;
}
public void setSensor(String sensor) {
this.sensor = sensor;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public int getAttacker_port() {
return attacker_port;
}
public void setAttacker_port(int attacker_port) {
this.attacker_port = attacker_port;
}
public int getAttacked_port() {
return attacked_port;
}
public void setAttacked_port(int attacked_port) {
this.attacked_port = attacked_port;
}
}
Try changing this to getActivity()
I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}
I have listview that have to fill from JSON file but until now after running app I see nothing and I don't know if the problem from java codes or JSON file??
also I notice that I can't add file extensions inside #Path ,,
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
final Retrofit retrofit = new Retrofit.Builder().baseUrl("http://10.0.2.2").addConverterFactory(GsonConverterFactory.create()).build();
TelService service = retrofit.create(TelService.class);
final retrofit.Call<List<tel_list>> calls = service.getphones("telephones");
calls.enqueue(new Callback<List<tel_list>>() {
#Override
public void onResponse(Response<List<tel_list>> response, Retrofit retrofit) {
if (!response.isSuccess()) {
//TODO
return;
}
List<tel_list> telephones = response.body();
TelAdapter adapter = new TelAdapter (MainActivity.this, telephones);
listView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
TelService.java
public interface TelService {
#GET("/alruthea/{getphones_1}.php")
retrofit.Call<List<tel_list>> getphones(#Path("getphones_1")String telephones);
}
TelAdapter.java
public class TelAdapter extends ArrayAdapter<tel_list> {
private Context context;
private List<tel_list> telephones;
public TelAdapter(Context context, List<tel_list> data) {
super(context, R.layout.list_item, data);
telephones = data;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View item = inflater.inflate(R.layout.list_item, null);
TextView name = (TextView) item.findViewById(R.id.names);
name.setText(telephones.get(position).getName());
TextView number = (TextView) item.findViewById(R.id.numbers);
number.setText(telephones.get(position).getNumber());
return item;
}
}
tel_list.java
public class tel_list {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}