Gallery widget using Lazy List - android

For this app I'm trying to write, the idea is that I'm going to host some pictures online and save the individual urls into a sqlite database. Then I will extract each url from the database and download the picture to be shown in a gallery widget. I read about Lazy List (kudos for the great work!) but I'm having problems implementing it. I have tried to modify the coding from Lazy List but it doesnt seem to work. I'm not sure if there is an error in my app or have I modified the Lazy List wrongly. Any help is greatly appreciated and thank you in advance! =)
Code for my app:
public class ResultDetails extends ListActivity {
protected int foodId;
protected String pic1, pic2, pic3, pic4, pic5;
LazyAdapter adapter1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_details);
foodId = getIntent().getIntExtra("FOOD_ID", 0);
SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT _id, pic1, pic2, pic3, pic4, pic5 FROM database WHERE _id = ?", new String[]{""+foodId});
pic1 = cursor.getString(cursor.getColumnIndex("pic1"));
pic2 = cursor.getString(cursor.getColumnIndex("pic2"));
pic3 = cursor.getString(cursor.getColumnIndex("pic3"));
pic4 = cursor.getString(cursor.getColumnIndex("pic4"));
pic5 = cursor.getString(cursor.getColumnIndex("pic5"));
String[] mStrings={
pic1,
pic2,
pic3,
pic4,
pic5};
Gallery g = (Gallery) findViewById(R.id.photobar);
adapter1=new LazyAdapter(this, mStrings);
g.setAdapter(adapter1);
}
I have modified the LazyAdapter as such:
public class LazyAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Activity activity;
private String[] data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, String[] d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public LazyAdapter(Context c) {
mContext = c;
TypedArray b = c.obtainStyledAttributes(R.styleable.Theme);
mGalleryItemBackground = b.getResourceId(
R.styleable.Theme_android_galleryItemBackground,
0);
b.recycle();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView vi = new ImageView(mContext);
imageLoader.DisplayImage(data[position], vi);
vi.setLayoutParams(new Gallery.LayoutParams(150, 100));
vi.setScaleType(ImageView.ScaleType.FIT_XY);
return vi;
}
}

