I am a beginner programmer so please bear with me. I have been able to create a listview with images in it and thought I could modify it to add a checkbox. However, this setup does not work. Any suggestions to how I may fix my code to create a listview with both an image and checkbox?
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CheckboxList extends ListActivity{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static CheckBox box0,box1,box2,box3;
static final String[] title = new String[] {
"Box 1", "Box 2",
"Box 3 ","Box 4" };
static final CheckBox[] boxes= new CheckBox[] {box0,box1,box2,box3};
private Integer[] imgid = {
R.drawable.magnum,R.drawable.mg,R.drawable.mk,
R.drawable.mk46};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],boxes[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.check_list,
R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position,
long id) {
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
private class RowData {
protected int mId;
protected String mTitle;
protected CheckBox mCBox;
RowData(int id,String title,CheckBox cbox){
mId=id;
mTitle = title;
mCBox=cbox;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mCBox;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
CheckBox box = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.check_list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
box = holder.getcheckbox();
box.setChecked(false);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private CheckBox cbox = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public CheckBox getcheckbox() {
if(null == cbox){
cbox = (CheckBox) mRow.findViewById(R.id.checkBox);
}
return cbox;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
} }
Look at this links.it may helpfull......
http://www.vogella.com/articles/AndroidListView/article.html
CustomListview With Images and Checkboxes Example
Related
Hello friend i am new in android i want to know how to save ToggleButton state in custom ArrayAdapter i create custom ListView with help of ArrayAdapter now i want how save its state in Adapter here is my code pleae explain what logic used to achieve this goal i am on beginner level don't how to achieve this goal?
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter < String > {
private ALLVERSE activity;
private List < String > versenumber;
private List < String > verseid;
private List < String > verselist;
private List < String > refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean save;
public static final String MyPREFERENCES = "MyPrefs";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List < String > versenumber, List < String > verselist, List < String > refernce, List < String > verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid = verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
holder.bookmark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
} else {
}
}
});
//mDBHelper = new DatabaseHelper(activity);
//mDb = mDBHelper.getWritableDatabase();
//ContentValues contentValues=new ContentValues();
//contentValues.put("id",verseid.get(position));
//contentValues.put("bookname",refernce.get(position));
//contentValues.put("versenumber",versenumber.get(position));
//contentValues.put("verse",verselist.get(position));
//long check=mDb.insert("favourite",null,contentValues);
//Log.d("MY_TAG","DB IS NOW "+check);
//Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
/* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
// long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
//Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
}
});*/
return convertView;
}
static class ViewHolder {
private ToggleButton favourite;
private TextView versenumber;
private TextView verselist;
private CircleMenu circleMenu;
private ImageView share;
//toggle button
public ToggleButton bookmark;
private boolean defaultvalue;
private ALLVERSE activity;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
bookmark = (ToggleButton) v.findViewById(R.id.adbookmark);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
}
}
}
Ideally an adapter is an object to adapt a particular dataset to render a view within a listview. So you should have a data structure (class object) for every row visible in that list view and put it in an array list. Based on the position in getView method, retrieve the data for the row and initialize views from this data. Now this data set can be saved on server or in local memory in any format preferably in JSON and can be retrieved back in future.
I want to know how to pass the argument to custom adapter . I'm trying to implement a YouTube video list using listview + baseadapter. I'm not sure how to populate properly the listview using the baseadapter
My error is:
Error:(67, 39) error: constructor VideoListAdapter in class YouTubeVideo.VideoListAdapter cannot be applied to given types;
required: Context
found: YouTubeVideo,int,List<Video>
reason: actual and formal argument lists differ in length
Here is my code:
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.google.android.youtube.player.YouTubeApiServiceUtil;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.fabric.sdk.android.Fabric;
public class YouTubeVideo extends AppCompatActivity {
public static List<Video> MyVideo = new ArrayList<Video>();
public static Map<String, Video> Video_Map = new HashMap<>();
private static void addItem(final Video currentVideo) {
MyVideo.add(currentVideo);
Video_Map.put(currentVideo.getVideoId(), currentVideo);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_you_tube_video);
Fabric.with(this, new Crashlytics());
//Check for any issues
final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(this);
if (result != YouTubeInitializationResult.SUCCESS) {
//If there are any issues we can show an error dialog.
result.getErrorDialog(this, 0).show();
}
populateVideoList();
populateListView();
}
private void populateVideoList() {
addItem(new Video("tttG6SdnCd4", "Open in the YouTube App"));
addItem(new Video("x-hH_Txxzls", "Open in the YouTube App in fullscreen"));
addItem(new Video("TTh_qYMzSZk", "Open in the Standalone player in fullscreen"));
addItem(new Video("tttG6SdnCd4", "Open in the Standalone player in \"Light Box\" mode"));
addItem(new Video("x-hH_Txxzls", "Open in the YouTubeFragment"));
}
private void populateListView() {
ArrayAdapter<Video> adapter = new VideoListAdapter(YouTubeVideo.this, R.layout.video_view, MyVideo);
ListView list = (ListView) findViewById(R.id.videoListView);
list.setAdapter(adapter);
}
//------------------------------------------------------------------------------------------------------------------- 12/05/16
private class VideoListAdapter extends BaseAdapter implements YouTubeThumbnailView.OnInitializedListener {
private Context mContext;
private Map<View, YouTubeThumbnailLoader> mLoaders;
public VideoListAdapter(final Context context) {
mContext = context;
mLoaders = new HashMap<>();
}
#Override
public int getCount() {
return MyVideo.size();
}
#Override
public Object getItem(int position) {
return MyVideo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
//------------------------------------------------------------------------------------------------------------------- 13/05/16
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View videoRow = convertView;
VideoHolder holder;
final Video currentVideo = MyVideo.get(position);
if (videoRow == null) {
//Create the row
final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
videoRow = inflater.inflate(R.layout.video_view, parent, false);
//Create the video holder
holder = new VideoHolder();
//Set the title
holder.title = (TextView) videoRow.findViewById(R.id.textView_title);
holder.title.setText(currentVideo.getVideoTitle());
//Initialise the thumbnail
holder.thumb = (YouTubeThumbnailView) videoRow.findViewById(R.id.imageView_thumbnail);
holder.thumb.setTag(currentVideo.getVideoId());
holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this);
videoRow.setTag(holder);
} else {
//Create it again
holder = (VideoHolder) videoRow.getTag();
final YouTubeThumbnailLoader loader = mLoaders.get(holder.thumb);
//Set the title
if (currentVideo != null) {
holder.title.setText(currentVideo.getVideoTitle());
if (loader == null) {
//Loader is currently initialising
holder.thumb.setTag(currentVideo.getVideoId());
} else {
//The loader is already initialised
loader.setVideo(currentVideo.getVideoId());
}
}
}
return videoRow;
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
mLoaders.put(view, loader);
loader.setVideo((String) view.getTag());
}
#Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
final String errorMessage = errorReason.toString();
Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show();
}
private class VideoHolder {
YouTubeThumbnailView thumb;
TextView title;
}
}
}
I can not find a constructor in VideoListAdapter with three parameters , I think you missed the following constructor in VideoListAdapter
public VideoListAdapter (Context context, int layoutResourceId,
List<Video> myvideos) {
super(activity, layoutResourceId, myvideos);
mContext = context;
}
or replace
ArrayAdapter<Video> adapter = new VideoListAdapter(YouTubeVideo.this, R.layout.video_view, MyVideo);
with
VideoListAdapter adapter = new VideoListAdapter(YouTubeVideo.this);
It is really easy to resolve it;
public VideoListAdapter (Context context, int layoutId, List lists) {
super(context);
mContext = context;
this.layoutId = layoutId;
this.lists = lists;
}
good luck!
I want to build an app that displays images in a gridview by using the picasso library. This is my code. The image didn't load. In Picasso log, after request it always error to load. Can you help me ?Please Thank you
UPDATE
CustomGridViewAdapter.Java
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Nicky-PC on 4/9/2016.
*/
public class CustomGridViewAdapter extends ArrayAdapter<gridItem> {
Context context;
int layoutResourceId;
ArrayList<gridItem> data = new ArrayList<gridItem>();
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<gridItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void setGridData(ArrayList<gridItem> mGridData)
{
this.data=mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.tvItem);
holder.imageItem = (ImageView) row.findViewById(R.id.imageView);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
gridItem item = data.get(position);
holder.txtTitle.setText(item.getBarang());
Picasso.with(context).
load(item.getImageUrl()).
into(holder.imageItem);
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
MainActivity.Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
JSONParser jParser= new JSONParser();
ArrayList<HashMap<String, String>> nameList;
JSONArray names=null;
GridView data;
private static final String URL_TEST_BARANG= "http://lomapod.azurewebsites.net/readBarang.php";
private static final String TAG_PESAN = "message";
private static final String TAG_HASIL = "result";
private static final String TAG_BARANG = "nama_barang";
private static final String TAG_IMAGE= "image_name";
ImageView imageview;
CustomGridViewAdapter mGridAdapter;
ArrayList<gridItem> mGridData;
public MainActivity()
{}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=(GridView) findViewById(R.id.lvSeller);
nameList= new ArrayList<HashMap<String, String>>();
imageview =(ImageView) findViewById(R.id.imageView);
mGridData=new ArrayList<>();
mGridAdapter=new CustomGridViewAdapter(this,R.layout.grid_item,mGridData);
new AmbilDataJson("1").execute();
}
public class AmbilDataJson extends AsyncTask<String,String,String> {
String id;
int sukses=0;
public AmbilDataJson(String id) {
this.id=id;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id_penjual",id));
try
{
JSONObject json = jParser.makeHttpRequest(URL_TEST_BARANG, "GET", params);
gridItem item=null;
if(json != null)
{
sukses = json.getInt(TAG_PESAN);
if(sukses == 0)
{
nameList = new ArrayList<HashMap<String,String>>();
Log.d("Semua Nama: ", json.toString());
names = json.getJSONArray(TAG_HASIL);
for(int i = 0; i < names.length();i++)
{
JSONObject c = names.getJSONObject(i);
String barang = c.getString(TAG_BARANG);
String image = "lomapod.esy.es/assets/"+c.getString(TAG_IMAGE);
item = new gridItem();
item.setBarang(barang);
item.setImageUrl(image);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_BARANG,barang);
map.put(TAG_IMAGE,image);
nameList.add(map);
mGridData.add(item);
}
}
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(sukses == 0)
{
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
if(mGridData.size()>0)
{
mGridAdapter.setGridData(mGridData);
data.setAdapter(adapter);
}
else
Toast.makeText(getApplicationContext(),"Error - No Data Available", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,"Failed",Toast.LENGTH_LONG);
}
}
}
}
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
mGridAdapter.setGridData(mGridData);
data.setAdapter(adapter);
mGridData is empty, you have not added data for this list. And you don't not need initialize new adapter.
You didn't add values to mGridData thats why its not showing anything. Before passing values to adapter check the size of mGridData.
`#Override
protected void onPostExecute(String s) {
if(sukses == 0)
{
CustomGridViewAdapter adapter = new CustomGridViewAdapter(
MainActivity.this,R.layout.grid_item,mGridData);
if(mGridData.size()>0)
{
mGridAdapter.setGridData(mGridData);
data.setAdapter(adapter);
}
else
Toast.makeText(getApplicationContext(),"Error - No Data Available", Toast.LENGTH_SHORT).show();
}`
The reason why your GridView is not showing anything is because the ArrayList<gridItem> you are passing to your CustomGridViewAdapter is empty.
You have initialized your ArrayList<gridItem> in MainActivity but never added a any item to the list.
There are some things you need to change in your program to make it work.
Since you are added server response in the ArrayList<HashMap<String, String>> nameList, you need to pass that ArrayList to your Adapter, and then use that ArrayList's items to bind in your grid's textView and imageView.
In onPostExecute(), initialize your adapter as,
CustomGridViewAdapter adapter = new CustomGridViewAdapter(MainActivity.this,R.layout.grid_item, nameList);
data.setAdapter(adapter);
//you don't even need to call mGridAdapter.setGridData(mGridData) method.
Also change your Adapter's constructor as,
public CustomGridViewAdapter(Context context, int layoutResourceId,
ArrayList<HashMap<String, String>> nameList) {
....
}
I am making a video gallery trying to get videos files from a specific directory i am getting an error parameters cannot be resolved to a variable here is my code of the gallery activity.I am a newbie to java and my English is not that good.Thanks in advance for helping.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity implements OnItemClickListener {
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String selection=MediaStore.Video.Media.DATA +" like?";
String[] selectionArgs=new String[]{"/storage/sdcard0/phd"};
cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
parameters, selection, selectionArgs, MediaStore.Video.Media.DATE_TAKEN + " DESC");
ListView listView = (ListView) this.findViewById(R.id.ListView);
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
MediaStore.Video.Thumbnails.VIDEO_ID };
String[] mediaColumns = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA, MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.MIME_TYPE };
cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
mediaColumns, null, null, null);
ArrayList<VideoViewInfo> videoRows = new ArrayList<VideoViewInfo>();
if (cursor.moveToFirst()) {
do {
VideoViewInfo newVVI = new VideoViewInfo();
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media._ID));
Cursor thumbCursor = managedQuery(
MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
+ "=" + id, null, null);
if (thumbCursor.moveToFirst()) {
newVVI.thumbPath = thumbCursor.getString(thumbCursor
.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
Log.v("", newVVI.thumbPath);
}
newVVI.filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
newVVI.title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
Log.v("", newVVI.title);
newVVI.mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
Log.v("", newVVI.mimeType);
videoRows.add(newVVI);
} while (cursor.moveToNext());
}
listView.setAdapter(new VideoGalleryAdapter(this, videoRows));
listView.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
if (cursor.moveToPosition(position)) {
int fileColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
int mimeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
String videoFilePath = cursor.getString(fileColumn);
String mimeType = cursor.getString(mimeColumn);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File newFile = new File(videoFilePath);
intent.setDataAndType(Uri.fromFile(newFile), mimeType);
startActivity(intent);
}
}
}
class VideoViewInfo {
String filePath;
String mimeType;
String thumbPath;
String title;
}
class VideoGalleryAdapter extends BaseAdapter {
private Context context;
private List<VideoViewInfo> videoItems;
LayoutInflater inflater;
public VideoGalleryAdapter(Context _context,
ArrayList<VideoViewInfo> _items) {
context = _context;
videoItems = _items;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return videoItems.size();
}
public Object getItem(int position) {
return videoItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View videoRow = inflater.inflate(R.layout.row, null);
ImageView videoThumb = (ImageView) videoRow
.findViewById(R.id.ImageView);
if (videoItems.get(position).thumbPath != null) {
videoThumb.setImageURI(Uri
.parse(videoItems.get(position).thumbPath));
}
TextView videoTitle = (TextView) videoRow
.findViewById(R.id.TextView);
videoTitle.setText(videoItems.get(position).title);
return videoRow;
}
}
I am getting two errors when trying to get pictures to put in my gridview
ImageItem item = data.get(position);
get's me error:
Error:(42, 34) error: incompatible types
required: ImageItem
found: Object
And
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
get's me error:
Error:(29, 60) error: cannot find symbol variable array
full code:
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.GridView;
public class MainActivity extends Activity {
private GridView gridView;
private GridViewAdapter customGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView);
customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(customGridAdapter);
}
private ArrayList getData() {
final ArrayList imageItems = new ArrayList();
// retrieve String drawable array
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
GridViewAdapter.Java
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GridViewAdapter extends ArrayAdapter {
private Context context;
private int layoutResourceId;
private ArrayList data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
//holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
//holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
//TextView imageTitle;
ImageView image;
}
}
ImageItem.java
import android.graphics.Bitmap;
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap image, String title) {
super();
this.image = image;
this.title = title;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
I know this post is from a while ago, but just in case someone else comes across this same issue that I had this is what I did to solve the problem.
I had the same exact issue. Took me a while to figure this out, but there is 2 places where you need to update your code that should solve this issue.
Within GridViewAdapter.Java make the following changes
Before...
private ArrayList data = new ArrayList();
After...
private ArrayList<ImageItem> data = new ArrayList();
Before...
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList data) {
After...
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList<ImageItem> data) {
I hope this helps!
You can create string-array, so that:
<string-array name="image_ids">
<item>#drawable/ads</item>
<item>#drawable/dsa</item>
<item>#drawable/sda</item>
</string-array>