Android Studio Unable to Display Photo Gallery on ListView - android

I'm developing a business profile page which contains profile image contact data and a photo gallery. I'm using Listview to check the urls from the received JSON data.
The problem is: the listview is not displayed on profile_layout. not inflated. Anyone can help?
Thanks a lot.
Here're the codes:
ProfileActivity.java
private void getGalleryJSON(String url) {
listView = (ListView) findViewById(R.id.gallery_listview);
galleryAdapter = new GalleryAdapter(this, R.layout.gallery_layout);
listView.setAdapter(galleryAdapter);
class GetGalleryJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String uri2 = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri2);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
bufferedReader.close();
con.disconnect();
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
gallery_json = s;
//TextView tv = (TextView)findViewById(R.id.gallery_content);
//tv.setText(gallery_json);
//=====================================
//======================================
// JSON OBJECT RECEIVED PERFECTLY
//======================================
//======================================
try {
gallery_jsonObject = new JSONObject(gallery_json);
gallery_jsonArray = gallery_jsonObject.getJSONArray("result");
int count = 0;
String thumb;
while (count < gallery_jsonArray.length()){
JSONObject JO = gallery_jsonArray.getJSONObject(count);
thumb = JO.getString("thumburl");
Gallery gallery = new Gallery(thumb);
galleryAdapter.add(gallery);
count++;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
GetGalleryJSON ggj = new GetGalleryJSON();
ggj.execute(url);
}
This is the adapter GalleryAdapter.java
public class GalleryAdapter extends ArrayAdapter{
List list = new ArrayList();
public GalleryAdapter(Context context, int resource)
{
super(context, resource);
}
public void add(Profiles object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
GalleryHolder galleryHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.gallery_layout, parent, false);
galleryHolder = new GalleryHolder();
galleryHolder.img_url = (TextView) row.findViewById(R.id.img_url);
row.setTag(galleryHolder);
}
else {
galleryHolder = (GalleryHolder) row.getTag();
}
Gallery gallery = (Gallery) this.getItem(position);
galleryHolder.img_url.setText(gallery.getUrl());
//=====================================
//======================================
// LATER I WILL USE THIS FOR IMAGEVIEW
//======================================
//===== //Picasso.with(this.getContext()).load(gallery.getUrl()).into(galleryHolder.img_url);
return row;
}
static class GalleryHolder{
TextView img_url;
}}
And this is the Gallery.java
public class Gallery {
private String url;
public Gallery(String url)
{
this.setUrl(url);
}
public void setUrl(String url){
this.url = url;
}
public String getUrl(){
return url;
}}
I use this layout on profile page
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true"
android:orientation="horizontal"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
screen-wide thumb
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/data">contact data
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:padding="10dp"
android:id="#+id/content">
<TextView
android:id="#+id/txt_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:text="Content" />
</LinearLayout>
<TextView
android:id="#+id/gallery_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gallery"
android:textAlignment="center"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:padding="10dp"
android:id="#+id/gallery">
<ListView
android:id="#+id/gallery_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"
android:background="#FF0000"
/>
</LinearLayout>
</LinearLayout>
</ScrollView>
And this is the gallery_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="85dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/img_url"
/>
</RelativeLayout>
Note:
I am using listview to check the urls only. I will change to GridView later

Probably your listview's height is calculated 'zero'. It's not recommended to put a listview inside scrollview, because the listview can not be scrolled anymore.
But if you insist to do this, calculate the listview's total height & update its height in runtime according to this answer: How to measure total height of ListView
But first set the listview's layout_height to wrap_content.

Related

cardView in a RecyclerView is not showing any item

