SQLite With List - java

I have an activity that contains a List. This list will take the data from SQLite:
public class RecentCases extends Activity {
Button GoToCaseInfo, CreateNewFormB;
RecentCaseClass recent1;
// the adapter class..
class RecentCasesInfoAdapter extends ArrayAdapter<RecentCaseClass>
{
public RecentCasesInfoAdapter() {
super(RecentCases.this, R.layout.recent_cases_row);
}
public View getView(final int position, View convertView,
ViewGroup parent)
{
recent1 = this.getItem(position);
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.recent_cases_row, parent,
false);
// this is our row items..
TextView recentName = (TextView) row
.findViewById(R.id.tvrecentName);
TextView recenInfo = (TextView) row.findViewById(R.id.recent_info);
ImageView recentImg = (ImageView) row.findViewById(R.id.list_image);
// TODO What's the info they want
// String CaseTime = recent1.getTime();
// recentName.setText(recent1.getName());
// recenInfo.setText("His/her age: " + recent1.getAge() +
// " year old"
// + " Lost sicnce :" + CaseTime);
String CasePicPath;
// TODO Linear or ??
RelativeLayout rowLayout = (RelativeLayout) row.findViewById(R.id.row_layout);
rowLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// go to
Intent k = new Intent(RecentCases.this, Case_Information.class);
startActivity(k);
}
});
return row;
}
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_cases);
// Moving to Create New Form Activity
CreateNewFormB = (Button) findViewById(R.id.cretnwfrmRC);
CreateNewFormB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent k = new Intent(RecentCases.this, CreateNewForm.class);
startActivity(k);
}
});
// For list
// Intilaize
ListView RecentCasesListView = (ListView) findViewById(R.id.recent_cases_list);
// create adapter
RecentCasesInfoAdapter recentCasesInfoAdapter = new RecentCasesInfoAdapter();
// 1-First receives MMS OnReceive Class 2- Assign the MMS info to Static
// Array 3- Assign the array to the adapater
// for(MedicineClass m: Model.getMedList()) MedicineInfoAdapter.add(new
// MedicineClass(m));
recentCasesInfoAdapter.add(recent1);
// after fill the adapter.. assign the list to the adapter
RecentCasesListView.setAdapter(recentCasesInfoAdapter);
}
}
and this is the class
public class RecentCaseClass {
private String pic;
private String name;
private String gender;
private int age;
private String clothes;
private String MoreInfo;
private String time;
private String location;
private int ID;
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClothes() {
return clothes;
}
public void setClothes(String clothes) {
this.clothes = clothes;
}
public String getMoreInfo() {
return MoreInfo;
}
public void setMoreInfo(String moreInfo) {
MoreInfo = moreInfo;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
}
The SMS will come to my app then i will save in SQLite then i should show it in my app
How can i take data from SQLite and show it in list?
If I delete the row information from SQLite how can i delete the row in list?
Should i change the adapter?
============================UPDATE===========================
I add this to my project but I did not change any thing just added this class:
public class RecentClassAdapter extends BaseAdapter{
private RecentCases RecentCases;
static public List<RecentCaseClass> listOfRCases;
RecentCaseClass entry;
int caseId;
public RecentClassAdapter(RecentCases recentcases, List<RecentCaseClass> listOfCaseParameter) {
this.RecentCases = recentcases;
this.listOfRCases = listOfCaseParameter;
}
public int getCount() {
return listOfRCases.size();
}
public Object getItem(int position) {
return listOfRCases.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
entry = listOfRCases.get(position);
caseId = entry.getID();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) RecentCases.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.recent_cases_row, null);
}
// this is row items..
// Set the onClick Listener on this button
//ConfExpandRegion = (Button) convertView.findViewById(R.id.expand);
//Button Cancelb = (Button) convertView.findViewById(R.id.cancelCase);
TextView RCase = (TextView) convertView.findViewById(R.id.tvrecentName);
RCase.setText(entry.getName());
Toast.makeText(RecentCases, "inside getview" + entry.getAge(), 0).show();
public void add(RecentCaseClass RCaseClass) {
// TODO Auto-generated method stub
listOfRCases.add(RCaseClass);
}
}
}

You have to create a custom array adapter and fetch the data from Database row by row and populate in your Listview with getView method.
Here is a example for custom array adapter
http://android-er.blogspot.in/2010/06/custom-arrayadapter-with-with-different.html
http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter

Related

Using button to delete selected item in Listview w/ ArrayAdapter

