sqlite Viewlist error - android

i trying tu put some elements from database to a List view,
my problem is that when i starrt my activity, I get this:
**com.example.restaurant.Restaurant#2be2d1d0
com.example.restaurant.Restaurant#2be3d3a8**
instead of database objects.
public class Liste extends Activity{
private ListView listview;
private Button boutonAjouter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.liste_restaurant);
listview = (ListView)findViewById(R.id.listView1);
Restaurant mcdo = new Restaurant("mcdo","brossard","take-out","fastfood","450-555-5555");
Restaurant burger = new Restaurant("burger","longueuil","take-out","fastfood","450-999-9999");
RestaurantBDD restaurantBDD = new RestaurantBDD(this);
restaurantBDD.openForWrite();
restaurantBDD.insertRestaurant(mcdo);
restaurantBDD.insertRestaurant(burger);
ArrayList <Restaurant> restaurantlist = restaurantBDD.getAllRestaurants();
restaurantBDD.close();
ArrayAdapter <Restaurant> adapter = new ArrayAdapter<Restaurant>(this, android.R.layout.simple_list_item_1, restaurantlist);
listview.setAdapter(adapter);
boutonAjouter = (Button) findViewById(R.id.btn_nouveau);
boutonAjouter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Liste.this, Formulaire.class);
startActivity(intent);
}
});
}
}

If you want to show a list with the names of the restaurants, supposing that your Restaurant class contains a string attribute "name", you should first create an array containing the names of the restaurants and then use an ArrayAdapter <String>:
String[] values = new String[restaurantlist.size()];
for(int i=0;i<restaurantlist.size();i++) {
values[i] = restaurantlist.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listview.setAdapter(adapter);

Related

How to remove item from ArrayList<HashMap<String, String>> one by one in android

I am new to Android. I am Using "com.devsmart.android.ui.HorizontalListView" to show my items(playing cards). In the List I am getting 8 cards in the first attempt. What I want if I again call the method the there must be 7 cards so on means 1 cards must be remove from the list at each time till the list gets empty. But I am not able not do this removing of item from the list. I am posting my code here. Help will be appreciated.
MainActivity.java
ArrayList<HashMap<String, String>> aList9;
Button btn_aditional_card;
HorizontalListView list1;
int[] cards3 = new int[]{
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1,
R.drawable.card1
};
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_aditional_card = (Button) findViewById(R.id.btn_aditional_card);
list1 = (HorizontalListView) findViewById(R.id.listview1);
btn_aditional_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add8();
}
});
}
public void add8() {
final android.view.animation.Animation animScale = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
list1.startAnimation(animScale);
aList9 = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 8; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("card", Integer.toString(cards3[i]));
aList9.add(hm);
}
String[] from = {"card"};
int[] to = {R.id.ImageView};
final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList9, R.layout.activity_animation__adapter, from, to);
list1.setAdapter(adapter);
adapter.notifyDataSetChanged();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
});
}
Here removing of item from the list must be done on list1.setOnItemClickListener but I don't have any idea how.
In your list1.setOnItemClickListener, do this:
if (aList9.size() > 0) {
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
When removing item from data list, you have to notify your adapter to update view.
You can remove the last item from the list like;
if (aList9.size() > 0) {
aList9.remove(aList9.size() - 1);
}
Another solution,
Take Length of your integer array and traverse the loop inside your add8 method according to this length and at the end of the method decrement the length by one, like;
int length = cards3.length;
Inside your add8 method;
for (int i = 0; i < length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("card", Integer.toString(cards3[i]));
aList9.add(hm);
}
After for loop decrement the length like;
length--;
Hope you'll get the solution.
In your main activity the code should look like.I am using arraylist instead you can use hashmap.This code is only to show you way what you need to do. follow this code in your project you will get solution this is tested in my site and working fine you need to change somewhere according to your code.In button click i am only removing last item from arraylist and notifying that dataset changed.hope it will help you.
ArrayList<String> arrlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrlist.add("B");
arrlist.add("C");
arrlist.add("D");
arrlist.add("E");
arrlist.add("F");
arrlist.add("G");
ListView lv = (ListView) findViewById(R.id.listview);
Button btnShowList = (Button) findViewById(R.id.btnShowList);
final ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arrlist);
//Listview adapter
lv.setAdapter(adapter);
btnShowList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (arrlist.size() > 0) {
arrlist.remove(arrlist.size() - 1);
adapter.notifyDataSetChanged();
}
}
});
}
Read the comments
class MainActivity extends AppCompatActivity {
//make your Adapter global
private SimpleAdapter adapter;
ArrayList<HashMap<String, String>> aList9;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add8();
btn_aditional_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// on button click you can add a view to the listview if you want
// if you don't want this just comment out the following line
// i still don't understand what you want to do with this button
alist9.add(...);
// if you add stuff in the array list then notify the adapter
// it will update the view
adapter.notifyDataSetChanged();
}
});
}
public void add8() {
// initialize your ArrayList and listview
//populate them
for(int i = 0; i < 8; i++) {
// do your stuff.
// populate the list
}
// initialize your adapter as before
adapter = new SimpleAdapter(....);
listview.setadapter(adapter);
adapter.notifyDataSetChanged();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// delete the items like this
// check if size is greater than 0 and then remove
aList9.remove(aList9.size() - 1);
adapter.notifyDataSetChanged();
}
});
}
}

