I have an app that loads data from a sqllite database, then converts the data to appropriate formats so it could pass on the data to fragment tabs.
Everything works fine except for the images.
In the DB images are stored in full path, for example R.drawable.muntjakas and the images are available in the resource drawable folder.
The app pulls the data from the db and then converts it to int format so it could be passed on. Eclipse is not giving me any errors, but when the app loads images are not displayed. My xml files have the image id set up and displays the images if I assign the values manually for example
flag = new int[] { R.drawable.muntjakas,.... };
What's the problem?
fragmenttab1.java class that loads data from sql and converts it:
public class FragmentTab1 extends SherlockFragment {
ListView list;
ListViewAdapter adapter;
private static final String DB_NAME = "animalsDB.sqllite3";
private static final String TABLE_NAME = "animals";
private static final String ANIMAL_ID = "_id";
private static final String ANIMAL_NAME = "name";
private static final String ANIMAL_PIC = "pic";
public static final String[] ALL_KEYS = new String[] {ANIMAL_ID, ANIMAL_NAME,ANIMAL_PIC };
private SQLiteDatabase database;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,
false);
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(getActivity(), DB_NAME);
database = dbOpenHelper.openDataBase();
Cursor cursor = getAllRows();
ArrayList<String> nameArray = new ArrayList<String>();
ArrayList<Integer> picArray = new ArrayList<Integer>();
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
nameArray.add(cursor.getString(cursor.getColumnIndex(ANIMAL_NAME)));
picArray.add(cursor.getInt(cursor.getColumnIndex(ANIMAL_PIC)));
}
final String[] name = (String[]) nameArray.toArray(new String[nameArray.size()]);
final Integer[] pic = (Integer[]) picArray.toArray(new Integer[picArray.size()]);
final int[] flag = new int[pic.length];
for (int i = 0; i < pic.length; i++ ) {
flag[i] = pic[i];
}
// Locate the ListView in fragmenttab1.xml
list = (ListView) rootView.findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), name, flag);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Capture clicks on ListView items
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send single item click data to SingleItemView Class
Intent i = new Intent(getActivity(), SingleItemView.class);
// Pass all data country
i.putExtra("country", name);
// Pass all data flag
i.putExtra("flag", flag);
// Pass a single position
i.putExtra("position", position);
// Open SingleItemView.java Activity
startActivity(i);
}});
return rootView;
}
public Cursor getAllRows() {
String where = null;
Cursor c = database.query(true, TABLE_NAME, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
}
My listViewAdapter.java class that should load the data on the screen:
package kf.kaunozoo;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
String[] country;
int[] flag;
LayoutInflater inflater;
public ListViewAdapter(Context context, String[] country, int[] flag) {
this.context = context;
this.country = country;
this.flag = flag;
}
public int getCount() {
return country.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView txtcountry;
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Locate the TextViews in listview_item.xml
txtcountry = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
imgflag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set to the TextViews
txtcountry.setText(country[position]);
// Capture position and set to the ImageView
imgflag.setImageResource(flag[position]);
return itemView;
}
}
What am I doing wrong? All answers are appreciated
I have had this problem once in one of my apps, however, what I did was, I saved unique ids for each drawable in database as I had limited images. While displaying I wrote a small function where I used switch statement to check for each id from database and then loaded images accordingly in ImageView.
However, when you have lots of images, try to use below function, where you can provide image names dynamically from database.
// image from res/drawable
int resID = getResources().getIdentifier("your_image_name",
"drawable", getPackageName());
Also, you may try the solution given at this blog.
Related
I am creating a notepad programm where the user can add images to his notes . When he creates a new note and picks a few images their paths(uri) are stored in an arraylist which is converted to a xml tag (string type conversion) . When the user wants to open a created note the selected images from before are displayed in a gridview. However when i try to convert the string tag from the xml file to an arraylist so the imageadapter can put them in the grid view i am getting errors about conversion types .
edit the error i get is -java.lang.String cannot be cast to android.net.Uri-
The adapter is this
`private Context ctx;
private int pos;
private LayoutInflater inflater;
private ImageView ivGallery;
ArrayList<Uri> mArrayUri;
public GalleryAdapter(Context ctx, ArrayList<Uri> mArrayUri) {
this.ctx = ctx;
this.mArrayUri = mArrayUri;
}
#Override
public int getCount() {
return mArrayUri.size();
}
#Override
public Object getItem(int position) {
return mArrayUri.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pos = position;
inflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.gv_item, parent, false);
ivGallery = (ImageView) itemView.findViewById(R.id.ivGallery);
ivGallery.setImageURI(mArrayUri.get(position));
return itemView;
}`
and the way i try to convert them to array and show them in the grid view is this
` String Paths = userData.get(1);
ArrayList mArrayUri = new ArrayList<>(Arrays.asList(Paths.split(",")));
galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);
gvGallery.setAdapter(galleryAdapter);
gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
.getLayoutParams();
mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);
`
The xml creation code is this
` xmlSerializer.startDocument("UTF-8", true);
xmlSerializer.startTag(null, "userData");
xmlSerializer.startTag(null,"Text");
xmlSerializer.text(NoteText);
xmlSerializer.endTag(null, "Text");
xmlSerializer.startTag(null,"Image Paths");
xmlSerializer.text(String.valueOf(Gallery.ImagePaths));
xmlSerializer.endTag(null,"Image Paths" );
xmlSerializer.endTag(null, "userData");
xmlSerializer.endDocument();`
Your code is pretty good just make your array list type string and then take string value of uri.
In the .text(String.valueof(Imagepath)) use Uri.toString instead of String valueof
Example :
Uri uri;
String myUriString;
myUriString = uri.toString();
I'm having this issue with my android custom listview such that everytime i exit the activity (i.e. click the "back" button on emulator), then return back to the same activity that contains this custom listview, the listview adds an additional row to itself.
For example, originally it is:
item a
When I leave that activity and come back to it, the row doubles:
item a
item a
However, when i restart the emulator again, the custom listview goes back to the original number of data retrieved from sqlite.
How do I stop the rows from doubling themselves?
Here are my codes.
list.java:
//DATABASE
MyItems mi;
//For Items display - ArrayList
private ArrayList<SalesItemInformationLV> displayiteminfo;
/* new ArrayList<SalesItemInformationLV>(); */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_sale_item);
final float sellingpvalue = 13.5f;
final float costpvalue = 19.0f;
final String datesoldvalue = "9/9/1995";
final String staffdiscountvalue = "true";
mi = MyItems.getInstance();
displayiteminfo = mi.retrieveAllForlist(getApplicationContext());
//New array adapter for customised ArrayAdapter
final ArrayAdapter<SalesItemInformationLV> adapter = new itemArrayAdapter(this, 0, displayiteminfo);
//displayiteminfo - the ArrayList of item objects to display.
//Find the list view, bind it with custom adapter
final ListView listView = (ListView)findViewById(R.id.customListview);
listView.setAdapter(adapter);
// listView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 9));
//LONG PRESS CONTEXT MENU
registerForContextMenu(listView);
//Selecting the listview item!
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SalesItemInformationLV saleitem = displayiteminfo.get(position);
String namevalue = saleitem.getItemname();
int qtyvalue = saleitem.getItemquantity();
Intent myintent = new Intent(ListSaleItemActivity.this, ViewSaleDetails.class);
myintent.putExtra("itemname", namevalue);
myintent.putExtra("itemqty", qtyvalue);
myintent.putExtra("itemcp", costpvalue);
myintent.putExtra("itemsp", sellingpvalue);
myintent.putExtra("itemds", datesoldvalue);
myintent.putExtra("itemsstaffdis", staffdiscountvalue);
startActivity(myintent);
}
});
}
//custom Arrayadapter
class itemArrayAdapter extends ArrayAdapter<SalesItemInformationLV>
{
private Context context;
private List<SalesItemInformationLV> item;
//constructor, call on creation
public itemArrayAdapter(Context context, int resource, ArrayList<SalesItemInformationLV> objects) {
//chaining to "default constructor" of ArrayAdapter manually
super(context, resource, objects);
this.context = context;
this.item = objects;
}
//called to render the list
public View getView(int position, View convertView, ViewGroup parent)
{
//get the item we are displaying
SalesItemInformationLV iteminfo = item.get(position);
//get the inflater and inflate the xml layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_layout, null);
//Each component of the custom item_layout
TextView name = (TextView) view.findViewById(R.id.ItemNameSales);
TextView qty = (TextView)view.findViewById(R.id.ItemNameQty);
//set the name of item - access using an object!
name.setText(String.valueOf(iteminfo.getItemname()));
//set the quantity of item - access using an object!
qty.setText(String.valueOf(iteminfo.getItemquantity()));
return view;
//Now return to onCreate to use this cuztomized ArrayAdapter
}
}
Myitems.java:
public class MyItems extends Application {
//ID and contact information
private List<String> contactList;
private List<Integer> contactIdList;
private static MyItems ourInstance = new MyItems();
//Populate SaleItemInformationLV
private ArrayList<SalesItemInformationLV> displayiteminfo2 =
new ArrayList<SalesItemInformationLV>();
public MyItems()
{
contactList = new ArrayList<String>();
contactIdList = new ArrayList<Integer>();
}
public static MyItems getInstance(){
return ourInstance;
}
//RETRIEVE ALL ENTRIES
//LISTVIEW
public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context c)
{
Cursor myCursor;
String mystring = "";
MyDbAdapter db = new MyDbAdapter(c);
db.open();
//contactIdList.clear();
//contactList.clear();
myCursor = db.retrieveAllEntriesCursor();
if (myCursor !=null && myCursor.getCount()>0)
{
myCursor.moveToFirst();
do {
displayiteminfo2.add(new SalesItemInformationLV(myCursor.getString(db.COLUMN_NAME_ID), db.COLUMN_QTYSOLD_ID));
} while (myCursor.moveToNext());
}
db.close();
return displayiteminfo2;
}
MyItems is a (java-)singleton. Each times that you call public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context), you add objects in displayiteminfo2 et return this list.
If you call a second times retrieveAllForlist, you keep the same list with objects already in it and add more to it.
It's a bad pattern to return a private instance object in a function. Anything outside of your class can modify the list. Just create one for returning it.
public ArrayList<SalesItemInformationLV> retrieveAllForlist(Context c)
{
ArrayList<SalesItemInformationLV> items = new ArrayList<SalesItemInformationLV>();
Cursor myCursor;
String mystring = "";
MyDbAdapter db = new MyDbAdapter(c);
db.open();
//contactIdList.clear();
//contactList.clear();
myCursor = db.retrieveAllEntriesCursor();
if (myCursor != null && myCursor.getCount() > 0)
{
myCursor.moveToFirst();
do {
items.add(new SalesItemInformationLV(myCursor.getString(db.COLUMN_NAME_ID), db.COLUMN_QTYSOLD_ID));
} while (myCursor.moveToNext());
}
db.close();
return items;
}
It looks like MyItems is a singleton. Are you clearing the values before calling
mi.retrieveAllForlist(getApplicationContext())? If not, you may be doubling up the values when onCreate() is called after returning to the activity.
I have a simple list view where each item is a view that has a title, from an ArrayList of strings and button, so that each entry in the ArrayList creates a new list item.
I also have another ArrayList of corresponding primary keys, which I want to use to delete specific items from an SQLite database but which isn't used in the list view(I don't want to display the ID's, but the strings that poplulate the list might not necessarily be unique so I can't use them to delete).
I have a onClick listener and method in the getView method for the list view, so that when someone clicks the delete button, I know the position in the list that the button was pressed in, so hopefully, I can then call a delete method on the database using id[position], however, I think due to the list view itself being created after the activity it's inside of, it can't resolve the id array, so I can't call delete.
public class TodayListActivity extends AppCompatActivity {
private ArrayList<String> names = new ArrayList<>();
FoodDB Db = null;
int deleteId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todaylist);
ListView lv = (ListView) findViewById(R.id.today_meal_list);
Bundle a = this.getIntent().getExtras();
String[] id = a.getStringArray("idArray"); //used to delete
String[] mealNames = a.getStringArray("mealNamesArray"); //displayed
Collections.addAll(names, mealNames);
//call the list adapter to create views based off the array list 'names'
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, names));
}
protected class MyListAdapter extends ArrayAdapter<String> {
private int layout;
private MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder viewholder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
viewholder = new viewHolder();
viewholder.title = (TextView) convertView.findViewById(R.id.report_meal_name);
viewholder.delButton = (Button) convertView.findViewById(R.id.button_delete_meal);
viewholder.delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
//int deleteId derived from id[position]
deleteId = Integer.parseInt(id[position]);
idToDelete(deleteId);
//update the list view to exclude the deleted item
names.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(viewholder);
} else {
viewholder = (viewHolder) convertView.getTag();
}
//set string value for title
viewholder.title.setText(getItem(position));
viewholder.delButton.setTag(position);
return convertView;
}
}
public class viewHolder {
TextView title;
TextView delButton;
}
//delete from database
public void idToDelete(int DeleteId){
Db.deleteFoods(deleteId);
}
}
Any suggestions as to how or where to get either the position index out of the list view (to the activity, where the id array is) or get access to the id array inside the listview would be appreciated!
You can pass the id array to the MyListAdapter adapter, by changing this class' constructor to accept it as a parameter. Also, you are already passing the names list as a parameter, you should keep a reference to it so you can access it when the button is pressed.
Here is an example:
protected class MyListAdapter extends ArrayAdapter<String> {
private int layout;
private List<String> names;
private String[] ids;
private MyListAdapter(Context context, int resource, List<String> names, String[] ids) {
super(context, resource, names);
layout = resource;
this.names = names;
this.ids = ids;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
...
viewholder.delButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int deleteId = Integer.parseInt(ids[position]);// the "position" variable needs to be set to "final" in order to access it in here.
idToDelete(deleteId);
names.remove(position);
notifyDataSetChanged();
}
});
....
}
}
and here is how you can create an instance of this adapter:
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, names, id));
I have 2 arrays like:
Array 1 :
String[] web = {"Google Plus","Twitter","Windows","Bing","Itunes","Wordpress","Drupal"} ;
Array 2 :
String[] webimage = {"#drawable/img1","#drawable/img2","#drawable/img3","#drawable/img4","#drawable/img5","#drawable/img6","#drawable/img7"} ;
And I want to create ArrayAdapter that uses my Array1 for TextView and uses Array2 for icon of row
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.single_row,R.id.textView,array);
You could create a class to hold the String and the drawable resource
public class Item{
private final String text;
private final int icon;
public Item(final String text, final int icon){
this.text = text;
this.icon = icon;
}
public String getText(){
return text;
}
public Drawable getIcon(final Context context){
return context.getResources().getDrawable(this.icon)
}
}
and then create an array of Items
Item[] items = new Item[1];
item[0] = new Item("Google Plus",R.drawable.img1);
//...etc
create a custom ArrayAdapter for Item
public class ItemAdapter extends ArrayAdapter<Item> {
private Context context;
public ItemAdapter(Context context, Item[] items) {
super(context, 0, items);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Item item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_row, parent, false);
}
// Lookup view for data population
TextView tvText = (TextView) convertView.findViewById(R.id.tvText);
ImageView ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
// Populate the data into the template view using the data object
tvText.setText(item.getText());
ivIcon.setImageDrawable(item.getDrawable(this.context));
// Return the completed view to render on screen
return convertView;
}
}
In the example above R.layout.item_row is a layout that you would have to create containing a TextView with id tvText and an ImageView with id ivIcon.
Good morning, i'm retrieving some values from my MySQL database because i want to display them into a ListView with custom adapter. I have this code.
for(int i=0; i<jsonArray.length();i++) {
ogge = new Ogge();
json = jsonArray.getJSONObject(i);
ogge.title = json.getString("Title");
ogge.array = new String[] {json.getString("field1"), json.getString("field2"), json.getString("field3"), json.getString("field4"), json.getString("field5"), json.getString("field6")};
ogge.adapter = Ogge.MY_CUSTOM;
list.add(ogge);
}
This for is correct because the values are put in the array in Ogge class. This is the adapter
case Ogge.MY_CUSTOM:
view = inflater.inflate(R.layout.custom, null);
textView = (TextView)view.findViewById(R.id.textView1);
textView2 = (TextView)view.findViewById(R.id.textView2);
textView3 = (TextView)view.findViewById(R.id.textView3);
textView.setText(Html.fromHtml(ogge.title));
textView2.setText(MyJsonClass.DATABASE_FIELD[position]);
textView3.setText(ogge.array[position]);
break;
The problem is the follow: when i open my app i see only the first and the second value of ogge.array but i want to show all. If i make a for into the adapter to get the value from the array the values are all stored into the array so the array is correct but, then, why i show only the first two values and not all?
Adapter full code
public MyCustomAdapter(Context context, int resource, ArrayList<Ogge> list) {
super(context, resource, list);
// TODO Auto-generated constructor stub
this.context = context;
this.list = list;
}
#SuppressLint("CutPasteId")
#Override
public View getView(int position, View view, ViewGroup parent) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final Ogge ogge = list.get(position);
switch(ogge.adapter) {
case Ogge.MY_CUSTOM:
view = inflater.inflate(R.layout.custom, null);
textView = (TextView)view.findViewById(R.id.textView1);
textView2 = (TextView)view.findViewById(R.id.textView2);
textView3 = (TextView)view.findViewById(R.id.textView3);
textView.setText(Html.fromHtml(ogge.title));
textView2.setText(MyJsonClass.DATABASE_FIELD[position]);
textView3.setText(ogge.array[position]);
break;
}
return view;
}
#Override
public boolean isEnabled(int position) {
return false;
}
}