I've been working with Java for a few months but new to Android. This is a recipe holder app.
I have an ArrayAdapter set on a ListView and am needing to select an item in the ListView and delete it with a Button (I've already successfully set up adding of Strings to the Listview). I'm using an ArrayList for the list used to store Ingredient objects rather than a regular array. I'm attempting to use AdapterView.onSelectedItemListener to identify a user selection in the ListView and then use the Button to delete the selected item. For the Button, I'm implementing Button.onClickItemListener.
To get the list items into the ListView I'm using a dialog. I'm using an interface to send the string input from the dialog to the ListView in RecipeFragmentNew. I haven't been having issues getting the Strings from the dialog to RecipeFragmentNew, so I haven't included any of that code.
Problem: Button is deleting list items but it is deleting the first item in the list, not the item that is being selected.
Recipe.java
public class Recipe {
private UUID mID;
private String mName;
private Date mDate;
private boolean mIsFavorite;
private final ArrayList<Ingredient> ingredients;
public final ArrayList<Instruction> instructions;
public Recipe() {
mID = UUID.randomUUID();
mDate = new Date();
this.ingredients = new ArrayList<>();
this.instructions = new ArrayList<>();
}
public UUID getID() {
return mID;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public boolean isFavorite() {
return mIsFavorite;
}
public void setFavorite(boolean favorite) {
mIsFavorite = favorite;
}
public ArrayList<Ingredient> getIngredients() {
return ingredients;
}
public ArrayList<Instruction> getInstructions() {
return instructions;
}
}
Ingredient.java
public class Ingredient {
private String name;
private String amount;
public Ingredient(String name, String amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public String getAmount() {
return amount;
}
#Override
public String toString() {
return this.name + " " + this.amount;
}
}
The arrayList is retreived from Recipe class using mRecipe.getIngredients().
The ListView is mIngredientWindow.
RecipeFragmentNew.java
public class RecipeFragmentNew extends Fragment implements IngredientListDialog.OnInputSelected {
public static final String TAG = "RecipeFragmentNew";
public static final String DIALOG_INGREDIENTS = "DialogIngredients";
private Recipe mRecipe;
private EditText mNameField;
private Button mIngredientAdd;
private Button mIngredientDelete;
private ListView mIngredientWindow;
private int listViewPosition;
private ArrayAdapter<Ingredient> listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID recipeId = (UUID) getArguments().getSerializable(ARG_RECIPE_ID);
mRecipe = RecipeQueue.get(getActivity()).getRecipe(recipeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lists_detail_view, container, false);
mIngredientDelete = v.findViewById(R.id.delete_ingredient_button);
mIngredientDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < mRecipe.getIngredients().size(); i++) {
if (i == listViewPosition) {
mRecipe.getIngredients().remove(i);
}
listAdapter.notifyDataSetChanged();
}
}
});
listAdapter = new ArrayAdapter<Ingredient>(
getActivity(),
android.R.layout.simple_list_item_1,
mRecipe.getIngredients()
);
mIngredientWindow = v.findViewById(R.id.ingredients_window);
mIngredientWindow.setAdapter(listAdapter);
AdapterView.OnItemSelectedListener itemSelectedListener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
listViewPosition = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
Button is deleting list items but it is deleting the first item in
the list, not the item that is being selected.
The variable listViewPosition is always 0 because the setOnItemSelectedListener is not called. please check this answer
So you can replace this method with setOnItemClicklistener like the below code:
mIngredientWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//mIngredientWindow.setSelection(position);
listViewPosition = position;
}
});
Simple
the listViewPosition variable always equals 0
Here's Why, You have defined an object from AdapterView.OnItemSelectedListener but you never attache it to the listview
all you need to do is add
mIngredientWindow.setOnItemSelectedListener (itemSelectedListener );

Add to favorite using room Database

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

How to send data of the list item of a custom arraylist when clicked to another activity?

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
}

EventsAdapter() in EventsAdapater cannot be applied [duplicate]

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

Android SQLite CustomAdapter and Custom ListView