android Spinner set Text give error in setText

I am working on EditText and Spinner . When I set text for EditText it were fine but when I try to set text for Spinner it give error.
this is code for set text EditText
New_Name.setText(NewName);
here New_Name is EditText
this is code for set text Spinner
New_Quantity.setText(NewQuantity);
here New_Quantity is Spinner
this is the full code.
public class UpdateFoodActivity extends Activity {
EditText Name_Search,New_Name,New_Calorie,New_Fat,New_Protein,New_Sugar,New_carbohydrates;
Spinner New_Quantity;
TextView title_text;
String SearchName,NewName,NewQuantity,NewCalorie,NewFat,NewProtein,NewSugar,Newcarbohydrates;
FoodDbHelper foodDbHelper;
SQLiteDatabase sqLiteDatabase;
Button UpdateButton;
ArrayAdapter<CharSequence> adapter;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.update_food_activity);
Name_Search = (EditText)findViewById(R.id.name_search);
New_Name = (EditText)findViewById(R.id.new_name);
New_Quantity = (Spinner)findViewById(R.id.new_quantity);
adapter = ArrayAdapter.createFromResource(this, R.array.quant, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
New_Quantity.setAdapter(adapter);
New_Quantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
New_Calorie = (EditText)findViewById(R.id.new_calorie);
New_Fat = (EditText)findViewById(R.id.new_fat);
New_Protein = (EditText)findViewById(R.id.new_protein);
New_Sugar = (EditText)findViewById(R.id.new_sugar);
New_carbohydrates = (EditText)findViewById(R.id.new_vitamins);
UpdateButton = (Button)findViewById(R.id.update_button);
title_text = (TextView)findViewById(R.id.title_text);
New_Name.setVisibility(View.GONE);
New_Quantity.setVisibility(View.GONE);
New_Calorie.setVisibility(View.GONE);
New_Fat.setVisibility(View.GONE);
New_Protein.setVisibility(View.GONE);
New_Sugar.setVisibility(View.GONE);
New_carbohydrates.setVisibility(View.GONE);
UpdateButton.setVisibility(View.GONE);
title_text.setVisibility(View.GONE);
}
public void searchFood(View view){
SearchName = Name_Search.getText().toString();
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
Cursor cursor = foodDbHelper.getFood(SearchName,sqLiteDatabase);
if (cursor.moveToFirst()) {
NewQuantity = cursor.getString(0);
NewCalorie = cursor.getString(1);
NewFat = cursor.getString(2);
NewProtein = cursor.getString(3);
NewSugar = cursor.getString(4);
Newcarbohydrates = cursor.getString(5);
NewName = SearchName;
New_Name.setText(NewName);
New_Quantity.setText(NewQuantity);
New_Calorie.setText(NewCalorie);
New_Fat.setText(NewFat);
New_Protein.setText(NewProtein);
New_Sugar.setText(NewSugar);
New_carbohydrates.setText(Newcarbohydrates);
New_Name.setVisibility(View.VISIBLE);
New_Quantity.setVisibility(View.VISIBLE);
New_Calorie.setVisibility(View.VISIBLE);
New_Fat.setVisibility(View.VISIBLE);
New_Protein.setVisibility(View.VISIBLE);
New_Sugar.setVisibility(View.VISIBLE);
New_carbohydrates.setVisibility(View.VISIBLE);
UpdateButton.setVisibility(View.VISIBLE);
title_text.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),
"No Dish Found " ,
Toast.LENGTH_SHORT).show();
}
}
public void updatebutton(View view)
{
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getWritableDatabase();
String name,quantity,calorie,fat,protein,sugar,carbohydrates;
name = New_Name.getText().toString();
quantity = New_Quantity.getSelectedItem().toString();
calorie = New_Calorie.getText().toString();
fat = New_Fat.getText().toString();
protein = New_Protein.getText().toString();
sugar = New_Sugar.getText().toString();
carbohydrates = New_carbohydrates.getText().toString();
int count = foodDbHelper.updateInformation(SearchName,name,quantity,calorie,fat,protein,sugar,carbohydrates,sqLiteDatabase);
Toast.makeText(getApplicationContext(),count+" dish updated",Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,UpdateFoodActivity.class);
startActivity(intent);
}
}
In order to add entries to the spinner you need to define an Adapter i give you an example:
spinner = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.spinner_item, list);
spinner.setAdapter(dataAdapter);
Spinner likes ListView, need an adapter for rendering data. Adapter, in simple term, is a collection of items. (As you see ListView always contains list of item and also Spinner). Nevertheless, Adapter of spinner often a list of string. (because spinner just represents user choice)
In your example, You can simply create ArrayAdapter and assign again to Spinner.
private void setTextForSpinner(Spinner spinner) {
String[] items = {"Stack", "Over", "Flow"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
}
If apply above code to your example, you can change again to:
private void setTextForSpinner(Spinner spinner, String NewName) {
String[] items = {NewName};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
}
Hope this help :)