With the help of Fedor, I figured out what was wrong with the implementation. Whether for list or gallery, there is no need to change the LazyAdapter! Just use the adapter as it is and use the following code in your app to load the pictures:
g = (Gallery) findViewById(R.id.photobar);
adapter1=new LazyAdapter(this, mStrings);
g.setAdapter(adapter1);}
I noticed that there are a lot of examples on using LazyList for lists and not galleries. To help those who want to use it for galleries, here is an example of the implementation:
public class ResultDetails extends ListActivity {
protected int foodId;
protected String pic1, pic2, pic3, pic4, pic5;
LazyAdapter adapter1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_details);
foodId = getIntent().getIntExtra("FOOD_ID", 0);
SQLiteDatabase db = (new DatabaseHelper(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT _id, pic1, pic2, pic3, pic4, pic5 FROM database WHERE _id = ?", new String[]{""+foodId});
pic1 = cursor.getString(cursor.getColumnIndex("pic1"));
pic2 = cursor.getString(cursor.getColumnIndex("pic2"));
pic3 = cursor.getString(cursor.getColumnIndex("pic3"));
pic4 = cursor.getString(cursor.getColumnIndex("pic4"));
pic5 = cursor.getString(cursor.getColumnIndex("pic5"));
String[] mStrings={pic1, pic2, pic3, pic4, pic5};
g = (Gallery) findViewById(R.id.photobar);
adapter1=new LazyAdapter(this, mStrings);
g.setAdapter(adapter1);}

Related

Retrieve image names from sqlite

I have a database and I have two columns
Name of the first column: Img
Name of the second column: Name
I want to show them in Listview
There is no problem displaying names
But there is a problem with displaying pictures What is the solution?
ِAdbter Listview
public class adbter_listview extends ArrayAdapter<String> {
Activity activity;
ArrayList<Integer> icons;
ArrayList<String> name;
public adbter_listview(Activity activity, ArrayList<Integer> icons, ArrayList<String> name) {
super(activity, R.layout.custom_listview, name);
this.activity = activity;
this.icons = icons;
this.name = name;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
View v = inflater.inflate(R.layout.custom_listview, parent, false);
ImageView iv = (ImageView) v.findViewById(R.id.imageView);
TextView tv = (TextView) v.findViewById(R.id.textView);
iv.setImageResource(icons.get(position));
tv.setText(name.get(position));
return v;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView con;
ArrayList<String> icons_name = new ArrayList<>();
ArrayList<Integer> icons = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = (ListView) findViewById(R.id.con);
db connect = new db(MainActivity.this);
SQLiteDatabase read = connect.getReadableDatabase();
Cursor save = read.rawQuery("select image from game",null);
save.moveToFirst();
while(save.isAfterLast()==false)
{
icons_name.add(save.getString(0));
icons.add(R.drawable.user);
save.moveToNext();
}
adbter_listview adb = new adbter_listview(MainActivity.this,icons,name);
con.setAdapter(adb);
}
}
please help me
Get int id of drawable using this line,
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
In your case
nameOfDrawable = save.getString(0); I guess
then add into icons arrayList,
icons.add(drawableResourceId);
Hope this will work.
Instead of this
icons.add(R.drawable.user);
Use
icons.add(Integer.parseInt(save.getString(1)));
in adapter it should work only if the images are from drawables folder and use it like
R.drawable.icons.get(position)
But first remove the database call from the oncreate mainThread call to a different thread. Either create a new Thread or use asynctask or use loaders. Don't make a sqlitedatabase call in mainthread.

custom adapter isn't showing any items

This is a follow on from an earlier question: ImageButton within row of ListView android not working
But after suggestions from SO gurus it has been suggested I post a new question.
The issue is that I have a custom adapter that is not showing any data. I have looked into other questions, but it didn't provide a solution.
In my Main Activity I have a couple of buttons, one of them: ToDo, should create a row that displays data from a SQLite database, and depending on some factors (dates mainly), it shows a type of traffic light that is stored as a drawable.
Part of the Items in this Row is an Image Button that I want the user to be able to click and the image should change. The user should be able also to click on the actual row and a new activity starts.
The issue I have is that NO DATA is being displayed.
So, here is my code:
public class MainActivity extends Activity {
// definitions etc ...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// definitions etc ...
}
public void ToDo(View v){ // the user has clicked in the ToDo button
IgroDatabaseHelper helper = new IgroDatabaseHelper(getBaseContext()); // create instance of SQLIte database
numRows = helper.NumEntries("ToDo"); // Get the number of rows in table
int i = 1;
ArrayList<RowItem> rowItems = new ArrayList<>();
RowItem myItem1;
while (i <= numRows){
// get items from database
// depending on value select different drawable
// put data into List Array of RowItem
myItem1 = new RowItem(TheWhat, R.drawable.teamworka, R.drawable.redtrafficlight, R.drawable.checkbox, TheWhenBy);
rowItems.add(myItem1);
//
i = i+ 1;
}
ListView yourListView = (ListView) findViewById(R.id.list);
CustomListViewAdapter customAdapter = new CustomListViewAdapter(this, R.layout.todo_row, rowItems);
yourListView.setAdapter(customAdapter);
}
The CustomListViewAdapter looks like this:
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
ArrayList<RowItem> _rowItems;
public CustomListViewAdapter(Context context, int resourceId,
ArrayList<RowItem> rowItems) {
super(context, resourceId);
this.context = context;
_rowItems = rowItems;
System.out.println("I am in the custom Adapter class "+ _rowItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
System.out.println("This is the get view");
View row = convertView;
RowItem item = _rowItems.get(position);
// you can now get your string and drawable from the item
// which you can use however you want in your list
String columnName = item.getColumnName();
int drawable = item.getDrawable();
if (row == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = mInflater.inflate(R.layout.todo_row, parent, false);
}
ImageButton chkDone = (ImageButton) row.findViewById(R.id.chkDone);
chkDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
System.out.println("I am in position "+ position);
}
});
return row;
}
}
The RowItem Class looks like:
public class RowItem {
private String _heading;
private int _icon;
private int _lights;
private int _chkdone;
private String _date;
public RowItem(String heading, int icon, int lights, int chkDone, String date) {
_heading = heading;
_icon = icon;
_lights = lights;
_chkdone = chkDone;
_date = date;
System.out.println("adding stuff to my rows");
System.out.println("my column Name is " + heading);
System.out.println("My drawable int is "+ icon);
}
public String getColumnName() {
System.out.println("column Names is "+ _heading);
return _heading;
}
public int getDrawable() {
return _icon;
}
public int getLights(){
return _lights;
}
public int getchkDone(){
return _chkdone;
}
public String getDate(){
return _date;
}
}
I am obviously missing something, as I mentioned earlier, no data gets shown. I know that there are 2 row items that get passed to the CustomListViewAdapter. But I also know that the View getView inside the CustomListViewAdapter does not actually get called.
I hope I have put enough information/code, but if you feel I need to explain something further, please say.
Thanking all very much in advance!
I don't see a getCount() method. You should be overriding it like this:
#Override
public int getCount() {
return _rowItems.getCount();
}
Alternatively, calling super(context, resourceId, rowItems); should also fix it.
Your ListView thinks there are no items to display. If you are using your own array, you must override the getCount() method to indicate the number of items you want to display.