I am trying to make an App that has two tabs in a ViewPager and each tab are fragments and should have a card View in a RecyclerView.I fetch the data from an API added it in an ArrayList. I dont see any error in my Adapter class and DailyMenuFrag. I will appreciate any kind of help
DailyMenuFrag.java
public class DailyMenuFrag extends Fragment {
private List<DailyData> data_list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
data_list = new ArrayList<>();
load_data();
View view = inflater.inflate(R.layout.fragment_daily_menu, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
DailyDataAdapter adapter = new DailyDataAdapter(getActivity(), data_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
TextView textView = (TextView) view.findViewById(R.id.tt);
textView.setText("hellp");
return view;
}
public void load_data() {
task.execute("http://yemekapp.kuarkdijital.com.tr/home.php");
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
JSONObject dailyObject = null;
JSONObject popularObject = null;
JSONObject jsonObject = new JSONObject(current);
JSONObject banner = jsonObject.getJSONObject("banner");
String daily = jsonObject.getString("daily");
String popular = jsonObject.getString("popular");
JSONArray dailyArray = new JSONArray(daily);
JSONArray popularArray = new JSONArray(popular);
for (int i = 0; i < dailyArray.length(); i++) {
dailyObject = dailyArray.getJSONObject(i);
popularObject = popularArray.getJSONObject(i);
DailyData singleData = new DailyData(dailyObject.getInt("id"), dailyObject.getString("Servings"), dailyObject.getString("Title"), dailyObject.getString("CookTime"), dailyObject.getString("Image"));
data_list.add(singleData);
Log.i("data", data_list.size() + "");
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
};
}
DailyDataAdapter.java
public class DailyDataAdapter extends RecyclerView.Adapter<DailyDataAdapter.ViewHolder> {
Context context;
List<DailyData> dailyDataList;
public DailyDataAdapter(Context context, List<DailyData> dailyDatas) {
this.context = context;
this.dailyDataList = dailyDatas;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(dailyDataList.get(position).getTitle());
holder.cookTime.setText(dailyDataList.get(position).getCookTime());
holder.servings.setText(dailyDataList.get(position).getServings());
//Image
Glide.with(context).load(dailyDataList.get(position).getImage_link()).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return dailyDataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView cookTime,servings,title;
public ImageView thumbnail;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
servings = (TextView) itemView.findViewById(R.id.servings);
cookTime = (TextView) itemView.findViewById(R.id.cooktime);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
ViewPagger viewPagger = new ViewPagger();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,viewPagger);
transaction.commit();
}
}
}
ViewPAgger.java
public class ViewPagger extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_view_pagger,container,false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab);
viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
return position == 0? new DailyMenuFrag():new PopularMenuFrag();
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return position == 0? "Daily":"Popular";
}
});
tabLayout.setupWithViewPager(viewPager);
return view;
}
}
ViewPagger.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nejat.yemektarifiproject.ViewPagger">
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</FrameLayout>
card.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/tools">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="5dp"
android:elevation="3dp"
card_view:cardCornerRadius="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="fitXY" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/thumbnail"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:textColor="#4c4c4c"
android:textSize="15dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:orientation="horizontal">
<TextView
android:id="#+id/servings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="10dp"
android:layout_weight="1"/>
<TextView
android:id="#+id/cooktime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="10dp" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Fragment_DailyMenuFrag.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nejat.yemektarifiproject.DailyMenuFrag">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
>
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/tt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</FrameLayout>
Add this
adapter.notifyDataSetChanged() in postExecute
I think you are forgetting to notify adapter about data change after you are getting data.
Declare your Adapter Global so you can call it from any where
DailyDataAdapter adapter = null;
and initialize it like this in your onCreateView
adapter = new DailyDataAdapter(getActivity(), data_list);
so call this notifyDataSetChanged() after doInBackground in your onPostExecute
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
}
this should work for you.

GridView getChildAt returning null for visible children

