I have custom adapter and an ArrayList<String> called groceries containing whatever user puts there.
This is my method saving the listView whenever the user puts something there or deletes:
public void saveGroceriesList() {
sharedPreferences = getContext().getSharedPreferences("com.me.application", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(groceries);
sharedPreferences.edit().putStringSet("Groceries", set).apply();
}
And here I set text strikethrough and change color onClick for listView:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
list_content = (TextView) view.findViewById(R.id.list_content);
if (!isChecked){
isChecked = true;
list_content.setPaintFlags(list_content.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
list_content.setTextColor(Color.parseColor("#a7a7a7"));
saveGroceriesList();
} else {
isChecked = false;
list_content.setPaintFlags(list_content.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
list_content.setTextColor(Color.parseColor("#000000"));
saveGroceriesList();
}
}
});
where list_content is my TextView for listView. The problem is, that the saveGroceriesList(); method wont save the color.
How can I save the color and strikethrough text with sharedPreferences?
I cannot see where are you adding color values into the Set, I think it is that problem
The best solution, by far IMHO, is to use a better data storage model. For example, you could use a SQLite database, with columns for the various properties (name, checked). Or, you could store your data in a JSON file, or an XML file, or a CSV file, or some other form of simple file.
If, for whatever reason, you are sure that you want to use SharedPreferences, you could:
Create a GroceryItem class that knows the name and checked state information
Hold an ArrayList<GroceryItem> that is your in-memory representation of your data model
Use Gson, Jackson, or some other JSON parser to convert the ArrayList<GroceryItem> to and from a String representation
Save the String in SharedPreferences
Related
I managed to get data from the Firebase Database and show it in an alphabetical order in my ListView.
Now I want to show the value from my database, if I click on an item in the ListView. As an example in my database it says "BB" as a name and the value is "Bye, bye".
So after an onClick event in the ListView a Toast message should show the value. How can I do this?
HereĀ“s my database:
To show the value after you click on an item:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final String selectedFromList = (String) list.getItemAtPosition(position);
ref.orderByChild(selectedFromList).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String retrievedValue=dataSnapshot.child(selectedFromList).getValue().toString();
Toast.makeText(activity_name.this, "Value: "+retrievedValue, Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Assuming you have a listview with the following:
Afk
MFG
After clicking on an item, get the item at that postion and use it in a query orderByChild and retrieve it's value.
The sample code 'Peter Haddad' provided in his answer basically works fine... IF you design your database in a better way I did back then.
If you use his code, you get the value of the database entry (so the text on the right side in the console database, but I wanted to get the left one.
I recommend using a structure like in the Firebase Docs about Structuring.
It could look something like this:
Here are two posts about searching and querying those kind of databases:
How to do a simple search in string in Firebase database?
Query based on multiple where clauses in Firebase
If you anyways want to do it in the way I tried, it`s possible:
In the sample code from 'Peter Haddad' simply replace dataSnapshot.child(selectedFromList).getValue().toString() with dataSnapshot.child(selectedFromList).getKey().toString().
The key represents the text on the left side of the console database structure.
I am fairly beginner and currently writing an app which contains a list of Restaurants. I am using a SQLite database to store the "Restaurant" objects and am using a CursorAdapter to display them into a ListView.
Currently the fields are a photo, the name of the restaurant and its location.
I want to have one more TextView which shows how many times that certain restaurant appears in the database. I'm having trouble figuring out how to do this inside my CursorAdapter class.
Below is my bindView method in the CursorAdapter class where the existing views get updated.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find individual views that we want to modify in the list item layout
ImageView foodImageView = (ImageView) view.findViewById(R.id.food_image_view);
TextView restaurantNameTextView = (TextView) view.findViewById(R.id.restaurant_name_text_view);
TextView restaurantLocationTextView = (TextView) view.findViewById(R.id.restaurant_location_text_view);
// Find the columns of restaurant attributes that we're interested in
int foodPictureColumnIndex = cursor.getColumnIndex(RestaurantEntry.COLUMN_FOOD_PHOTO_URL);
int restaurantNameColumnIndex = cursor.getColumnIndex(RestaurantEntry.COLUMN_RESTAURANT_NAME);
int restaurantLocationColumnIndex = cursor.getColumnIndex(RestaurantEntry.COLUMN_RESTAURANT_LOCATION);
// Read the restaurant attributes from the Cursor for the current restaurant
String foodPhoto = cursor.getString(foodPictureColumnIndex);
String restaurantName = cursor.getString(restaurantNameColumnIndex);
String restaurantLocation = cursor.getString(restaurantLocationColumnIndex);
// Update the Views with the attributes for the current restaurant
Picasso.with(mContext).load(foodPhoto).into(foodImageView);
restaurantNameTextView.setText(restaurantName);
restaurantLocationTextView.setText(restaurantLocation);
}
Answered my own question; used a temporary ArrayList to track how many times a certain name appears in the database table
I am trying to display a list in android using guidance from vogella's tutorial for sqlite in android :
this is part of my ProjectListDataSource class (This gets all data from the sqlite database):
public List<ProjectList> getAllProjects() {
List<ProjectList> projects = new ArrayList<ProjectList>();
Cursor cursor = database.query(ProjectListHelper.TABLE_PROJECT_LIST,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
projects.add(cursorToProjectList(cursor));
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return projects;
}
private ProjectList cursorToProjectList(Cursor cursor) {
ProjectList projList = new ProjectList();
projList.setId(cursor.getLong(0));
projList.setProjName(cursor.getString(1));
projList.setProjComment(cursor.getString(2));
projList.setProjDateTime(cursor.getString(3));
return projList;
}
And this is my activity class :
public class ProjectListActivity extends ListActivity implements
OnClickListener {
private static final String TAG = "ProjectListActivity";
private ProjectListDataSource datasource;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_projectlist);
Log.d(TAG, "On Creat'd");
init();
}
private void init() {
// Getting data from database and adding to ListView
datasource = new ProjectListDataSource(this);
datasource.open();
List<ProjectList> values = datasource.getAllProjects();
ArrayAdapter<ProjectList> adapter = new ArrayAdapter<ProjectList>(this,
android.R.layout.simple_list_item_activated_1, values);
setListAdapter(adapter);
}
But on doing that I am getting unexpected result like this (see image) :
http://i.imgur.com/tQMooi8.png
But the database has records like this (see image):
http://i.imgur.com/HfY2azs.png
Can anyone please explain and give a solution as to why I cant get the list view to show the records as in the database...
Thanks,
Viney
Basic adapters, like ArrayAdapter or CursorAdapter, will map only one value to a single view. Here, a ProjectList object to a TextView with the id of android.R.id.simple_list_item_activated_1
You need a single layout(for a single view within the ListView) with multiple views to which you will map id, name, date, comment, etc. You need to extend one of the adapters. Preferably BaseAdapter or CursorAdapter.
There are several issues here, depending on what you want to display.
The reason you're seeing the object string reference in your list is because you're using a plain ArrayAdapter, which simply calls toString() on the objects in the array. If you override toString() in ProjectList, you can display what you want (though that's normally not the best way to solve this problem).
Another option which would allow you to keep using a plain ArrayAdapter would be to create an array of strings from the ProjectList objects of the data you want to display. A bit wasteful, but that's another option.
What you normally want to do is extend ArrayAdapter and override getView(). In getView() you assign the data you want to display in the view.
If you want to display all the data from your ProjectList objects in a single list item, you'll also need to create a custom layout to represent the row.
I'm passing a listview in to an onselect but theres a couple of ways it's called from different listviews. So i'm trying to work out which listview is being clicked.
I thought I could do the following however the string thats returned is like com.myapp.tool/id/32423423c (type thing) instead of lvAssets.
Here is what I've got:
#Override
public void onNumberRowSelect(ListView listview, clsNameID stat) {
if(listview.getAdapter().toString().equals("lvGenericAssets")){
} else if(listview.getAdapter().toString().equals("lvAssets")){
} else {
Functions.ShowToolTip(getApplicationContext(),
listview.getAdapter().toString());
}
}
As Emil Adz said in first, you can get the id of your list by calling list.getId();
Then use String idList = getResources().getResourceEntryName(id); and you will be able to get the name of the id you have given to your list
Why wont you just use: list.getId(); if you defined it in the XML file then you should define there an id for you ListView.
If you are doing this from code then you can use the list.setId(); to first set it's id.
Another thing you can do is to add a Tag to your listView: list.setTag("list1");
and latter on distinct this listView using the Tag: list.getTag();
I'm trying to figure out how to capture data from a form using EditText & Spinner's and insert it into a SQLite database. I am able to write the hard coded attributes but when I try to use R.id.fieldName it throws an error due to being an Integer vice a String.
public class PetAdd extends Activity {
DBAdapter db = new DBAdapter(this);
private OnClickListener btnPetAddListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
db.open();
long id;
id = db.insertPet("name", "type", "breed", "sex", "notes");
/**id = db.insertPet(R.id.petName, R.id.SpinnerPetType, R.id.petBreed, R.id.SpinnerPetGender, R.id.EditTextPetAddOptions);*/
db.close();
}
};
I'm still trying to learn all this stuff and my brain is fried from looking at a plethora of online tutorials, examples and Google documentation. If anyone can show me how to do this or direct me to a barney style tutorial that breaks it down for me to understand what's going on, it'd be greatly appreciated.
R.id.fieldName is a numeric reference to the item in your Activity (provided it's part of your layout).
You'll need to call findViewById(R.id.fieldName) to get a refererene to it. You'll also need to cast it to the correct type of view (in your case EditText) and then call getText().toString() on the whole thing.
Putting it all together...
EditText myField = (EditText)findViewById(R.id.userName); //assuming you have a field named userName in your XML
String userNameValue = myField.getText().toString();
Oh, and welcome to Stack... don't forget to mark answers as correct and up-vote them when they're helpful.
If you use R.id.name you are in fact using internally generated int that Android uses. You need the raw data your spinner has.
I suggest you play with getItem and getItemId in your Spinner. If you are using a SimpleAdapter you can expect to get the ID of your item with getItemId.
The implementation of getItem is up to you. I usually use BaseAdapter or in the case of Spinners, ArrayAdapter, which has several convenient methods.
And with the EditText you need to call getText() to the EditText.