I have the class GetAllENtrysListViewAdapter extends BaseAdapter where the list View in the PinboardActivity is set with an array.
I want to change the likeImage if there is saved an certain entry in the SQLite Database. I call the getLike Cursor in getView this way:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListCell cell;
if (convertView == null) {
convertView = inflater.inflate(R.layout.get_all_entry_list_view_cell, null);
cell = new ListCell();
cell.likes = (TextView) convertView.findViewById(R.id.listViewLikes);
cell.note = (TextView) convertView.findViewById(R.id.listViewNote);
cell.img = (ImageView) convertView.findViewById(R.id.listViewImg);
cell.likeImage = (ImageView) convertView.findViewById(R.id.heartImage);
convertView.setTag(cell);
}
else {
cell = (ListCell)convertView.getTag();
}
try {
JSONObject jsonObject = this.dataArray.getJSONObject(position);
cell.likes.setText(jsonObject.getString("likes"));
cell.note.setText(jsonObject.getString("note"));
String img = jsonObject.getString("image");
String urlForImageInServer = baseUrlForImage + img;
new AsyncTask<String, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(String... params) {
//download image
String url = params[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch(MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return icon;
}
#Override
protected void onPostExecute(Bitmap result) {
cell.img.setImageBitmap(result);
}
}.execute(urlForImageInServer);
//CURSOR IS CALLED --> THIS LINE CAUSES THE ERROR
cursor = dbh.getLike(dbh);
cursor.moveToFirst();
String markerID = pinboard.markerID;
if (cursor.moveToFirst()) {
do {
if (cursor.getString(0).equals(markerID) && Integer.parseInt(cursor.getString(1))== position && Integer.parseInt(cursor.getString(2)) == 1) {
cell.likeImage.setImageResource(R.drawable.heart_filled);
}
}
while(cursor.moveToNext());
}
cursor.close();
}
catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
public static class ListCell {
private TextView likes;
private TextView note;
private ImageView img;
public ImageView likeImage;
public boolean touched;
}
As opening the PinboardActivity I get the following error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor de.mareike.cityexplorer.DbHelper.getLike(de.mareike.cityexplorer.DbHelper)' on a null object reference
Am I calling the cursor on the wrong place or what could cause the issue?
By the way, the context is set this way:
public GetAllEntrysListViewAdapter(Context context, Cursor cursor) {
super();
cursor = cursor;
DbHelper dbh = new DbHelper(context);
inflater=LayoutInflater.from(context);
}
Related
My recyclerView is not displaying the item views and dont no why, and I am able to get the data from the server but the recyclerView is just not populating my data with the ui.
Here is my Adapter class that binds the itemviews with the data :
public class AdapterBooking extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<Booking> data= Collections.emptyList();
Booking current ;
public AdapterBooking(Context context,List<Booking> data) {
this.context = context;
this.inflater= LayoutInflater.from(context);
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.containerbookings, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder = (MyHolder) holder;
current = data.get(position);
myHolder.txtAccommoName.setText(current.AccommoName);
myHolder.txtBookingDate.setText("Booking Date: " + current.BookingDate);
myHolder.txtBookingExpiry.setText("Booking Expiry: " + current.BookingDuration);
myHolder.txtBookngStatus.setText("Status " + current.AccredStatus);
myHolder.txtBookngStatus.setTextColor( ContextCompat.getColor(context, R.color.colorAccent));
Glide.with(context).load(R.drawable.the_yard_room)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(myHolder.img);
}
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtAccommoName;
ImageView img;
TextView txtBookingDate;
TextView txtBookingExpiry;
TextView txtBookngStatus;
BootstrapButton btnCancel;
public MyHolder(View itemView) {
super( itemView );
txtAccommoName = (TextView)itemView.findViewById(R.id.textBookedAccommoName);
img= (ImageView) itemView.findViewById(R.id.imageBookedAccomo);
txtBookingDate = (TextView)itemView.findViewById(R.id.txtBookingDate);
txtBookingExpiry = (TextView)itemView.findViewById( R.id. txtBookingExpiry);
txtBookngStatus = (TextView)itemView.findViewById( R.id.txtBookingStatus );
btnCancel = (BootstrapButton)itemView.findViewById( R.id. btnCancelBookings);
}
Here is my Activity class that gets the data from the server:
public class BookingList extends AppCompatActivity {
List<Booking> data;
Booking booking;
RecyclerView recyclerViewBooking;
AdapterBooking mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_booking_list );
new Connect().execute();
}
private class Connect extends AsyncTask<String,String,String>
{
ProgressDialog load;
HttpURLConnection connection = null;
URL url = null;
String http = null;
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(BookingList.this);
int studID = settings.getInt("STUDENT_ID_BOOKING",0 );
public Connect() {
load = new ProgressDialog(BookingList.this);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
load.setMessage("Loading...");
load.setCancelable(false);
load.show();
}
#Override
protected String doInBackground(String... params) {
http = "http://192.168.42.197:5432/WCF/BookingServices.svc/getAllBookingsByStud/"+studID;
try {
url = new URL(http);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(15000);
connection.setConnectTimeout(10000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "Application/json");
connection.setDoInput(true);
} catch (IOException e) {
e.printStackTrace();
}
try {
int code = connection.getResponseCode();
System.out.println("Response: " + code);
if(code ==HttpURLConnection.HTTP_OK)
{
InputStream input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line = null;
while((line=reader.readLine()) != null)
{
result.append(line);
}
System.out.println(result.toString());
return (result.toString());
}else {
return("Unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
}finally {
connection.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
load.dismiss();
load.dismiss();
data= new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject object = jsonObject.getJSONObject("Accommodation");
JSONObject objectStudent = jsonObject.getJSONObject("Student");
booking = new Booking();
booking.Name = objectStudent.getString("Name");
booking.Surname = objectStudent.getString("Surname");
booking.StudentNumber = objectStudent.getInt("StudentNumber");
booking.AccommoName = object.getString("AccommoName");
booking.AccredStatus = object.getString("AccredStatus");
booking.BookingDate = jsonObject.getString("BookingDate");
booking.BookingDuration = jsonObject.getString("BookingDuration");
booking.BookingStatus = jsonObject.getString( "BookingStatus" );
data.add(booking);
}
recyclerViewBooking = (RecyclerView)findViewById(R.id.listOfbooks);
mAdapter = new AdapterBooking(BookingList.this,data);
recyclerViewBooking.setAdapter(mAdapter);
recyclerViewBooking.setLayoutManager(new LinearLayoutManager(BookingList.this));
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(BookingList.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Check your Layout, make sure your RecyclerView isn't child of ScrollView. If you need that, you can use NestedScrollView.
If you make a breakpoint, your onBindViewHolder works?
Another thing yo can try:
There is a RecyclerView method: setHasStableIds(boolean).
#Override
public void setHasStableIds(boolean hasStableIds) {
return false;
}
Also, I think the context is wrong:
In activity:
private Activity getActivity {
return this;
}
In AsyncTask:
mAdapter = new AdapterBooking(getActivity().getApplicationContext(),data);
I hope this information help you.
Good luck.
Remove this:
MyHolder myHolder = (MyHolder) holder;
Instead do this: because I think there is no need to get another holder reference when you already have it on onBindViewHolder(..) method
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
current = data.get(position);
holder.txtAccommoName.setText(current.AccommoName);
holder.txtBookingDate.setText("Booking Date: " + current.BookingDate);
holder.txtBookingExpiry.setText("Booking Expiry: " + current.BookingDuration);
holder.txtBookngStatus.setText("Status " + current.AccredStatus);
holder.txtBookngStatus.setTextColor( ContextCompat.getColor(context, R.color.colorAccent));
Glide.with(context).load(R.drawable.the_yard_room)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(holder.img);
}
Try this please and do let me know if it changes anything for you.
EDIT: As pointed out by #adnbsr as well in his comments you need to check this as well because it feels wrong instead you should have done this
extends RecyclerView.Adapter<AdapterBooking.MyHolder>
Fixed the problem. Im using shared preference to store data so I used the wrong key to get a value from the shared preference which before was causing the sharedpreference value to be initialized to zero.
i have some problem with my JSON code.
I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please master help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for HomeFragment.java (where i doing the JSON).
public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {
private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;
public HomeFragment() {
}
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
try {
mCallbacks = (CategorySelectionCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
if (UtilMethods.isConnectedToInternet(getActivity())) {
initCategoryList();
} else {
internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener,
getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), CATEGORY_ACTION);
}
}
public class getCategList extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
/**
* json is populating from text file. To make api call use ApiHandler class
*
* <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
* <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done. Do the parsing as the following.
*/
URL hp = null;
try {
hp = new URL(
getString(R.string.liveurl) + "foodcategory.php");
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("UR1L", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
categoryList = new ArrayList<Category>();
for (int i = 0; i < j.length(); i++) {
Category category = new Category();// buat variabel category
JSONObject Obj;
Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
category.setId(Obj.getString(JF_ID));
category.setTitle(Obj.getString(JF_TITLE));
category.setIconUrl(Obj.getString(JF_ICON));
if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
}
Log.d("URL1",""+Obj.getString(JF_TITLE));
categoryList.add(category);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
}
});
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
Error = e.getMessage();
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
Error = e.getMessage();
}
return null;
}
}
//! function for populate category list
private void initCategoryList() {
new getCategList().execute();
}
#Override
public void onConnectionEstablished(int code) {
if (code == CATEGORY_ACTION) {
initCategoryList();
}
}
#Override
public void onUserCanceled(int code) {
if (code == CATEGORY_ACTION) {
getActivity().finish();
}
}
//! catch json response from here
#Override
public void onSuccessResponse(String tag, String jsonString) {
//! do same parsing as done in initCategoryList()
}
//! detect response error here
#Override
public void onFailureResponse(String tag) {
}
//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
void onCategorySelected(String catID, String title);
}
}
This code for categoryAdapter.java (where i put the result of JSON to the list)
public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {
private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;
public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
super(activity, R.layout.layout_category_list);
this.activity = activity;
this.inflater = LayoutInflater.from(activity.getApplicationContext());
this.categoryList = categoryList;
this.mCallbacks = mCallbacks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder row;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_category_list, null);
row = new ViewHolder();
row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);
} else {
row = (ViewHolder) convertView.getTag();
}
Category category = categoryList.get(position);
Picasso.with(activity).load(UtilMethods
.getDrawableFromFileName(activity,category.getIconUrl()))
.tag(category.getIconUrl())
.into(row.categoryImage);
row.categoryName.setText(category.getTitle());
Picasso.with(activity)
.load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
.placeholder(R.drawable.img_banner_placeholder)
.tag(category.getIconUrl())
.fit()
.into(row.bannerImage);
row.bannerImage.setOnClickListener(this);
row.categoryImage.setTag(position);
row.categoryName.setTag(position);
row.bannerImage.setTag(position);
return convertView;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public void onClick(View v) {
int position = Integer.parseInt(v.getTag().toString());
mCallbacks.onCategorySelected(categoryList.get(position).getId(),
categoryList.get(position).getTitle());
}
private static class ViewHolder {
public ImageView bannerImage;
public TextView categoryName;
public ImageView categoryImage;
}
}
Try this.
Picasso.with(activity).load(category.getIconUrl())
.into(row.categoryImage);
If it worked !. You Check the UtilMethods.getDrawableFromFileName() !!!
I'm creating an activity that shows files in the device (including external storage) with '.mp4' extension in a ListView.
Here's my Activity file
public class FindVideoActivity extends AppCompatActivity {
private List<String> fileNames;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_video);
fileNames = new ArrayList<>();
lv = (ListView) findViewById(R.id.find_video_list);
updateFileList();
}
public void updateFileList() {
String path;
String extension = Environment.getExternalStorageState();
if(extension.equals(Environment.MEDIA_MOUNTED)) {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videostreaming/";
} else {
path = Environment.MEDIA_UNMOUNTED;
}
File file = new File(path);
ArrayAdapter<String> fileList = new ArrayAdapter<>(this, R.layout.file_list_item, fileNames);
VideoFinder finder = new VideoFinder();
File[] files = file.listFiles(finder);
for(File f: files) {
fileNames.add(f.getName());
}
lv.setAdapter(fileList);
}
}
In order to filter out the '.mp4' files, I created another class and named it VideoFinder.java. This class implements java.io.FilenameFilter. Here's the code.
public class VideoFinder implements FilenameFilter {
// overriding the method from the FilenameFilter interface.
#Override
public boolean accept(File dir, String filename) {
if(filename.endsWith(".mp4")) {
return true;
}
return false;
}
}
When I run the code above, it returns `NullPointerException` like the following.
Caused by: java.lang.NullPointerException
at com.marshall.videostreaming.FindVideoActivity.updateFileList(FindVideoActivity.java:46)
at com.marshall.videostreaming.FindVideoActivity.onCreate(FindVideoActivity.java:26)
So it says that the for loop in the updateFileList() method is catching the exception. I still cannot catch what I am missing in this code. Can anyone help?
Check your path, because assigning Environment.MEDIA_UNMOUNTED doesn't seem right. also check if Files is null, because this is why you got NPE.
Its my Main Java class
/**
* Created by ravindra on 2/12/15.
*/
public class GalleryScreen extends Activity implements View.OnClickListener{
private ArrayList<String> file_path = new ArrayList<String>();
GridView gridview;
ImageView left_iv;
TextView header_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_screen);
Bundle bundle = getIntent().getExtras();
gettingIds();
gettingOnClickListener();
fetchDeviceGallery();
}
private void fetchDeviceGallery() {
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
file_path = getFilePaths();
GalleryAdapter adapter = new GalleryAdapter(GalleryScreen.this,file_path);
gridview.setAdapter(adapter);
System.out.println("Gallery images================="+cursor.getCount()+" "+columnIndex);
}
private void gettingIds() {
gridview = (GridView) findViewById(R.id.gridview);
left_iv = (ImageView) findViewById(R.id.left_iv);
header_tv = (TextView) findViewById(R.id.header_tv);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
finish();
// overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
}
private void gettingOnClickListener() {
left_iv.setOnClickListener(this);
}
public ArrayList<String> getFilePaths() {
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null) {
c = GalleryScreen.this.managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst())) {
do {
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try {
dirList.add(tempDir);
} catch (Exception e) {
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for (int i = 0; i < dirList.size(); i++) {
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if (imageList == null)
continue;
for (File imagePath : imageList) {
try {
if (imagePath.isDirectory()) {
imageList = imagePath.listFiles();
}
if (imagePath.getName().contains(".jpg") || imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg") || imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
|| imagePath.getName().contains(".mp4") || imagePath.getName().contains(".MP4")
||imagePath.getName().contains(".mp3") || imagePath.getName().contains(".MP3"))
{
System.out.println("RESOURCES ARE====="+imagePath);
String path = imagePath.getAbsolutePath();
resultIAV.add(path);
}
// }
catch (Exception e) {
e.printStackTrace();
}
}
}
return resultIAV;
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.left_iv:
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
break;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
}
And Its adapter class is as follow:-
/**
* Created by ravindra on 2/12/15.
*/
public class GalleryAdapter extends BaseAdapter {
private final DisplayImageOptions options;
private final ImageLoader imageLoader;
Activity activity;
ArrayList<String> arrayList = new ArrayList<String>();
public GalleryAdapter(Activity activity, ArrayList<String> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
imageLoader = ImageLoader.getInstance();
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(activity));
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loader)
.showImageForEmptyUri(R.drawable.loader)
.showImageOnFail(R.drawable.loader)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
ImageView gallery_item;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder _viewHolder;
if (convertView == null) {
_viewHolder = new ViewHolder();
LayoutInflater _layInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = _layInflater.inflate(R.layout.gallery_item, null);
_viewHolder.gallery_item = (ImageView) convertView.findViewById(R.id.gallery_item);
convertView.setTag(_viewHolder);
} else {
_viewHolder = (ViewHolder) convertView.getTag();
}
if (arrayList.get(position).contains(".mp3") || arrayList.get(position).contains(".MP3"))
{
_viewHolder.gallery_item.setImageResource(R.drawable.audio_img);
}
else {
imageLoader.displayImage("file://" + arrayList.get(position), _viewHolder.gallery_item, options, null);
}
return convertView;
}
}
I'm attempting to populate a ListView with XML Data by using an ArrayList - which I've been able to accomplish thus far - the issue is the ArrayList does not seem to populate the ListView with data beyond the first item in the listView and I'm unsure why.
Screenshot
XML Data:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<response>
<cmd>getVideos</cmd>
<success>1</success>
<NumberOfVideos>4</NumberOfVideos>
<Videos>
<Video>
<VideoName>sample_iPod</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_mpeg4</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_sorenson</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_iTunes</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov
</VideoUrl>
<VideoTags/>
</Video>
</Videos>
</response>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<Cmd> {
Activity context;
List<Cmd> videos;
public CustomListViewAdapter(Activity context, List<Cmd> videos) {
super(context, R.layout.list_item2, videos);
this.context = context;
this.videos = videos;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtSuccess;
TextView txtCmd;
TextView txtPrice;
}
public Cmd getItem(int position) {
return videos.get(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item2, null);
holder = new ViewHolder();
holder.txtSuccess = (TextView) convertView.findViewById(R.id.success);
holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd);
holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Cmd cmd = (Cmd) getItem(position);
holder.txtSuccess.setText(cmd.getSuccess());
holder.txtCmd.setText(cmd.getCmd());
// holder.imageView.setImageBitmap(cmd.getImageBitmap());
holder.txtPrice.setText(cmd.getVideoName() + "");
return convertView;
}
}
SAXParserAsyncTaskActivity.java
public class SAXParserAsyncTaskActivity extends Activity implements
OnClickListener, OnItemClickListener {
Button button;
ListView listView;
List<Cmd> videos = new ArrayList<Cmd>();
CustomListViewAdapter listViewAdapter;
static final String URL = "http://mobile.example.com/api/xml.php?cmd=getVideos&username=fake&password=";
public static final String LIBRARY = "Library";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
findViewsById();
button.setOnClickListener(this);
listView.setOnItemClickListener(this);
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[] { URL });
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
listView = (ListView) findViewById(R.id.cmdList);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
// GetXMLTask task = new GetXMLTask(this);
// task.execute(new String[] { URL });
}
// private inner class extending AsyncTask
private class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
protected void onPostExecute(List<Cmd> videos) {
listViewAdapter = new CustomListViewAdapter(context, videos);
listView.setAdapter(listViewAdapter);
}
/*
* uses HttpURLConnection to make Http request from Android to download
* the XML file
*/
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<Cmd> doInBackground(String... urls) {
List<Cmd> videos = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
videos = SAXXMLParser.parse(stream);
for (Cmd cmd : videos) {
String videoName = cmd.getVideoName();
// String getVideos = cmd.getVideos();
String getVideo = cmd.getVideo();
String getVideoURL = cmd.getVideoURL();
String getNumberOfVideos = cmd.getNumberOfVideos();
Bitmap bitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
bitmap = BitmapFactory.decodeStream(
new URL(videoName).openStream(), null,
bmOptions);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// stream.close();
return videos;
}
}
}
Cmd.java
public class Cmd implements ListAdapter {
private String success;
private String cmd;
List<Cmd> videos;
private String video;
private String numberofvideos;
private String videoname;
private String videourl;
private LayoutInflater mInflater;
Button fav_up_btn1;
Button fav_dwn_btn1;
Context my_context;
// private Bitmap imageBitmap;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If convertView wasn't null it means we have already set it to our
// list_item_user_video so no need to do it again
if (convertView == null) {
// This is the layout we are using for each row in our list
// anything you declare in this layout can then be referenced below
convertView = mInflater.inflate(R.layout.list_item_user_video,
parent, false);
}
// We are using a custom imageview so that we can load images using urls
ImageView thumb = (ImageView) convertView
.findViewById(R.id.userVideoThumbImageView);
//thumb.setScaleType(ScaleType.FIT_XY);
TextView title = (TextView) convertView
.findViewById(R.id.userVideoTitleTextView);
TextView uploader = (TextView) convertView
.findViewById(R.id.userVideouploaderTextView);
TextView viewCount = (TextView) convertView
.findViewById(R.id.userVideoviewsTextView);
uploader.setText(videos.get(position).getTitle());
viewCount.setText(videos.get(position).getviewCount() + " views");
fav_up_btn1 = (Button) convertView.findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(my_context.getResources()
.getDrawable(R.drawable.fav_up_btn1)
.getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
// Get a single video from our list
final Cmd video = videos.get(position);
// Set the image for the list item
// / thumb.setImageDrawable(video.getThumbUrl());
//thumb.setScaleType(ScaleType.FIT_XY);
// Set the title for the list item
title.setText(video.getTitle());
uploader.setText("by " + video.getUploader() + " | ");
return convertView;
}
public String getUploader() {
// TODO Auto-generated method stub
return null;
}
public String getviewCount() {
// TODO Auto-generated method stub
return null;
}
public CharSequence getTitle() {
// TODO Auto-generated method stub
return null;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getNumberOfVideos() {
return numberofvideos;
}
public void setNumberOfVideos(String numberofvideos) {
this.numberofvideos = numberofvideos;
}
public List<Cmd> getVideos() {
return videos;
}
public void setVideos(List<Cmd> videos) {
this.videos = videos;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getVideoName() {
return videoname;
}
public void setVideoName(String videoname) {
this.videoname = videoname;
}
public String getVideoURL() {
return videourl;
}
public void setVideoURL(String videourl) {
this.videourl = videourl;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public boolean areAllItemsEnabled() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
return false;
}
public String getId() {
// TODO Auto-generated method stub
return null;
}
}
SAXXMLParser.java
public class SAXXMLParser {
public static List<Cmd> parse(InputStream is) {
List<Cmd> response = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHandler saxHandler = new SAXXMLHandler();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// get the `Video list`
response = saxHandler.getResponse();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return video list
return response;
}
}
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Cmd> videos;
private String tempVal;
// to maintain context
private Cmd cmd;
public SAXXMLHandler() {
videos = new ArrayList<Cmd>();
}
public List<Cmd> getResponse() {
return videos;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("cmd")) {
// create a new instance of cmd
cmd = new Cmd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("videos")) {
// add it to the list
videos.add(cmd);
} else if (qName.equalsIgnoreCase("success")) {
cmd.setSuccess(tempVal);
} else if (qName.equalsIgnoreCase("numberofvideos")) {
cmd.setNumberOfVideos(tempVal);
} else if (qName.equalsIgnoreCase("videos")) {
cmd.setVideos(videos);
} else if (qName.equalsIgnoreCase("video")) {
cmd.setVideo(tempVal);
} else if (qName.equalsIgnoreCase("videoname")) {
cmd.setVideoName(tempVal);
} else if (qName.equalsIgnoreCase("videourl")) {
cmd.setVideoURL(tempVal);
}
}
}
parser_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/button" />
<ListView
android:id="#+id/cmdList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
XML Screenshot
P.S.
If any additional information is required - please let me know (I will be at my desk working on this for the next few hours and will gladly answer any questions and accept any answers promptly)
In SAXXMLHandler.java's endElement() method you only add the cmd to the videos list if qName.equalsIgnoreCase("videos").
In all other cases you modify the cmd but you dont actually add it to the list. You want to add a videos.add(cmd) statement in the else if blocks as well so all the cmd's get added to the list.
This mistake right here is the cause of your List<Cmd> videos only having one item and thus only showing one item in your listview.
Hi my problem is simple : imageviews are not fixed. I saw an answer in this link : link and i do understand the answer but i can't do it. So my question is : How do i turn off view recycling in my Adapter ?
If you want i can put a little bit of code :
public class PortfolioAdapter extends ArrayAdapter<PortfolioView>{
private ArrayList<PortfolioView> items;
public PortfolioAdapter(Context context, int textViewResourceId, ArrayList<PortfolioView> items) {
super(context, textViewResourceId, items);
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.portfolio_rows, null);
}
PortfolioView pv = items.get(position);
if (pv != null) {
TextView ticker = (TextView) v.findViewById(R.id.portfolio_rows_ticker);
TextView location = (TextView)v.findViewById(R.id.portfolio_rows_location);
TextView country = (TextView)v.findViewById(R.id.portfolio_rows_country);
TextView portfolio_value = (TextView)v.findViewById(R.id.portfolio_rows_portfolio_value);
TextView yesterday_earnings = (TextView)v.findViewById(R.id.portfolio_rows_yesterday_earnings);
TextView shares = (TextView)v.findViewById(R.id.portfolio_rows_shares);
TextView last_buy_shares = (TextView)v.findViewById(R.id.portfolio_rows_last_buy_shares);
TextView last_buy = (TextView)v.findViewById(R.id.portfolio_rows_last_buy);
TextView your_shares_held = (TextView)v.findViewById(R.id.portfolio_rows_your_shares_held);
ImageView SmPortrait = (ImageView)v.findViewById(R.id.portfolio_rows_sm_portrait);
if (ticker != null) {
ticker.setText(pv.getPortfolio_ticker());
}
if (location != null) {
location.setText(pv.getLocation());
}
if (country != null) {
country.setText(pv.getCountry());
}
if (portfolio_value != null) {
DecimalFormat f_portfolio_value = new DecimalFormat();
f_portfolio_value.setMaximumFractionDigits(2);
String portfolio_value_format = f_portfolio_value.format(pv.getPortfolio_value());
portfolio_value.setText(portfolio_value_format);
}
if (yesterday_earnings != null) {
DecimalFormat f_yesterday_earnings = new DecimalFormat();
f_yesterday_earnings.setMaximumFractionDigits(2);
String yesterday_earnings_format = f_yesterday_earnings.format(pv.getYesterday_earnings());
yesterday_earnings.setText(yesterday_earnings_format);
}
if (shares != null) {
shares.setText(Integer.toString(pv.getShares()));
}
if (last_buy_shares != null) {
last_buy_shares.setText(Integer.toString(pv.getLast_buy_shares()));
}
if (last_buy != null) {
last_buy.setText(pv.getLast_buy());
}
if (your_shares_held != null) {
your_shares_held.setText(Integer.toString(pv.getYour_shares_held()));
}
if(SmPortrait != null){
createimage(SmPortrait, pv.getSm_portrait());
}
}
return v;
}
private class CreateImage extends AsyncTask<String, Void, Drawable> {
ImageView image;
public CreateImage(ImageView img) {
image = img;
image.invalidate();
}
protected void onPreExecute() {
}
protected Drawable doInBackground(String... urls) {
InputStream is;
Drawable d = null ;
try {
is = (InputStream)new URL(urls[0]).getContent();
d = Drawable.createFromStream(is, "Image");
return d;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}
protected void onPostExecute(Drawable d) {
image.setBackgroundDrawable(d);
image.invalidateDrawable(d);
}
}
// Catch portrait
public void createimage(ImageView img, String url){
new CreateImage(img).execute(url);
}
}
The basic idea is that when you setup your view you want to add a thumbnail as a placeholder. Then use the Tag property to "mark" the view with something like the ID from the database - this can then be used to identify which row should be getting the image and you shouldn't suffer from shifting rows anymore.
Take a look at the answer to this question by Fedor: link - it provides you with a very good example.
You do not need to invalidate the image drawable after set its background. Remove
image.invalidateDrawable(d);
line from the onPostExecute() method and see if it fixes.
What's it for the method invalidateDrawable about Class ImageView?
I 've found the source core as bellow:
#Override
public void invalidateDrawable(Drawable dr) {
if (dr == mDrawable) {
/* we invalidate the whole view in this case because it's very
* hard to know where the drawable actually is. This is made
* complicated because of the offsets and transformations that
* can be applied. In theory we could get the drawable's bounds
* and run them through the transformation and offsets, but this
* is probably not worth the effort.
*/
invalidate();
} else {
super.invalidateDrawable(dr);
}
}