update listView from ActionBarActivity

My MainActivity, which extends ActionBarActivity, has a ListView, which I want to reload using notifyDataSetChanged(), but I do not know how to do this.
My code so far:
public class MainActivity extends ActionBarActivity {
private JournalEntryDataSource datasource;
private ListView listView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new JournalEntryDataSource(this);
datasource.open();
listView = (ListView) findViewById(R.id.list);
List<JournalEntry> values = datasource.getAllJournalEntries();
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Log.i("app", "Deleting item number " + position);
datasource.deleteJournalEntry((JournalEntry) listView.getAdapter().getItem(position));
//I would like to do this here:
//ArrayAdapter<JournalEntry> adapter = (ArrayAdapter<JournalEntry>) getListAdapter();
//adapter.notifyDataSetChanged();
}
});
}
But I get an error when calling adapter.notifyDatasetChanged()...
Any tips? I've been looking at similar questions and no luck so far...
--------EDITED CODE---------
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new JournalEntryDataSource(this);
datasource.open();
listView = (ListView) findViewById(R.id.list);
values = datasource.getAllJournalEntries();
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
ArrayAdapter<JournalEntry> adapter = (ArrayAdapter<JournalEntry>) getListAdapter();
// use the SimpleCursorAdapter to show the
// elements in a ListView
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
listView.setLongClickable(true);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
Log.i("hola","borrando la posiciĆ³n "+position);
JournalEntry removeMe = (JournalEntry)listView.getAdapter().getItem(position);
values.remove(removeMe);
datasource.deleteJournalEntry(removeMe);
//adapter.notifyDataSetChanged();
reloadMe();
return true;
}
});
}
public void reloadMe(){
//need to do this better... but meh.
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
protected ListView getListView() {
if (listView == null) {
listView = (ListView) findViewById(android.R.id.list);
}
return listView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
Updated Answer for updated code
instead of creating the same activity again, you should choose to set another new adapter object with the new values object.
public void reloadMe(){
//need to do this better... but meh.
//Intent intent = new Intent(this, MainActivity.class);
//this.startActivity(intent);
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
}
Perhaps, you are deleting from
datasource.deleteJournalEntry((JournalEntry) listView.getAdapter().getItem(position));
But you did not set "datasource" as the data source of the adapter. If you look carefully you did set the "values" list object-
listView.setAdapter(new ArrayAdapter<JournalEntry>(this, R.layout.list_item, R.id.lugares, values));
Perhaps you may need to also remove from the values list also.

How can i convert this code so i can get the row from list view

I want to be able to fetch a row from a list view and populate textViews in a different activity. I want to be able to do this onclick of an item with the list view..
public class CBFilter extends Activity {
ListView RecipeNames;
Cursor cursor;
SimpleCursorAdapter adapter;
CBDataBaseHelper data;
SQLiteDatabase data2;
TextView RecipeText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecipeNames = (ListView) findViewById(R.id.List1);
RecipeNames.setTextFilterEnabled(true);
RecipeText = (TextView) findViewById(R.id.recipeText);
adapter = new SimpleCursorAdapter (this, 0, cursor, null, null);
data = new CBDataBaseHelper(this);
data.open();
cursor = data.query();
startManagingCursor(cursor);
String[] from = {CBDataBaseHelper.KEY_NAME};
int[] to = { R.id.recipeText};
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
RecipeNames.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void CreateNew(View view){
Intent myIntent = new Intent(this, CBCreate.class);
startActivity(myIntent);
}
}
How can i convert this code in order to achieve the required functionality.. thanks Stefan
try like this
public void onListItemClick(ListView parent, View v, int position, long id) {
String string = from[position]); // this depends on your Adapter ...
Intent i = new Intent(CheckData.this,ShowData.class);
i.putExtra("SELECTED", string);
startActivity(i);
i got it from this link , it will be use full for you :
Use of SQLite

How to click a ListView item in Android

I'm trying to have another activity launch when a list item gets clicked. Below is my code:
public class AvoidForeclosure extends CustomListTitle {
/** Called when the activity is first created. */
private DbAdapter db;
private SimpleCursorAdapter clients;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = getListView();
setContentView(R.layout.main);
this.title.setText("Avoid Foreclosure");
db = new DbAdapter(this);
db.open();
fillData();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
int viewId = view.getId();
TextView theView = (TextView) findViewById(viewId);
String name = theView.getText().toString();
Cursor clientData = db.getClientByName(name);
Intent intent = new Intent();
intent.setClass(view.getContext(), CurrentMarketValue.class);
intent.putExtra("clientId", clientData.getInt(0));
startActivity(intent);
}
});
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = db.fetchAllClients();
startManagingCursor(c);
String[] from = new String[] { DbAdapter.KEY_NAME };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
clients = new SimpleCursorAdapter(this, R.layout.clientsrow, c, from, to);
setListAdapter(clients);
}
}
Yet when I click it, nothing happens at all. Any ideas?
Try switching this line:
ListView list = getListView();
to be after this one:
setContentView(R.layout.main);
Otherwise you'll be getting a handle to the ListActivity's default layout's ListView, rather than R.layout.main's listview (which is the one you really want).

Categories

Resources