I have a grid of images that were taken from a custom camera activity.
On other activity I load the images into a grid.
I have a method that turn on & off a checkbox on each Image.
While trying to move through all the images, I'm getting some strange behavior:
GridView.getCount() returns the correct number of images in the GridView, but GridView.getChildAt() method returned only part of the images.
so, when I try to do so, I get a null Exception.
The GridView Adapter:
public class PhotoGalleryAdapter extends ArrayAdapter {
// Declare variables
private Activity adapterActivity;
private int layoutResourceId;
private ArrayList gridItemsArray;
private static LayoutInflater inflater = null;
public PhotoGalleryAdapter(Activity a, int layoutResourceId, ArrayList fGridItemArray) {
super(a, layoutResourceId, fGridItemArray);
this.layoutResourceId = layoutResourceId;
this.adapterActivity = a;
this.gridItemsArray = fGridItemArray;
}
public int getCount() {
return gridItemsArray.size();
}
public Object getItem(int position) {
return gridItemsArray.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
HolderViewRow holderRow = null;
View rowView = (View) convertView;
if (rowView == null){
LayoutInflater inflater = adapterActivity.getLayoutInflater();
rowView = inflater.inflate(layoutResourceId, parent, false);
holderRow = new HolderViewRow();
holderRow.imageFileBMP = (ImageView) rowView.findViewById(R.id.imageObject);
holderRow.checkBox = (CheckBox) rowView.findViewById(R.id.itemCheckBox);
holderRow.checkBoxImage = (ImageView) rowView.findViewById(R.id.itemImageCheckBox);
rowView.setTag(holderRow);
}
else
{
holderRow = (HolderViewRow) rowView.getTag();
}
PhotoGalleryItem item = (PhotoGalleryItem) gridItemsArray.get(position);
// Set the decoded bitmap iitemnto ImageView
holderRow.imageFileBMP.setImageBitmap(item.getImageBMP());
holderRow.imageFilePath = item.getImagePath();
return rowView;
}
static class HolderViewRow {
ImageView imageFileBMP;
String imageFilePath;
CheckBox checkBox;
ImageView checkBoxImage;
}
}
public class PhotoGalleryItem {
private Bitmap imageBMP;
private String imagePath;
private CheckBox checkBox;
private ImageView checkBoxImage;
public PhotoGalleryItem(Bitmap imageBMP, String imagePath) {
super();
this.imageBMP = imageBMP;
this.imagePath = imagePath;
}
public Bitmap getImageBMP() {
return imageBMP;
}
public void setImageBMP(Bitmap imageBMP) {
this.imageBMP = imageBMP;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
The Grid Activity:
private void RenderGridAndSetImages() {
// Locate the GridView in gridView_PhotoDisplay.xml
gridView = (GridView) findViewById(R.id.gridView_PhotoDisplay);
// Pass String arrays to Adapter Class
imageAdapter = new PhotoGalleryAdapter(this, R.layout.gridview_photo_item, GridItemArrayList);
gridView.setAdapter(imageAdapter);
}
And the function that has the problem:
public void SetVisibilityCheckBox_OnGrid (boolean checkBoxVisibility) {
// Handle item selection On GRIDVIEW ImageItem
final int size = gridView.getCount();
try {
ImageView imageCB;
int cbVisibility;
if (checkBoxVisibility)
cbVisibility = View.VISIBLE;
else
cbVisibility = View.INVISIBLE;
for(int i = 0; i < size; i++) {
View viewItem = (View) gridView.getChildAt(i);
if (viewItem != null) {
imageCB = (ImageView) viewItem.findViewById(R.id.itemImageCheckBox);
imageCB.setVisibility(cbVisibility);
}
}
}
catch (Exception ex) {
// Error occurred while SetSelectCheckBoxOnGrid
Log.e(PACKAGE_NAME, ACTIVITY_NAME + ".SetVisibilityCheckBox_OnGrid\n" + ex.getMessage());
}
}
The GridView Layout:
<RelativeLayout
android:id="#+id/layout_Holder"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#color/activityBackground"
tools:context="com.mountain.saymera.PhotoGalleryActivity">
<!-- Image view: layout_GridView -->
<RelativeLayout
android:id="#+id/layout_PhotoGridDisplay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:background="#color/activityBackground"
android:padding="1dp">
<GridView
android:id="#+id/gridView_PhotoDisplay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:numColumns="auto_fit"
android:verticalSpacing="1dp"
android:horizontalSpacing="1dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:focusable="true"
android:clickable="true"/>
<TextView
android:id="#+id/textView_NoImages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gallery_no_images"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#00000000"
android:textColor="#color/MenuButtonTint"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
The GridView Item Layout:
<RelativeLayout
android:id="#+id/layout_Holder"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/single_photo_frame_on_grid">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:background="#color/Grid_ItemFrame"
android:padding="0.3dp">
<com.mountain.saymera.SquareImageView
android:id="#+id/imageObject"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
</LinearLayout>
<CheckBox
android:id="#+id/itemCheckBox"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="invisible"
android:tint="#color/Grid_ItemCheckbox"/>
<ImageView
android:id="#+id/itemImageCheckBox"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="invisible"
android:background="#00000000"
android:src="#mipmap/ic_crop_square_black_24dp"
android:tint="#color/MenuCheckboxTint"/>
</RelativeLayout>
Need some help, Thanks
I have faced the same issue with programatically added ImageViews in a LinearLayout. Unfortunately, this method seems to be buggy at the moment, so I had to help myself by finding an alternative.
As a workaround, I saved the references of my ImageViews in a List and worked with them.

Android ListView lags for every scroll, even with ViewHolder

I want to give a little context: The app I'm currently involved in helping develop is an app a company has already developed for IOS and Android but the Android developer didn't delivered the expected results (mostly performance wise) so the leader gave me the code to see if I could fix it. Given the code I tried to improve it, now, the app is a picture sharing app somewhat like Instagram and it uses and endless scrolling list, the problem with the app is that every time I scroll a little bit, the app lags or freezes for a second and then loads a new row.
The listview only has one row visible at any moment.
What have I tried?:
The adapter wasn't using the ViewHolder pattern so I tried to implement it.
The programmer was defining a lot of click listeners on the getView method so I removed them.
still, every time I scroll ( a new row appears as there's only one visible row at any time) it lags. Are there any other noticeable problems here that could be the cause?
On another note, on this view there's a lot of overdraw so, maybe it's affecting the performance on the ListView? if so, tell me and I'll post the XML part.
Here's the code I adapted:
public class SomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
// declaration and constructors.....
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//initialization......
//setting variables.......
//getting views.....
listview = (ListView)rootView.findViewById(R.id.listview);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
int position = listview.getLastVisiblePosition();
if (!loading) {
loading = true;
listview.addFooterView(footerView, null, false);
currentVal = position + 1;
LoadMoreStuffAsyncTask loadMoreStuffAsyncTask = new LoadMoreStuffAsyncTask();
loadMoreStuffAsyncTask.execute();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (listview == null || listview.getChildCount() == 0) ? 0 : listview.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(firstVisibleItem == 0 && topRowVerticalPosition >= 0);
}
});
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity, container, false);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(SomeFragment.this);
return rootView;
}
private void LoadStuff () {
list=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
try {
list = query.find();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void LoadMoreStuff () {
List<ParseObject> moreList=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
query.setSkip(currentVal);
try {
moreList = query.find();
if(moreList!=null|| moreList.size()!=0){
for(int i =0;i<moreList.size();i++){
list.add(moreList.get(i));
}
}else{
loading=false;
}
} catch (ParseException e) {
e.printStackTrace();
loading=false;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
listAdapter.notifyDataSetChanged();
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
class LoadMoreStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected Void doInBackground(Void... params) {
LoadMoreStuff();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
listAdapter.updateList(list);
listview.setAdapter(listAdapter);
loading=false;
listview.removeFooterView(footerView);
listview.setSelection(currentVal);
}
}
class LoadStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getString(R.string.loading));
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
LoadStuff();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
swipeRefreshLayout.setRefreshing(false);
listAdapter = new CustomAdapter(activity,momentosGeneral);
listview.setAdapter(listAdapter);
}
}
}
This is the adapter:
public class CustomAdapter extends BaseAdapter {
//declaration of variables.....
public CustomAdapter(ActionBarActivity activity, List<ParseObject> list) {
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder{
//holderfields......
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder holder;
if (v == null) {
v = View.inflate(activity.getApplicationContext(), R.layout.customview, null);
holder = new ViewHolder();
holder.profilepicture = (CircularImageView) v.findViewById(R.id.profilepic);
holder.username = (TextView) v.findViewById(R.id.username);
holder.picture = (ParseImageView) v.findViewById(R.id.picture);
holder.container =(LinearLayout)v.findViewById(R.id.container);
holder.share=(LinearLayout)v.findViewById(R.id.share);
holder.comment= (TextView) v.findViewById(R.id.comment);
holder.likes= (TextView) v.findViewById(R.id.likes);
holder.publishDate =(TextView)v.findViewById(R.id.publisdate);
holder.liked = (ImageView)v.findViewById(R.id.liked);
v.setTag(holder);
}
holder = (ViewHolder)v.getTag();
CustomTypography customTypo = new CustomTypography(activity.getApplicationContext());
holder.username.setTypeface(customTypo.OpenSansSemibold());
if(list.get(position).getParseUser("User")!=null){
holder.username.setText(list.get(position).getParseUser("User").getString("name"));
profilePic = list.get(position).getParseUser("User").getParseFile("profilePic");
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
else{
holder.username.setText("");
}
final ParseFile picture = list.get(position).getParseFile("picture");
if (picture != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(picture.getData(), 0, picture.getData().length));
holder.picture.setImageDrawable(drawable);
holder.picture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
else{
}
holder.container.setLayoutParams(customLayoutParams);
holder.comment.setText(capitalizarPrimeraLetra(list.get(postiion).getString("Comment")));
holder.comment.setTypeface(customTypo.OpenSansRegular());
final int likes= list.get(position).getInt("Likes");
if(likes==0|| likes<0){
holder.likes.setText("");
}else{
holder.likes.setText(String.valueOf(likes));
}
holder.likes.setTypeface(customTypo.OpenSansLight());
holder.publishDate.setText(timeBetween(list.get(position).getCreatedAt()));
ParseQuery<ParseObject> query = ParseQuery.getQuery("LikedPictures");
query.whereEqualTo("picture", list.get(position));
query.whereEqualTo("user", currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> likelist, ParseException e) {
if (e == null) {
if (likelist.size() != 0) {
hasLiked = true;
holder.liked.setBackground(activity.getApplicationContext().getResources().getDrawable(R.drawable.like));
holder.likes.setTextColor(activity.getApplicationContext().getResources().getColor(R.color.red));
} else {
hasLiked = false;
}
} else {
hasLiked = false;
}
}
});
return v;
}
private String timeBetween(Date date){
String result="";
Date parsedPictureDate = null;
Date parsedCurrentDate=null;
Date today = new Date();
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
try {
parsedPictureDate= dateFormatLocal.parse(dateFormatGmt.format(date));
parsedCurrentDate=dateFormatLocal.parse(dateFormatGmt.format(hoy));
} catch (java.text.ParseException e) {
result="";
}
long milis=parsedCurrentDate.getTime()-parsedPictureDate.getTime();
final long MILISECS_PER_MINUTE=milis/(60 * 1000);
final long MILISECS_PER_HOUR=milis/(60 * 60 * 1000);
final long MILLSECS_PER_DAY=milis/(24 * 60 * 60 * 1000);
if(milis<60000){
result="Now";
}
if(milis>=60000&&milis<3600000){
result=MILISECS_PER_MINUTE+" min";
}
if(milis>=3600000&&milis<86400000){
result=MILISECS_PER_HOUR+" h";
}
if(milis>=86400000){
result=MILLSECS_PER_DAY+" d";
}
return result;
}
This is the item that always gets populated in the listview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#android:color/white"
android:paddingBottom="20dp"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/somelayout"
android:layout_weight="0.5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_marginLeft="5dp"
android:paddingRight="#dimen/padding_16dp_sw600"
android:gravity="left"
android:layout_marginBottom="5dp">
<customImageView
android:layout_gravity="center"
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/profilepicture"
app:border_width="0dp"
/>
<TextView
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/username"
android:textSize="14sp"
android:gravity="left"
android:singleLine="true"
android:minLines="1"
android:maxLines="1"
android:lines="1"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/layoutTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:layout_weight="0.5"
android:layout_gravity="center" >
<TextView
android:gravity="right"
android:id="#+id/publishdate"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:textSize="14sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/container"
android:layout_gravity="center"
android:background="#drawable/border"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.parse.ParseImageView
android:layout_margin="1dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/picture" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<LinearLayout
android:id="#+id/layoutlikes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="left"
android:layout_weight="0.5"
android:layout_gravity="center" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/likes"
>
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/numlikes"
android:text="0"
android:textSize="14sp"
android:layout_margin="#dimen/margin_16dp_sw600"
/>
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/likepic"
android:background="#drawable/like_off"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/sharelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:padding="10dp"
android:layout_weight="0.5"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_gravity="center" >
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sharepic"
android:background="#drawable/ellipsis"
/>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/division_2dp_sw_600"
android:layout_margin="#dimen/margin_16dp_sw600"
android:background="#color/loading" />
<TextView
android:layout_gravity="left"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/comment"
android:textSize= "14sp"
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_marginRight="#dimen/margin_16dp_sw600"
/>
</LinearLayout>
Your biggest performance hit is probably the code below. You should use some sort of caching rather than decoding the Bitmap each time.
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
Also, you are creating a new CustomTypography instance everytime getView() is called. I assume this class extends Typeface, in which case you could just use a single instance that gets initialised in the adapter's constructor.
Here are a couple of things:
1. in your adapter.getView() method, move the
holder = (ViewHolder)v.getTag();
to if/else scope:
if(view ==null){
//creation of viewHolder
}else{
holder = (ViewHolder)v.getTag();
}
2. There is too much code in the adapter.getView(), specially the parse query. You better call it once per item, by caching the result of query for each item in adapter. It is currently being called on every item get visible on scroll.
3. Try to reduce the count of views in your item's xml. Too many views in ListView items cause in memory leak and low performance.
4. Adding the hardwareAccelerated="true" to your activity in manifest might help.
5. Try to comment out the scroll listener, to find out if it is reducing the performance.

How to Change ListView to GridView on Button Click in android

I want to change my view listview to gridview and back gridview to listview on a button click.Here my product.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/main_linear_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/product_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:visibility="gone"/>
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1000"
android:textColor="#D64530"/>
<TextView
android:id="#+id/product_discount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="discout price"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/product_href"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:visibility="gone"/>
<RatingBar
android:id="#+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
</LinearLayout> </LinearLayout></LinearLayout>
Here My product_category.xml:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="shoppingmazza.android.catalyst.com.dynamiclayout.ProductCategory">
<!-- Header aligned to top -->
<RelativeLayout
android:id="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FILTER"
android:id="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SORT"
android:id="#+id/textView2"
android:layout_marginLeft="257dp"
android:layout_marginStart="257dp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_below="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#+id/list_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:listitem="#layout/product"/>
</LinearLayout>
</RelativeLayout>
Here My ProductCategory.java:-
public class ProductCategory extends AppCompatActivity {
private ListView listView;
ProductAdapter adapter;
ArrayList<shoppingmazza.android.catalyst.com.dynamiclayout.Product> productsList;
private int len;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_category);
new Product().execute("http://opencart.codeniques.com/shopping/?route=feed/web_api/products&category=369&key=test123$");
listView = (ListView)findViewById(R.id.list_product);
productsList = new ArrayList<shoppingmazza.android.catalyst.com.dynamiclayout.Product>();
adapter = new ProductAdapter(getApplicationContext(),R.layout.product,productsList);
listView.setAdapter(adapter);
}
public class Product extends AsyncTask<String,Void,Boolean>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(ProductCategory.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("products");
for(int i=0;i<jsonArray.length();i++){
len=jsonArray.length();
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
shoppingmazza.android.catalyst.com.dynamiclayout.Product product = new shoppingmazza.android.catalyst.com.dynamiclayout.Product();
product.setId(jsonObject1.getString("id"));
product.setName(jsonObject1.getString("name"));
product.setPrice(jsonObject1.getString("pirce"));
product.setDiscountprice(jsonObject1.getString("discountprice"));
product.setHref(jsonObject1.getString("href"));
product.setThumb(jsonObject1.getString("thumb"));
product.setRating(jsonObject1.getString("rating"));
productsList.add(product);
}
return true;
}
}catch (IOException |JSONException e){
Log.e("Error :",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Boolean aVoid) {
dialog.dismiss();
adapter.notifyDataSetChanged();
if(!aVoid){
Toast.makeText(ProductCategory.this, "Data is not Parsed", Toast.LENGTH_LONG).show();
}
else{
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),R.layout.product,productsList);
listView.setAdapter(adapter);
}
}
}
}
Here My ProductAdapter.java:-
public class ProductAdapter extends ArrayAdapter<Product> {
ArrayList<Product> productsList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ProductAdapter(Context context, int resource, ArrayList<Product> object) {
super(context, resource, object);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
productsList = object;
Resource = resource;
// this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageView=(ImageView)v.findViewById(R.id.image_product);
holder.tvId = (TextView)v.findViewById(R.id.product_id);
holder.tvName = (TextView)v.findViewById(R.id.product_name);
holder.tvPrice = (TextView)v.findViewById(R.id.product_price);
holder.tvDiscount = (TextView)v.findViewById(R.id.product_discount);
holder.tvHref = (TextView)v.findViewById(R.id.product_href);
holder.tvRating = (RatingBar)v.findViewById(R.id.rating);
v.setTag(holder);
}
else{
holder = (ViewHolder)v.getTag();
}
new DownlaoadImageTask(holder.imageView).execute(productsList.get(position).getThumb());
holder.tvId.setText(productsList.get(position).getId());
holder.tvName.setText(productsList.get(position).getName());
holder.tvPrice.setText(productsList.get(position).getPrice());
holder.tvDiscount.setText(productsList.get(position).getDiscountprice());
holder.tvHref.setText(productsList.get(position).getHref());
holder.tvRating.setNumStars(Integer.parseInt(productsList.get(position).getRating()));
return v;
}
static class ViewHolder{
public TextView tvId;
public TextView tvName;
public TextView tvPrice;
public TextView tvDiscount;
public TextView tvHref;
public ImageView imageView;
public RatingBar tvRating;
}
private class DownlaoadImageTask extends AsyncTask<String,Void,Bitmap>{
ImageView bmImage;
public DownlaoadImageTask(ImageView bmImage){
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls){
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try{
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (IOException e){
Log.e("Error", e.getMessage());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result){
bmImage.setImageBitmap(result);
}
}
}
I am new in android developing Please Help me thanks in advance!
You can add both ListView and GridView and set GridView android:visibility="gone"
<LinearLayout
android:layout_below="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#+id/list_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:listitem="#layout/product"/>
<GridView
android:id="#+id/list_productGV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
on button click change visibilty of ListView to gone and GridView to visible and vice versa
1.You can try to use GridView only and change it's columns number using gridview.setNumColumns(n);. For ListView imitation just use n = 0.
2.Another option is to use RecyclerView with GridLayoutManager.
final int gridSpanCount = 4;
mImagesGrid = (RecyclerView) findViewById(R.id.gallery);
mLayoutManager = new GridLayoutManager(this, gridSpanCount);
mImagesGrid.setLayoutManager(mLayoutManager);
mSwitch = (Button) findViewById(R.id.switch_btn);
mSwitch.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
if (mLayoutManager.getSpanCount() == gridSpanCount){
mLayoutManager.setSpanCount(1);
}
else {
mLayoutManager.setSpanCount(gridSpanCount);
}
}
}

