Using button to delete selected item in Listview w/ ArrayAdapter - java

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

Related

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 get spinner value after item select in spinner

I am using spinner in my app I am populating spinner with the data fetching from the server.I am using Retrofit2 as a networking library. There are 2 values I am fetching from the server one is state name and other is state id.
In spinner I am showing state name, but on select state it should select corresponding state name id that I have fetched from the server. In spinner state name is showing successfully but I want to gets corresponding state name id that I have in POJO class and not item position.
Below is my code:
Server response is given below:
{
"data": [
{
"id": "5",
"name": "Bihar"
},
{
"id": "7",
"name": "Chhattisgarh"
},
{
"id": "10",
"name": "Delhi"
}
],
"status": true,
"code": 200
}
States.java
public class States {
#SerializedName("data")
#Expose
private List<AllStates> data = null;
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("code")
#Expose
private int code;
public States(){
}
public List<AllStates> getData() {
return data;
}
public void setData(List<AllStates> data) {
this.data = data;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
AllStates.java
public class AllStates {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
public AllStates(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CalenderFragment.java
public class CalendarFragment extends Fragment {
Spinner spinnerState;
List<AllStates> stateList = new ArrayList<>();
ArrayList<String> stateSpinnerList = new ArrayList<>();
public CalendarFragment() {
// 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_calendar, container, false);
spinnerState = view.findViewById(R.id.spinnerState);
spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
apiService.allStates().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<States>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(States states) {
stateList = states.getData();
stateSpinnerList.add("Select state");
for(int i =0;i<stateList.size();i++){
stateSpinnerList.add(stateList.get(i).getName());
}
ArrayAdapter<String> stateAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,stateSpinnerList);
spinnerState.setAdapter(stateAdapter);
}
#Override
public void onError(Throwable e) {
TastyToast.makeText(getActivity(),e.getMessage(),TastyToast.LENGTH_SHORT,
TastyToast.ERROR).show();
}
#Override
public void onComplete() {
}
});
return view;
}
}
How can I get the desired result?
So what I understand is you are selecting state from Spinner and getting name of state but you want to get stateId.
one possible solution, I can think of is to use HashMap<StateName, StateId> map.
when you receive state name from spinner just call map.get(name) and you will get state Id.
Edit:
you can implement it like this
HashMap<String, Integer> map = new HashMap<>();
for(state in list){
map.put(state.name, state.id);
}
spinnerState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String name = parent.getItemAtPosition(position).toString();
int id = map.get(name);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If you don't want to use a custom adapter then fetch selected spinner position and using that position fetch your State model
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// int position = spinnerState.getSelectedItemPosition();
if(position >= 1){
AllStates allStates = stateList.get(position - 1)
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Now you can access id from allStates model

How to add elements to a list from another class?

So i have my a list on my main activity that i want to be able to access in another class. The second class is supposed to add more records to the list based on the users input but i don't know how to access it. Can anybody help?
Contactos.java:
This is my main class and its also where the list is kept, i did a test run on it so that's why the constructor is filled with numbers. I want to be able to add to the list from another class.
public class Contactos extends AppCompatActivity {
private Button btnReciente;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReciente = (Button) findViewById(R.id.Reciente);
listView = (ListView) findViewById(R.id.list1);
List<contactosLista> list1 = new ArrayList<contactosLista>();
list1.add(new contactosLista("1","2","3","4","5","6"));
ContactosAdapter adapter = new ContactosAdapter(this,list1);
listView.setAdapter(adapter);
ContactosAdapter.java: This is where i inflate the list, i use it so i can use a .xml file to better display the values in the list.
public class ContactosAdapter extends BaseAdapter
{
private Context mContext;
private List<contactosLista>mListaContactos;
public ContactosAdapter(Context context, List<contactosLista> list)
{
mContext = context;
mListaContactos = list;
}
#Override
public int getCount() {
return mListaContactos.size();
}
#Override
public Object getItem(int position) {
return mListaContactos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
contactosLista entrada = mListaContactos.get(position);
if(convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.contactos_row,null);
}
TextView Contact = (TextView) convertView.findViewById(R.id.Contacto);
Contact.setText(entrada.getmName() + " -- " + entrada.getmEmpresa());
return convertView;
}
}
contactosLista.java: This the class that defines the elements that the list needs. i made a constructor that accommodates all the strings and made all the setters & getters
public class contactosLista
{
private String mName;
private String mEmpresa;
private String mRazon;
private String mDireccion;
private String mEstatus;
private String mPaquete;
public contactosLista(String mName, String mEmpresa, String mRazon, String mDireccion, String mEstatus, String mPaquete)
{
this.mName = mName;
this.mEmpresa = mEmpresa;
this.mRazon = mRazon;
this.mDireccion = mDireccion;
this.mEstatus = mEstatus;
this.mPaquete = mPaquete;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmEmpresa() {
return mEmpresa;
}
public void setmEmpresa(String mEmpresa) {
this.mEmpresa = mEmpresa;
}
public String getmRazon() {
return mRazon;
}
public void setmRazon(String mRazon) {
this.mRazon = mRazon;
}
public String getmDireccion() {
return mDireccion;
}
public void setmDireccion(String mDireccion) {
this.mDireccion = mDireccion;
}
public String getmEstatus() {
return mEstatus;
}
public void setmEstatus(String mEstatus) {
this.mEstatus = mEstatus;
}
public String getmPaquete() {
return mPaquete;
}
public void setmPaquete(String mPaquete) {
this.mPaquete = mPaquete;
}
}
createContact.java: finally this is the class where i want to be able to access the list from Contactos.java, I have a layout file that has a bunch of Edit text so that i can record input from the user. When the user clicks on the button to save i want my void "GuardarCon" to save the input from the user to strings and then i want to use those strings as parameters for my list. This is where the problem arises, i don't know how to call the list. PLS help.
public class createContact extends AppCompatActivity
{
EditText nombre;
EditText empresa;
EditText razon;
EditText direccion;
EditText estatus;
EditText paquete;
String snombre;
String sempresa;
String srazon;
String sdireccion;
String sestatus;
String spaquete;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_contact);
nombre = (EditText) findViewById(R.id.nombreT);
empresa = (EditText) findViewById(R.id.empresaT);
razon = (EditText) findViewById(R.id.razonSocialT);
direccion = (EditText) findViewById(R.id.direccionT);
estatus = (EditText) findViewById(R.id.EstatusT);
paquete = (EditText) findViewById(R.id.paqueteT);
}
public void GuardarCon(View view)
{
snombre = nombre.getText().toString();
sempresa = empresa.getText().toString();
srazon = razon.getText().toString();
sdireccion = direccion.getText().toString();
sestatus = estatus.getText().toString();
spaquete = paquete.getText().toString();
}
Create a singleton class and access and modify data as you want !
public class DataHolder{
public static final DataHolder instance = new DataHolder();
private List<Your_Data_Type> data;
//Your methods goes here...
}
You could use startActivityForResult method to start createContact from Contactos activity and after the addition process is done use setResult method to return the added item to the Contactos activity and handle adding the item to the list in onActivityResult.
take a look at this link for further info:
https://developer.android.com/training/basics/intents/result

No setter/field for name found on class for Firebase

I have seen others ask this question but it seems to me that I have done all the things that are required and I'm still not getting it to work. I am getting the No setter/field for name found on class error. Database
I included a pic of what my database is. It is incredibly simple.
public class Restaurants {
private String name;
public Restaurants(){}
public Restaurants(String name)
{
this.name = name;
}
public String getRestaurant()
{
return name;
}
public void setRestaurant(String name)
{
this.name = name;
}
#Override
public String toString() {
return "Restaurants" +
"name" + name;
}
}
I have my getter and setter here so in theory it should be working.
public class RestaurantSelectionList extends Fragment {
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mRestReference = mRootRef.child("restaurants");
List<String>listofrest = new ArrayList<String>();
ListView restaurantListView;
ListAdapter restaurantListAdapter;
public RestaurantSelectionList(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.restaurant_selection_list_frag,container,false);
restaurantListView = (ListView) view.findViewById(R.id.restaurantListView);
restaurantListAdapter = new FirebaseListAdapter<Restaurants>(getActivity(),Restaurants.class,R.layout.individual_restaurant_name,mRestReference) {
#Override
protected void populateView(View v, Restaurants model, int position) {
TextView restName = (TextView) v.findViewById(R.id.restname);
restName.setText(model.getRestaurant());
listofrest.add(position,model.getRestaurant());
}
};
restaurantListView.setAdapter(restaurantListAdapter);
restaurantListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getActivity(), "test", Toast.LENGTH_SHORT).show();
}
});
return view;
}
This is the code that calls it. Please tell me what I am missing. This is going on 4 hours of looking at this.
Please change your Model Class to:
public class Restaurants {
private String name;
public Restaurants(){}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
#Override
public String toString() {
return "Restaurants" + "name" + name;
}
}

SQLite With List

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

Categories

Resources