Android notifyDatasetChange with SQLite cursor how to?

So I have 2 activities.
The first (ActivityOne) displays a listview with data from SQLite cursor, and a button.
On click of that button, I want to add an item to the listview, so I display the second activity (ActivityTwo), that contains a number of editTexts and a save Button, that does the saving in the Database.
But what I want is:
after saving the new item to the DB, the ActivityTwo should close and the ActivityOne should be displayed with the refreshed content from the DB
.
This seems a reasonable workflow. How do I achieve it?
Code for ActivityOne:
public class ActivityOne extends Activity {
private ArrayList<String> idclient = new ArrayList<String>();
private ArrayList<String> numeclient = new ArrayList<String>();
private ArrayList<String> tipclient = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView mylist = (ListView) findViewById(R.id.lv_clienti);
LoadList();
Button btnex = (Button) findViewById(R.id.btnNewCli);
btnex.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View aView)
{
Toast.makeText(getApplicationContext(), "Add new client... " , Toast.LENGTH_SHORT).show();
Intent toAnotherActivity = new Intent(aView.getContext(), NewClientActivity.class);
startActivity(toAnotherActivity);
}
}
);
}
public void LoadList(){
SQLiteDatabase db = new myDbHelper(getApplicationContext()).getWritableDatabase();
Cursor mCursor = db.rawQuery("select idclient,nameclient,typeclient from clienti order by numeclient" , null);
idclient.clear();
numeclient.clear();
tipclient.clear();
if (mCursor.moveToFirst()) {
do {
idclient.add(Integer.toString(mCursor.getInt(0)));
nameclient.add(mCursor.getString(1));
typeclient.add(mCursor.getString(2));
} while (mCursor.moveToNext());
}
DisplayClientiAdapter disadpt = new DisplayClientiAdapter(ClientiActivity.this,idclient,nameclient, typeclient);
ListView lv = (ListView) findViewById(R.id.lv_clienti);
lv.setAdapter(disadpt);
mCursor.close();
db.close();
}
}
And in the ActivityTwo, I have in a button click:
db.execSQL("insert into clients (idclient, nameclient,typeclient,...");
DisplayClientiAdapter da = new DisplayClientiAdapter(getApplicationContext());
da.notifyDataSetChanged();
finish();
Also the displayAdapter is something like:
public class DisplayClientiAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> idclient;
private ArrayList<String> numeclient;
private ArrayList<String> tipclient;
public DisplayClientiAdapter(Context c){
this.mContext = c;
}
public DisplayClientiAdapter(Context c, ArrayList<String> idclient, ArrayList<String> numeclient, ArrayList<String> tipclient) {
this.mContext = c;
this.idclient = idclient;
this.numeclient = numeclient;
this.tipclient = tipclient;
}
public int getCount() {
return idclient.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.clienti_item, null);
mHolder = new Holder();
mHolder.txt_idclient = (TextView) child.findViewById(R.id.tv_cl_id);
mHolder.txt_numeclient = (TextView) child.findViewById(R.id.tv_cl_nume);
mHolder.txt_tipclient = (TextView) child.findViewById(R.id.tv_cl_tip);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_idclient.setText(idclient.get(pos));
mHolder.txt_numeclient.setText(numeclient.get(pos));
mHolder.txt_tipclient.setText(tipclient.get(pos));
return child;
}
public class Holder {
TextView txt_idclient;
TextView txt_numeclient;
TextView txt_tipclient;
}
Of course it does not work like this. The list is not refreshed... I assume it has to do with the displayAdapter !?!?!
I cannot call the LoadList method since it is static or something like that...
Please help.
Thank you
Its not a problem with your adapter. You have to call Loadlist() in onresume method instead of oncreate method in ActivityOne. It will work then.
First of all, have a look at this two articles:
http://www.doubleencore.com/2013/05/layout-inflation-as-intended/
http://www.doubleencore.com/2013/06/context/
You shouldn't inflate your views with null in your inflate method if you have parent view available.
Also, using application context for inflating may cause strange behaviour, as it may not use correct theme you may've set in app manifest for your Activity.
On the other hand - why don't you use CursorAdapter instead of BaseAdapter?
The problem with your adapter is, that you don't set the data in it! :)
///EDIT:
I checked the wrong activity - why do you create second adapter in there?
The easiest solution would be to move the LoadList() to onStart.
If you want to do it right, you should use ContentObserver and (probably) CursorAdapter.

Cannot display image on listview using simple cursor adapter