I am a very new android developer and I have been trying to learn it by creating simple apps.
Right now I'm stuck on trying to create a custom ListView for my app.
My data's are being stored in SQLite and I'm calling these data's as a List. I can't seem to find a website to demonstrate how to get SQLite data's to work with Custom ListView.
Below are my data's and I hope someone can help me with setting up my custom adapter to work with my sqlite data's.
Records.java
public class Records {
private long id;
private String name;
private String type;
private float mf;
private float mftop;
private float mfbot;
private float mfleft;
private float mfright;
private float rf;
private float rftop;
private float rfbot;
private float rfleft;
private float rfright;
private float tb;
private float tbtop;
private float tbbot;
private float tbleft;
private float tbright;
private float bridge;
private float bridgel;
private float bridger;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
// Middle Finger
public float getMF() {
return mf;
}
public void setMF(float mf) {
this.mf = mf;
}
public float getMFTop() {
return mftop;
}
public void setMFTop(float mftop) {
this.mftop = mftop;
}
public float getMFBot() {
return mfbot;
}
public void setMFBot(float mfbot) {
this.mfbot = mfbot;
}
public float getMFLeft() {
return mfleft;
}
public void setMFLeft(float mfleft) {
this.mfleft = mfleft;
}
public float getMFRight() {
return mfright;
}
public void setMFRight(float mfright) {
this.mfright = mfright;
}
//Ring Finger
public float getRF() {
return rf;
}
public void setRF(float rf) {
this.rf = rf;
}
public float getRFTop() {
return rftop;
}
public void setRFTop(float rftop) {
this.rftop = rftop;
}
public float getRFBot() {
return rfbot;
}
public void setRFBot(float rfbot) {
this.rfbot = rfbot;
}
public float getRFLeft() {
return rfleft;
}
public void setRFLeft(float rfleft) {
this.rfleft = rfleft;
}
public float getRFRight() {
return rfright;
}
public void setRFRight(float rfright) {
this.rfright = rfright;
}
//Thumb
public float getTB() {
return tb;
}
public void setTB(float tb) {
this.tb = tb;
}
public float getTBTop() {
return tbtop;
}
public void setTBTop(float tbtop) {
this.tbtop = tbtop;
}
public float getTBBot() {
return tbbot;
}
public void setTBBot(float tbbot) {
this.tbbot = tbbot;
}
public float getTBLeft() {
return tbleft;
}
public void setTBLeft(float tbleft) {
this.tbleft = tbleft;
}
public float getTBRight() {
return tbright;
}
public void setTBRight(float tbright) {
this.tbright = tbright;
}
//Bridge
public float getBridge() {
return bridge;
}
public void setBridge(float bridge) {
this.bridge = bridge;
}
public float getBridgeL() {
return bridgel;
}
public void setBridgeL(float bridgel) {
this.bridgel = bridgel;
}
public float getBridgeR() {
return bridger;
}
public void setBridgeR(float bridger) {
this.bridger = bridger;
}
//Will be used by the ArrayAdapter in the ListView
#Override
public String toString() {
return name;
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<NTAdapter> {
Context context;
int layoutResourceId;
NTAdapter data[] = null;
public CustomAdapter(Context context, int layoutResourceId, NTAdapter[] data) {
super(context, layoutResourceId, data);
// TODO Auto-generated constructor stub
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
DataHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DataHolder();
holder.dataName = (TextView)row.findViewById(R.id.dataName);
holder.dataType = (TextView)row.findViewById(R.id.dataType);
row.setTag(holder);
} else {
holder = (DataHolder)row.getTag();
}
NTAdapter ntadapter = data[position];
holder.dataName.setText(ntadapter.name);
holder.dataType.setText(ntadapter.type);
return row;
}
static class DataHolder {
TextView dataName;
TextView dataType;
}
}
NTAdapter.java
public class NTAdapter {
public int id;
public String name, type;
public NTAdapter() {
super();
}
public NTAdapter(int id, String name, String type) {
super();
this.id = id;
this.name = name;
this.type = type;
}
}
DataLayout.java
public class DataLayout extends ListActivity {
private RecordsDataSource datasource;
Button btnDataCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_layout);
datasource = new RecordsDataSource(this);
datasource.open();
List<Records> values = datasource.getAllRecords();
//use the SimpleCursorAdapter to show the
//elements in a ListView
ArrayAdapter<Records> adapter = new ArrayAdapter<Records>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
/**
CustomAdapter adapter = new CustomAdapter(this, R.layout.data_layout_listview, values);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
*/
Button btnDataCancel = (Button)findViewById(R.id.btnDataCancel);
//Cancel Button
btnDataCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent goMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(goMain);
finish();
}
});
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Please note that within my DataLayout.java, I have been trying to get my sqlite data's to work with my custom listview setup.
/**
CustomAdapter adapter = new CustomAdapter(this, R.layout.data_layout_listview, values);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
*/
I do know that my problem is that my NTAdapter.java and my CustomAdapter.java aren't being setup properly. However, I don't know how to fix it so that it will accept the list of data's which are being stored in values
As the code started to get abit too long to read, I didn't post my other classes. But please do note that everything is working fine if I'm not using my custom listview, as it is not yet working.
Any help will be appreciated. Thank you in advance.
edit: Also, I know that NTAdapter isn't really needed, but I don't know how to make it so that my CustomAdapter.java will get the data's from my values and uses them to setup my custom ListView.
edit2: For those that are wondering what values is, please refer to DataLayout.java.
.
What you are doing while making a CustomAdapter is that you are trying to pass a List
to a constructor which accepts NTAdapter array . So your program is not supposed to work properly.
What you could do is make your CustomAdapter class something like the following :
public class CustomAdapter extends ArrayAdapter<Records> {
Context context;
int layoutResourceId;
List<Records> data;
public CustomAdapter(Context context, int layoutResourceId, ArrayList<Records> data) {
super(context, layoutResourceId, data);
// TODO Auto-generated constructor stub
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data=data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
DataHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DataHolder();
holder.dataName = (TextView)row.findViewById(R.id.dataName);
holder.dataType = (TextView)row.findViewById(R.id.dataType);
row.setTag(holder);
} else {
holder = (DataHolder)row.getTag();
}
Records records = data.get(position);
holder.dataName.setText(records.getName());
holder.dataType.setText(records.getType());
return row;
}
static class DataHolder {
TextView dataName;
TextView dataType;
}

Categories

Resources