How to move the position of Progress bar when the image loads in List View

I am loading the images one by one in Listview by running the task in back ground.I am running a progress bar until it loads fully.The position of progress is not changing when the image starts loading.I want the postion of the progressbar also to be changed when the images loads.How to do it? what am i doing wrong?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relaGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include
android:id="#+id/Master"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/activity_master_page" />
<ListView
android:id="#+id/ItemView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/Master" >
</ListView>
<ProgressBar
android:id="#+id/ItemsProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Master"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Added the code for loading image
private class testAynscTask extends AsyncTask {
#Override
protected void onPreExecute() {
TheProgressBarG = (ProgressBar) findViewById(R.id.ItemsProgressBar);
TheProgressBarG.setVisibility(View.VISIBLE);
}
protected Void doInBackground(Void... ParamsP) {
try {
POSManager aPOSManagerL = new POSManager();
ListCriteria aListCriteriaL = new ListCriteria();
ObjectInformation zItemInfoL = new ObjectInformation();
CategoryItemListG = new ObjectList();
//Get CategoryId
String zCategoryIdL = GetCategoryId();
aListCriteriaL.SearchConditionsM.AddSearchConditionWithValue("Item_Category.Id", zCategoryIdL);
Gson gsonBuilderL = new GsonBuilder().serializeNulls().create();
String zListCriteriaL = gsonBuilderL.toJson(aListCriteriaL);
//Get Category Items List
aPOSManagerL.GetCategoryItems(HttpUtil.SessionKeyM,zListCriteriaL);
DisplayMetrics zDisplayMetricsL = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(zDisplayMetricsL);
int nPreviewSizeL = zDisplayMetricsL.widthPixels / 3;
ObjectList zItemListL = HttpUtil.CategoryItemListM;
for (int countL = 0; countL < zItemListL.GetLength(); countL++) {
zItemInfoL = (ObjectInformation) zItemListL.GetObject(countL);
String zItemIdL = (String) zItemInfoL.GetValue("ID");
//Get Item Image
aPOSManagerL.GetCategoryItemImage(HttpUtil.SessionKeyM,zItemIdL, nPreviewSizeL);
zItemInfoL.SetValue("aPictureByteArrayP",HttpUtil.CategoryItemImageBytesM);
CategoryItemListG.Add(zItemInfoL);
publishProgress(countL);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... PositionP) {
ListView TheItemListViewL=(ListView) findViewById(R.id.ItemView);
TheItemListViewL.setAdapter(anImageAdapterG);
super.onProgressUpdate(PositionP);
}
#Override
protected void onPostExecute(Void ResultP) {
super.onPostExecute(ResultP);
TheProgressBarG.setVisibility(View.INVISIBLE);
anImageAdapterG.notifyDataSetChanged();
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return CategoryItemListG.GetLength();
// return mImageIds.length;
}
public Object getItem(int PositionP) {
return PositionP;
}
public long getItemId(int PositionP) {
return PositionP;
}
public View getView(int PositionP, View ConvertViewP, ViewGroup ParentP) {
ObjectInformation zItemInfoL = (ObjectInformation)CategoryItemListG.GetObject(PositionP);
String zItemNameL = (String)zItemInfoL.GetValue("ITEMNAME");
String zItemPriceL = (String)zItemInfoL.GetValue("SalesPrice");
String zItemImageBytesL = (String)zItemInfoL.GetValue("aPictureByteArrayP");
Bitmap ItemImageBitMapL =GetItemImageBitMap(zItemImageBytesL);
RelativeLayout TheRelativelayoutL = new RelativeLayout(getApplicationContext());
ImageView TheItemImageL = new ImageView(mContextL);
TheItemImageL.setImageBitmap(ItemImageBitMapL);
TheItemImageL.setScaleType(ImageView.ScaleType.FIT_XY);
TheItemImageL.setLayoutParams(new ListView.LayoutParams(100,100));
TheItemImageL.setPadding(1, 0, 0, 0);
TheItemImageL.setId(1);
TextView tvItemNameL = new TextView(mContextL);
tvItemNameL.setText(zItemNameL);
tvItemNameL.setGravity(Gravity.CENTER);
tvItemNameL.setTextSize(10);
tvItemNameL.setTextColor(Color.parseColor("#000000"));
tvItemNameL.setPadding(15, 0, 0, 0);
tvItemNameL.setId(2);
TextView tvItemPriceL = new TextView(mContextL);
tvItemPriceL.setText("Rs. "+zItemPriceL);
tvItemPriceL.setGravity(Gravity.CENTER);
tvItemPriceL.setTextSize(10);
tvItemPriceL.setTextColor(Color.parseColor("#A30000"));
tvItemPriceL.setId(3);
tvItemPriceL.setPadding(15, 0, 0, 20);
TheRelativelayoutL.addView(TheItemImageL);
RelativeLayout.LayoutParams zRelativeLayoutParamsL = new RelativeLayout.LayoutParams((RelativeLayout.LayoutParams.WRAP_CONTENT),(RelativeLayout.LayoutParams.WRAP_CONTENT));
zRelativeLayoutParamsL.addRule(RelativeLayout.RIGHT_OF,1);
zRelativeLayoutParamsL.addRule(RelativeLayout.CENTER_IN_PARENT);
TheRelativelayoutL.addView(tvItemNameL, zRelativeLayoutParamsL);
zRelativeLayoutParamsL = new RelativeLayout.LayoutParams((RelativeLayout.LayoutParams.WRAP_CONTENT),(RelativeLayout.LayoutParams.WRAP_CONTENT));
zRelativeLayoutParamsL.addRule(RelativeLayout.RIGHT_OF,1);
zRelativeLayoutParamsL.addRule(RelativeLayout.BELOW,2);
zRelativeLayoutParamsL.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
TheRelativelayoutL.addView(tvItemPriceL, zRelativeLayoutParamsL);
return TheRelativelayoutL;
}
I made the below changes to the UI and it works fine for me
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relaGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<include
android:id="#+id/Master"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/activity_master_page" />
<ListView
android:id="#+id/ItemView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/Master" >
</ListView>
<ProgressBar
android:id="#+id/ItemsProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ItemView"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Categories

Resources