I had populated a listview using simplecursoradapter. However, I want to add images, wherein if the answer is correct it should display check on the right and if null or incorrect it should display an x-mark. It does not display anything but there is no error. Here is my activity code:
public class Results extends ListActivity{
DBAdapter db = new DBAdapter(this);
private Cursor mCursor;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultslist);
db.open();
fillData();
db.close();
}
private void fillData() {
mCursor = db.getAllInfo();
startManagingCursor(mCursor);
String[] from = new String[]{DBAdapter.KEY_QUESTIONS, DBAdapter.KEY_CORRECTANSWERS, DBAdapter.KEY_YOURANSWERS};
int[] to = new int[]{R.id.textViewquestionresults, R.id.textViewcorrectansresults, R.id.textViewyouranswerresults};
SimpleCursorAdapter c=
new SimpleCursorAdapter(this, R.layout.rowresults, mCursor, from, to);
setListAdapter(c);
}
private class c extends SimpleCursorAdapter{
Context lcontext;
public c(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
lcontext = context;
}
#Override
public View getView(final int pos, View v, ViewGroup parent) {
v = super.getView(pos, v, parent);
final ImageView iv = (ImageView) v.findViewById(R.id.imageViewresults);
final TextView tvQuestion = (TextView) v.findViewById(R.id.textViewQuestion);
final TextView tvCorrectAns = (TextView) v.findViewById(R.id.textViewcorrectansresults);
final TextView tvYourAns = (TextView) v.findViewById(R.id.textViewyouranswerresults);
if(tvYourAns.equals(tvCorrectAns)){
iv.setImageResource(R.drawable.greencheckmark);
}else{
iv.setImageResource(R.drawable.redxmark);
}
return v;
}
}
}
When extending SimpleCursorAdapter, you shouldn't override getView().
You should override newView() and bindView() instead.
In newView() inflate your layout and initialize your views.
In bindView() set your views' values.

Custom Spinner Crashing

I asked a question on here about a week or so ago about a custom spinner and got led to this guide. http://app-solut.com/blog/2011/03/using-custom-layouts-for-spinner-or-listview-entries-in-android/
I followed it and I've tried adapting it to work with my code and pull the results from a database onto the spinner but it keeps crashing.
This is the code for the spinner.
public class EditTeam extends Activity {
private final List<SpinnerEntry> spinnerContent = new LinkedList<SpinnerEntry>();
private Spinner D1Spinner;
private final ETSpinnerAdapter D1Adapter = new ETSpinnerAdapter(spinnerContent, this);
DataBaseHelper myDbHelper = new DataBaseHelper(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editteam);
myDbHelper = new DataBaseHelper(this);
myDbHelper.openDataBase();
fillSpinner();
}
private void fillSpinner() {
Cursor c = myDbHelper.FetchDrivers();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"FirstName", "LastName"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
spinnerContent.add(new SpinnerEntry(1, null, "Test"));
//adapter.setDropDownViewResource( R.layout.spinner_entry_with_icon );
D1Spinner = (Spinner) findViewById(R.id.spr_Driver1);
D1Spinner.setAdapter((SpinnerAdapter) D1Adapter);
}
}
And I am using the two classes from that contacts example which are un-modified at the moment.
As you can see I'm trying to just manually add one item at the moment but it just crashes when you load it.
This seems to be the breaking point?
05-25 15:17:34.773: E/AndroidRuntime(241): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.f1manager.android/com.f1manager.android.EditTeam}: java.lang.ClassCastException: com.f1manager.android.ETSpinnerAdapter
Any ideas would be great.
Thanks.
ETSpinnerAdapter Code (Unmodified from the original code in the example):
public class ETSpinnerAdapter {
private final List<SpinnerEntry> content;
private final Activity activity;
public ETSpinnerAdapter(List<SpinnerEntry> content, Activity activity) {
super();
this.content = content;
this.activity = activity;
}
public int getCount() {
return content.size();
}
public SpinnerEntry getItem(int position) {
return content.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final LayoutInflater inflater = activity.getLayoutInflater();
final View spinnerEntry = inflater.inflate(
R.layout.spinner_entry_with_icon, null); // initialize the layout from xml
final TextView contactName = (TextView) spinnerEntry
.findViewById(R.id.spinnerEntryContactName);
final ImageView contactImage = (ImageView) spinnerEntry
.findViewById(R.id.spinnerEntryContactPhoto);
final SpinnerEntry currentEntry = content.get(position);
contactName.setText(currentEntry.getContactName());
//contactImage.setImageBitmap(currentEntry.getContactPhoto());
return spinnerEntry;
}
}
It would seem like your ETSpinnerAdapter is not a SpinnerAdapter as your are getting a class cast exceptin. Maybe you can post your code for the ETSpinnerAdapter?

Categories

Resources