Android multiple lists using #id/android:list - java

I've got a new List of things that needs to be clicked but this one isn't working. onListItemClick is never called. I have another one in my app that has been working as expected and I can't figure out what the difference is. It occurs to me that maybe there's some conflict since they are both using the provided #id/android:list but they're in different Activities and I haven't found other people complaining about the same problem so I'm not sure.
Here is a bunch of code. I would appreciate any suggestions.
Working:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
v_ProjectInvestigatorSiteContact project = (v_ProjectInvestigatorSiteContact) this.getListAdapter().getItem(
position);
Intent myIntent = new Intent(this, Details.class);
myIntent.putExtra(res.getString(R.string.project), project);
startActivity(myIntent);
}// onListItemClick
Not Working:
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// get the item that was clicked
final v_SitePeople vSitePeople = (v_SitePeople) this.getListAdapter().getItem(
position);
AlertDialog.Builder builder = new AlertDialog.Builder(Share.this);
builder.setTitle(res.getString(R.string.forgot_password_check_dialog_title))
.setMessage(res.getString(R.string.share_check_dialog_text))
.setPositiveButton(res.getString(R.string.send), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
sendShareEmail(vSitePeople);
}
}).setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// cancelled, so do nothing
}
});
AlertDialog msgBox = builder.create();
msgBox.show();
}// onListItemClick
Working 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="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/title_background" >
<ImageView
android:id="#+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="#string/app_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/search_gradient" >
<ImageView
android:id="#+id/searchBoxIcon"
android:layout_width="38dp"
android:layout_height="38dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:scaleType="centerCrop"
android:src="#drawable/action_search" >
</ImageView>
<EditText
android:id="#+id/searchBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="#+id/searchBoxIcon"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/searchBoxIcon"
android:background="#drawable/search_box"
android:hint="#string/search_hint"
android:inputType="text"
android:maxLines="1"
android:minHeight="30sp"
android:paddingBottom="2dp"
android:paddingLeft="25sp"
android:paddingTop="2dp"
android:textColor="#ff000000" />
</RelativeLayout>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="#color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/loading"
android:textColor="#color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Not Working 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="match_parent"
android:background="#ffffffff"
android:orientation="vertical" >
<!-- dummy item to prevent edittext from gaining focus on activity start -->
<LinearLayout
android:layout_width="0px"
android:layout_height="0px"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/title_background" >
<ImageView
android:id="#+id/logo"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_logo" >
</ImageView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/logo"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingLeft="50dp"
android:paddingRight="60dp"
android:paddingTop="5dp"
android:text="#string/share_header"
android:textColor="#ffffffff"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/divider_gray"
android:cacheColorHint="#00000000"
android:divider="#color/divider_gray"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" />
<TextView
android:id="#+id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/loading"
android:textColor="#color/loading_gray"
android:textSize="20sp" />
</LinearLayout>
Here is more on how the broken one works, just in case you want more code.
Not Working Row XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_weight="1"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="6dp"
android:background="#ffffffff"
android:layout_margin="10dp" >
<TextView
android:id="#+id/toptext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="#id/moreInfo"
android:gravity="center_vertical"
android:minHeight="20sp"
android:textColor="#ff000000"
android:textStyle="bold" />
</RelativeLayout>
Not Working View Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.share_row, null);
convertView.setTag(holder);
}// if
else
{
holder = (ViewHolder) convertView.getTag();
}
v_SitePeople i = items.get(position);
if (i != null)
{
TextView topText = (TextView) convertView.findViewById(R.id.toptext);
topText.setGravity(Gravity.CENTER_VERTICAL);
topText.setMinHeight(40);
if (topText != null)
{
if (i.SitePerson != null)
{
if (i.PersonTitle != null)
{
topText.setText(String.format(i.SitePerson + ", " + i.PersonTitle));
}
else
{
topText.setText(i.SitePerson);
}
}// if has ProtocolNumber
else
{
if (i.Nickname != null)
{
topText.setText(i.Nickname);
}
}// if does not have ProtocolNumber
}// if
}// if
return convertView;
}// getView
Thank you so much for your help.
More code as requested.
Working setListAdapter:
public void updateDisplay(ArrayList<v_ProjectInvestigatorSiteContact> vProjectInvestigatorSiteContactList)
{
if (fullAdapter != null)
{
if (fullAdapter.isEmpty())
{
fullAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
fullAdapter = reOrder(fullAdapter);
setListAdapter(fullAdapter);
}
else
{
filteredAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
filteredAdapter = reOrder(filteredAdapter);
setListAdapter(filteredAdapter);
}
}
else
{
fullAdapter = new ProjectAdapter(this, R.layout.row, vProjectInvestigatorSiteContactList);
fullAdapter = reOrder(fullAdapter);
setListAdapter(fullAdapter);
}
}// updateDisplay
Working list setup:
private class DownloadProjectsTask extends AsyncTask<String, Void, ArrayList<v_ProjectInvestigatorSiteContact>> {
#Override
protected ArrayList<v_ProjectInvestigatorSiteContact> doInBackground(String... URLs)
{
return ProjectsHelper.parseProjects(URLs, CurrentStudies.this);
}// doInBackground
#Override
protected void onPostExecute(ArrayList<v_ProjectInvestigatorSiteContact> vProjectInvestigatorSiteContactList)
{
updateDisplay(vProjectInvestigatorSiteContactList);
}// onPostExecute
}// DownloadProjectsTask
Working adapter:
public class ProjectAdapter extends ArrayAdapter {
private ArrayList items;
private Resources res;
public ProjectAdapter(Context context, int textViewResourceId, ArrayList<v_ProjectInvestigatorSiteContact> items)
{
super(context, textViewResourceId, items);
this.items = items;
this.res = context.getResources();
}// ProjectAdapater
#Override
public int getCount()
{
return items.size();
}
#Override
public v_ProjectInvestigatorSiteContact getItem(int position)
{
return items.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getViewTypeCount()
{
return 2;
}
#Override
public int getItemViewType(int position)
{
if (items.get(position).ProjectID == null)
{
return 0;
}
else
{
return 1;
}
}
#Override
public boolean isEnabled(int position)
{
if (getItemViewType(position) == 0)
{
return false;
}
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null)
{
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (type == 0)
{
convertView = vi.inflate(R.layout.row_header, null);
}
else
{
convertView = vi.inflate(R.layout.row, null);
}
convertView.setTag(holder);
}// if
else
{
holder = (ViewHolder) convertView.getTag();
}
v_ProjectInvestigatorSiteContact i = items.get(position);
if (i != null)
{
TextView topText = (TextView) convertView.findViewById(R.id.toptext);
TextView bottomText = (TextView) convertView.findViewById(R.id.bottomtext);
if (topText != null)
{
if (i.ProtocolNumber != null)
{
if (i.WebIndication != null)
{
topText.setText(i.ProtocolNumber);
bottomText.setText(i.WebIndication);
}
else if (i.ProjectName != null)
{
topText.setText(i.ProtocolNumber);
bottomText.setText(i.ProjectName);
}
}// if has ProtocolNumber
else
{
if (i.WebIndication != null)
{
topText.setText(i.WebIndication);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
else if (i.ProjectName != null)
{
topText.setText(i.ProjectName);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
else
{
topText.setText(i.SiteID);
topText.setMinHeight(40);
topText.setGravity(Gravity.CENTER_VERTICAL);
}
}// if does not have ProtocolNumber
}// if
// Coming Soon logic
if (i.ProjectStatusID != null)
{
if (i.ProjectStatusID.equals(res.getString(R.string.feasibility_id)))
{
topText.setTextColor(res.getColor(R.color.coming_soon_gray));
bottomText.setText("(Coming Soon)");
}
else {
topText.setTextColor(Color.BLACK);
}
}//if
if (bottomText != null)
{
if (type == 0)
{
if (position == getCount() - 1 || getItemViewType(position + 1) == 0)
{
bottomText.setVisibility(View.VISIBLE);
bottomText.setText(res.getString(R.string.no_studies));
bottomText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 0, (float) 1.0));
}
else
{
bottomText.setVisibility(View.GONE);
}
}// header followed by another header, or end of list
}// if
//recenters row headers
if (type == 0)
{
topText.setGravity(Gravity.CENTER);
}
}// if
return convertView;
}// getView
public static class ViewHolder {
public TextView textView;
}
}// ProjectAdapter
Not Working setListAdapter:
public void updateDisplay(ArrayList<v_SitePeople> vSitePeopleShareList)
{
adapter = new ShareAdapter(this, R.layout.share_row, vSitePeopleShareList);
setListAdapter(adapter);
}// updateDisplay
Not Working list setup:
private class DownloadShareTask extends AsyncTask<String, Void, ArrayList<v_SitePeople>> {
#Override
protected ArrayList<v_SitePeople> doInBackground(String... params)
{
return ProjectsHelper.getSharePeople(params[0], Share.this);
}// doInBackground
#Override
protected void onPostExecute(ArrayList<v_SitePeople> vSitePeopleShareList)
{
updateDisplay(vSitePeopleShareList);
}// onPostExecute
}// DownloadProjectsTask

I figured it out. I didn't ever post the relevant code, or I'm sure you guys would have spotted it for me.
I copied a non working adapter from a working piece of code which returns false if the viewType is 0. And since my second list only has one type, everything was disabled.
Thank you all for your efforts. I apologize that I didn't give you the correct code.

Related

ViewPager inside Dialog not showing

I have a custom dialog that has a ViewPager inside of it, when the dialog shows the ViewPager is just blank, not progressing on swipe or when pressing the "Next" button I implemented. I tried slightly altering my code and it didn't work. I saw several posts like this, but none of their solutions worked. PS if some things don't make sense or have mismatched names then that's because I renamed/removed some of the files/variables to simplify.
SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private ArrayList<String> text;
public SliderAdapter(Context context, ArrayList<String> text) {
this.context = context;
this.text = text;
}
public String[] txtH = {
"test1",
"test2",
"test3"
};
#Override
public int getCount() {
return txtH.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == (ConstraintLayout) object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_wr, container, false);
TextView txt1 = view.findViewById(R.id.txt11);
TextView txt2 = view.findViewById(R.id.txt22);
txt1.setText(txtH[position]);
txt2.setText(text.get(position));
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout) object);
}
}
Dialog itself:
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.Dialog);
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog, null);
preferences = getActivity().getSharedPreferences("label", 0);
Random random = new Random();
text.add("test1");
text.add("test2");
text.add("test3");
viewPager = view.findViewById(R.id.viewPager);
dotLayout = view.findViewById(R.id.dotLayout);
next = view.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (next.getText().toString().equals("Proceed")) {
dismiss();
} else {
viewPager.setCurrentItem(currentPage + 1);
}
}
});
back = view.findViewById(R.id.back);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(currentPage--);
}
});
builder.setView(view)
.setCancelable(true);
addDotsIndicator(0);
viewPager.setOnPageChangeListener(viewListener);
adapter = new SliderAdapter(getActivity(), text);
return builder.create();
}
private void addDotsIndicator(int position) {
dots = new TextView[3];
dotLayout.removeAllViews();
for (int i = 0; i<dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("&#8226"));
dots[i].setTextSize(35);
dots[i].setTextColor(Color.parseColor("#404040"));
dotLayout.addView(dots[i]);
}
if(dots.length > 0) {
dots[position].setTextColor(Color.BLACK);
}
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addDotsIndicator(position);
currentPage = position;
if (currentPage == 0) {
back.setEnabled(false);
next.setEnabled(true);
back.setText("");
next.setText("Next");
} else if (currentPage == 1) {
back.setEnabled(true);
next.setEnabled(true);
back.setText("Back");
next.setText("Next");
} else if (currentPage == 2) {
back.setEnabled(true);
next.setEnabled(false);
back.setText("Back");
next.setText("Proceed");
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
}
Dialog XML:
<RelativeLayout
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="wrap_content"
android:background="#drawable/dialog_bg"
app:cardCornerRadius="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/dotLayout"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:layout_margin="15dp"
android:layout_below="#+id/viewPager"
android:orientation="horizontal" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_below="#+id/viewPager"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Back"
android:textColor="#android:color/black" />
<Button
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/viewPager"
android:layout_margin="5dp"
android:background="#android:color/transparent"
android:elevation="0dp"
android:text="Next"
android:textColor="#android:color/black" />
</RelativeLayout>
ViewPager's slide layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:background="#android:color/white">
<TextView
android:id="#+id/txt11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST"
android:textColor="#android:color/black"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.24000001" />
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Test"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/txt11"
app:layout_constraintStart_toStartOf="#+id/txt11"
app:layout_constraintTop_toBottomOf="#+id/txt11"
app:layout_constraintVertical_bias="0.26" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you didn't set the ViewPager adapter
public class DialogWeeklyReport extends AppCompatDialogFragment {
...
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
viewPager = view.findViewById(R.id.viewPager);
...
adapter = new SliderAdapter(getActivity(), text);
viewPager.setAdapter(adapter); // <<<<<< change here
return builder.create();
}
...
Here is my test

Android Listview autoscroll makes items invisible

I have progress listview of progress items. Whenever the item is finished I checkmark it.
This Progress items are divided into Phases. Each phase can contain Steps. After all steps are done and marked with checkmark, code marks whole phase as done.
At the end what I do is just render a listview of phases and for each phase I dynamicly add another listview in it. I end up with listview with more listviews in it.
This works fine and I don't have any problems with it.
My boss asked me to create auto scroller which would follow the steps as being completed. This I implemented and was happy to see that It works.
Problem: I was happy that It works only to the point when the something little over of half is reached. Then suddenly items disapear. When I touch the list, List goes back to top and all the items are visible.
Any idea what could couse this behavior?
The code for this is quite large so I will share only the parts I think are needed.
//Adapters
public class ProcessFeedbackAdapter extends android.widget.BaseAdapter {
public static final String TAG = "ProcessFeedbackAdapter";
public Context appContext;
public ProgressOverviewData ProgressOverviewData;
public ListView Listview;
public int FirstNotCompletedIndex=0;
public void UpdateList(){
HotApplication.getHandler().post(new Runnable(){
#Override
public void run() {
notifyDataSetChanged();
}
});
}
public ProcessFeedbackAdapter(Context Context,ProgressOverviewData ProgressOverviewData,ListView listview){
this.appContext=Context;
this.ProgressOverviewData=ProgressOverviewData;
this.Listview=listview;
}
#Override
public int getCount() {
return ProgressOverviewData.Phases.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
public void ScrollToCurrentlyActiveTask(int y){
int listviewBottom = Listview.getBottom();
if(listviewBottom <y*50){
Listview.scrollTo(0, listviewBottom);
}
else {
Listview.scrollTo(0,y*50);
}
Listview.computeScroll();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
try {
Phase curItem = ProgressOverviewData.Phases.get(i);
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item, null);
ListView ChildList=view.findViewById(R.id.childrenList);
ViewGroup.LayoutParams params = ChildList.getLayoutParams();
int ListHeight=curItem.PhaseSteps.size()*50;
params.height=ListHeight;
ChildList.setLayoutParams(params);
TextView ProgressMessage = (TextView) view.findViewById(R.id.ProgressMessage);
ImageView Check = (ImageView) view.findViewById(R.id.CheckMark);
ImageView ErrorMark = (ImageView) view.findViewById(R.id.ErrorMark);
ProcessFeedbackChildrenAdapter ChilAdapter=new ProcessFeedbackChildrenAdapter(appContext,curItem.PhaseSteps);
ChildList.setAdapter(ChilAdapter);
int CheckVisibility = 0;
int ErrorVisibility=0;
if(curItem.Status.equals(AppEnums.StepResult.NotCompleted)){
CheckVisibility=View.INVISIBLE;
ErrorVisibility=View.INVISIBLE;
}
else if(curItem.Status.equals(AppEnums.StepResult.Completed)){
CheckVisibility=View.VISIBLE;
ErrorVisibility=View.INVISIBLE;
}
else if(curItem.Status.equals(AppEnums.StepResult.Failed)){
ErrorVisibility=View.VISIBLE;
CheckVisibility=View.INVISIBLE;
}
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
ProgressMessage.setText(curItem.PhaseName);
return view;
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
}
class ProcessFeedbackChildrenAdapter extends android.widget.BaseAdapter {
public static final String TAG = "ProcessFeedbackChildrenAdapter";
public Context appContext;
public ArrayList<Step> Steps= new ArrayList<Step>();
public void UpdateList(){
HotApplication.getHandler().post(new Runnable(){
#Override
public void run() {
notifyDataSetChanged();
}
});
}
public ProcessFeedbackChildrenAdapter(Context Context,ArrayList<Step> Steps){
this.appContext=Context;
this.Steps=Steps;
}
#Override
public int getCount() {
return Steps.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
try {
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item_children, null);
TextView ProgressMessage = (TextView) view.findViewById(R.id.ProgressMessage);
ImageView Check = (ImageView) view.findViewById(R.id.CheckMark);
ImageView ErrorMark = (ImageView) view.findViewById(R.id.ErrorMark);
Step curItem = Steps.get(i);
int CheckVisibility = 0;
int ErrorVisibility=0;
if(curItem.Status== AppEnums.StepResult.NotCompleted){
CheckVisibility=View.INVISIBLE;
ErrorVisibility=View.INVISIBLE;
}else {
if(curItem.Status== AppEnums.StepResult.Completed){
CheckVisibility=View.VISIBLE;
ErrorVisibility=View.INVISIBLE;
}
else if(curItem.Status==AppEnums.StepResult.Failed){
ErrorVisibility=View.VISIBLE;
CheckVisibility=View.INVISIBLE;
}
}
ProgressMessage.setText(curItem.StepName);
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
return view;
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
}
// Main list view
<ListView
android:id="#+id/ProgressStepsContainer"
android:layout_width="0dp"
android:layout_height="267dp"
android:fastScrollEnabled="false"
android:scrollbarThumbVertical="#drawable/scrollbar_vertical_thumb"
android:verticalScrollbarPosition="left"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/ProgressErrorContainer"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage">
</ListView>
// Phases list item
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="0dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_check" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_error" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView"
android:textAlignment="center"
android:textColor="#color/colorWhitish"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/childrenList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage" />
</androidx.constraintlayout.widget.ConstraintLayout>
// Steps (inner) list item
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
android:layout_height="50dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_check" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_overview_error" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="center"
android:text="TextView"
android:textAlignment="center"
android:textColor="#color/colorWhitish"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Your adapter code does not work in my phone. Only part of the child list is shown. In addition, I think your requirements are easier to implement by ExpandableListView. Therefore I followed your data structure and created the following demo codes which use ExpandableListView. You can start a new project and try it.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ProgressOverviewData sampleData;
ProcessFeedbackAdapter1 adapter;
ExpandableListView listView;
TextView textView;
int completedPhase = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sampleData = new ProgressOverviewData("Project", new ArrayList<Phase>());
textView = findViewById(R.id.ProgressMessage);
textView.setText(sampleData.projectName);
listView = findViewById(R.id.ProgressStepsContainer);
adapter = new ProcessFeedbackAdapter1(this, sampleData);
listView.setAdapter(adapter);
// Disable ExpandableListView from group collapse by override OnGroupClickListener.
listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
return true;
}
});
for (int i = 0; i < sampleData.Phases.size(); i++) listView.expandGroup(i);
Button btAddPhase = findViewById(R.id.bt_add_phase);
btAddPhase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Phase newPhase = genNewPhase();
sampleData.Phases.add(newPhase);
adapter.notifyDataSetChanged();
listView.expandGroup(sampleData.Phases.size() - 1);
textView.setText(sampleData.projectName + " [" + completedPhase + "/" + sampleData.Phases.size() + "]");
}
});
Button btCompletedStep = findViewById(R.id.bt_completed_step);
btCompletedStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean stepCompleted = false;
Step step;
String msg = "";
int viewPosition = 0;
for (int i = 0; i < adapter.getGroupCount(); i++) {
viewPosition++;
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
viewPosition++;
if (adapter.getChild(i, j).Status == AppEnums.StepResult.NotCompleted) {
step = adapter.getChild(i, j);
step.Status = AppEnums.StepResult.Completed;
msg = step.StepName + " Completed!";
if (j == adapter.getGroup(i).PhaseSteps.size() - 1) {
adapter.getGroup(i).Status = AppEnums.StepResult.Completed;
completedPhase++;
textView.setText(sampleData.projectName + " [" + completedPhase + "/" + sampleData.Phases.size() + "]");
msg += "\n" + adapter.getGroup(i).PhaseName + " Completed!!!!!";
}
stepCompleted = true;
break;
}
}
if (stepCompleted) break;
}
if (stepCompleted) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "All Completed", Toast.LENGTH_LONG).show();
}
listView.smoothScrollToPositionFromTop(viewPosition - 1, 0);
adapter.notifyDataSetChanged();
}
});
}
private Phase genNewPhase() {
int phaseId = sampleData.Phases.size() + 1;
Random random = new Random();
int numberOfSteps = random.nextInt(5) + 1;
ArrayList<Step> steps = new ArrayList<>();
for (int j = 0; j < numberOfSteps; j++) {
Step step = new Step("Step " + (phaseId) + "-" + (j + 1));
steps.add(step);
}
return new Phase("Phase " + (phaseId) + " [" + steps.size() + "]", steps);
}
}
ProcessFeedbackAdapter1.java:
public class ProcessFeedbackAdapter1 extends BaseExpandableListAdapter {
public static final String TAG = "ProcessFeedbackAdapter";
public Context appContext;
public ProgressOverviewData ProgressOverviewData;
public ProcessFeedbackAdapter1(Context Context, ProgressOverviewData ProgressOverviewData) {
this.appContext = Context;
this.ProgressOverviewData = ProgressOverviewData;
}
#Override
public int getGroupCount() {
return ProgressOverviewData.Phases.size();
}
#Override
public int getChildrenCount(int i) {
return ProgressOverviewData.Phases.get(i).PhaseSteps.size();
}
#Override
public Phase getGroup(int i) {
return ProgressOverviewData.Phases.get(i);
}
#Override
public Step getChild(int i, int i1) {
return ProgressOverviewData.Phases.get(i).PhaseSteps.get(i1);
}
#Override
public long getGroupId(int i) {
return 0;
}
#Override
public long getChildId(int i, int i1) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
try {
Phase curItem = getGroup(i);
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item, null);
TextView ProgressMessage = view.findViewById(R.id.ProgressMessage);
ImageView Check = view.findViewById(R.id.CheckMark);
ImageView ErrorMark = view.findViewById(R.id.ErrorMark);
int CheckVisibility = 0;
int ErrorVisibility = 0;
if (curItem.Status.equals(AppEnums.StepResult.NotCompleted)) {
CheckVisibility = View.INVISIBLE;
ErrorVisibility = View.INVISIBLE;
} else if (curItem.Status.equals(AppEnums.StepResult.Completed)) {
CheckVisibility = View.VISIBLE;
ErrorVisibility = View.INVISIBLE;
} else if (curItem.Status.equals(AppEnums.StepResult.Failed)) {
ErrorVisibility = View.VISIBLE;
CheckVisibility = View.INVISIBLE;
}
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
ProgressMessage.setText(curItem.PhaseName);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
try {
LayoutInflater inflater = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.progress_list_item_children, null);
TextView ProgressMessage = view.findViewById(R.id.ProgressMessage);
ImageView Check = view.findViewById(R.id.CheckMark);
ImageView ErrorMark = view.findViewById(R.id.ErrorMark);
Step curItem = getChild(i, i1);
int CheckVisibility = 0;
int ErrorVisibility = 0;
if (curItem.Status == AppEnums.StepResult.NotCompleted) {
CheckVisibility = View.INVISIBLE;
ErrorVisibility = View.INVISIBLE;
} else {
if (curItem.Status == AppEnums.StepResult.Completed) {
CheckVisibility = View.VISIBLE;
ErrorVisibility = View.INVISIBLE;
} else if (curItem.Status == AppEnums.StepResult.Failed) {
ErrorVisibility = View.VISIBLE;
CheckVisibility = View.INVISIBLE;
}
}
ProgressMessage.setText(curItem.StepName);
Check.setVisibility(CheckVisibility);
ErrorMark.setVisibility(ErrorVisibility);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return false;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:background="#000000"
tools:context=".MainActivity">
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Progress Messages:"
android:textColor="#F8F8F8"
android:textSize="20sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/bt_add_phase"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="20dp"
android:text="Add Phase"
app:layout_constraintRight_toLeftOf="#id/bt_completed_step"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="RtlSymmetry" />
<Button
android:id="#+id/bt_completed_step"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="20dp"
android:text="Completed Step"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="RtlSymmetry" />
<ImageView
android:id="#+id/ProgressErrorContainer"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage" />
<ExpandableListView
android:id="#+id/ProgressStepsContainer"
android:layout_width="0dp"
android:layout_height="267dp"
android:background="#000033"
android:fastScrollEnabled="false"
android:verticalScrollbarPosition="left"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/ProgressErrorContainer"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ProgressMessage" />
</androidx.constraintlayout.widget.ConstraintLayout>
progress_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="0dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/checkbox_on_background" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/ic_delete" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textAlignment="center"
android:textColor="#F8F8F8"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
progress_list_item_children.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:paddingStart="50dp"
android:layout_width="wrap_content"
android:layout_height="50dp">
<ImageView
android:id="#+id/CheckMark"
android:layout_width="50dp"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/checkbox_on_background" />
<ImageView
android:id="#+id/ErrorMark"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="visible"
app:layout_constraintStart_toStartOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/ic_delete" />
<TextView
android:id="#+id/ProgressMessage"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:gravity="center"
android:textAlignment="center"
android:textColor="#F8F8F8"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="#+id/CheckMark"
app:layout_constraintStart_toEndOf="#+id/CheckMark"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
For the classes that related to your data structure, you can copy from your original project.

Add Progress bar while data loading from database

I use volley library to get data from database i use this code
public class R_arabic extends AppCompatActivity {
RequestQueue requestQueue;
ListView listView;
ArrayList<listitem_gib> listitems = new ArrayList<listitem_gib>();
String name, img, url, num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_r_arabic);
listView = (ListView) findViewById(R.id.listView);
TextView textView_Title = (TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
String story_type = intent.getStringExtra("story_type");
switch (story_type) {
case "arabic":
textView_Title.setText("arabic");
break;
case "romance":
textView_Title.setText("romance");
break;
case "motrgm":
textView_Title.setText("motrgm");
break;
case "ro3b":
textView_Title.setText("ro3b");
break;
case "siasa":
textView_Title.setText("siasa");
break;
}
String url = "http://grassyhat.com/android/" + story_type + ".php";
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("all");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String img = respons.getString("img");
String url = respons.getString("url");
String num = respons.getString("num");
listitems.add(new listitem_gib(id, name, img, url, num));
}
} catch (JSONException e) {
e.printStackTrace();
}
listAllItme();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(R_arabic.this, "no connection", Toast.LENGTH_LONG).show();
} else {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
showad++;
if (showad >= 5) {
showad = 0;
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
i want to add progress bar while data loading to avoid blank page
sorry i'm new in android and i google for that and don't get useful answer
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.kamal.ahmed.rewaya.R_arabic"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#drawable/bg"
tools:showIn="#layout/app_bar_r_arabic">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:id="#+id/textView2" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingRight="#dimen/activity_horizontal_margin"
android:divider="#drawable/div1"
android:dividerHeight="35dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="gone">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
Add progressBar in your activity_r_arabic
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
add ProgessBar progressBar; as global variable in your activity
and initialise it as
progressBar = (ProgessBar) findViewById(R.id.progress_bar);
and then In onResponse(JSONObject response) method add following line
progressBar.setVisibility(View.GONE)
EDIT
Make your linearLayout visible in xml
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/progress_layout"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginBottom="60dp"
android:layout_weight="1"/>
<TextView
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress_txt"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#e873400c"
android:layout_gravity="center"
android:layout_marginRight="90dp"
android:layout_marginBottom="60dp"
android:layout_weight="1" />
</LinearLayout>
and inside onResponse(JSONObject response) method add following line
progress_layout.setVisibility(View.GONE)

Android - add header to table row (ArrayAdapter)

I have one app that creates a table row from an adapter.Here the adapter:
public class TableAdapter extends ArrayAdapter<Table> {
public TableAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public TableAdapter(Context context, int resource, List<Table> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_table, parent, false);
holder.position = (TextView) convertView.findViewById(R.id.position);
holder.progress = (ProgressBar) convertView.findViewById(R.id.progress);
holder.image = (ImageView) convertView.findViewById(R.id.image);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.points = (TextView) convertView.findViewById(R.id.points);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position != 0) {
convertView.findViewById(R.id.header).setVisibility(View.GONE);
}
holder.position.setText(String.valueOf(getItem(position).getPosition()));
holder.image.setVisibility(View.GONE);
holder.progress.setVisibility(View.VISIBLE);
holder.name.setText(getItem(position).getName());
holder.points.setText(String.valueOf(getItem(position).getPoints()));
final ViewHolder tmp = holder;
Picasso.with(getContext()).load(getContext().getResources().getString(R.string.team_logo) + getItem(position).getId() + ".png").into(holder.image, new Callback() {
#Override
public void onSuccess() {
tmp.progress.setVisibility(View.GONE);
tmp.image.setVisibility(View.VISIBLE);
}
#Override
public void onError() {
}
});
return convertView;
}
class ViewHolder {
TextView position;
ProgressBar progress;
ImageView image;
TextView name;
TextView points;
}
}
and the layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/position"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/imgHolder"
android:layout_width="50dp"
android:layout_height="50dp" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:indeterminate="true"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/points"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
So far everything is working great as expected.
But I would like to add an header to the table.
Something like:
# | Name | Pts
I tried to add this in the layout, and check if the position != 0 and set the visibility to GONE, but the problem is when I scroll down and up it disappears.
My question is: How can I add and header to this table?
Or add this header fixed, and everything else scrollable?
In your adapter, add these two method overrides:
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return position == 0 ? 0 : 1;
}
This tells the adapter that you have two types of row layout, and which rows have each type.

UIL LinearBackground image not working

I've spent half day reading documentation and examples. I can't find a solution.
I've a ListView in an Activity, each item has LinearLayout with a background image loaded with Android-Universal-Image-Loader by nostr13.
I use this library to put a LinearBackground image as a background. In my Activity I download a JSON, parsing and creating a String array with the URIs.
The problem is the print done by the library is wrong! It works fine with ImageView but if I use LinearBackground with loadImage() intestead of displayImage() it doesn't put correctly the backgrounds. The procees seen at slow motion is like: create the right number of elements (4), place the first loaded image as background of one row, then once another image is loaded the library replaces the old background with this new image, different, then it places another image and stop. This is an example of the bug. It's always different!!! Some of them are empty but the onLoadingComplete event is called. I thought it was a problem of cache and I've played with the UIL's options without luck. Images are just 4 and very small (<10kb each).
I set the adapter in the onPostExecute event, is it ok?
What can be the problem?
Here the important code:
The Activity code (i've removed not relevant code to help to find the problem):
public class myActivity extends Activity {
Context context;
// Output Vars
String mStrings[];
ListView listView;
// UIL
DisplayImageOptions options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_left);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_stagioni);
listView = (ListView) findViewById(R.id.listView);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.fail)
.showImageOnFail(R.drawable.fail)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.build();
startAsynkTask(context);
}
public void startAsynkTask(final Context context) {
AsyncTask<String, Void, Void> task = new AsyncTask<String, Void, Void>() {
private ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(ActivityStagioni.this);
pd.setTitle(getResources().getString(R.string.dialog_loading));
pd.setMessage(getResources().getString(R.string.dialog_loading_stagioni));
pd.setCancelable(true);
pd.setCanceledOnTouchOutside(true);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(String... arg0) {
//... Not relevant code ...
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
((ListView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener()
{
//... Not relevant code ...
});
}
};
task.execute();
}
public class ImageAdapter extends BaseAdapter {
ImageLoader imageLoader;
public ImageAdapter() {
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.stagioni_item, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (LinearLayout) view.findViewById(R.id.linearLayoutLocandina);
holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
imageLoader.loadImage(mStrings[position], new SimpleImageLoadingListener() {
//final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
//if (loadedImage != null) {
// boolean firstDisplay = !displayedImages.contains(imageUri);
// if (firstDisplay) {
BitmapDrawable background = new BitmapDrawable(loadedImage);
holder.imageView.setBackgroundDrawable(background);
//}
// }
}
});
return view;
}
The ListView item is:
<?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="match_parent"
android:background="#color/black"
android:orientation="horizontal"
android:weightSum="5"
android:baselineAligned="false">
<LinearLayout
android:id="#+id/linearLayoutLocandina"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_margin="0dp"
android:layout_weight="1"
android:background="#drawable/ic_launcher"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="25dp"
android:layout_weight="5" >
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="25dp"
android:layout_weight="5"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0"
android:alpha="1"
android:background="#80000000" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_NumeroStagione"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="bottom|center_horizontal"
android:text="30"
android:textColor="#color/white"
android:textSize="25sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_NomeStagione"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_weight="0"
android:text="TextView"
android:textColor="#color/white" />
<TextView
android:id="#+id/textView_NumeroEpisodi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="TextView"
android:textColor="#color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_objectID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="100"
android:layout_gravity="bottom"
style="#style/ProgressBarStyle" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Application
public class MyAppName extends Application {
#Override
public void onCreate() {
super.onCreate();
initImageLoader(getApplicationContext());
}
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
}
Logcat
http://pastebin.com/JejB8miC
Thanks for support
Add this ImageAware into your project:
public class BgImageAware implements ImageAware {
public static final String WARN_CANT_SET_DRAWABLE = "Can't set a drawable into view. You should call ImageLoader on UI thread for it.";
public static final String WARN_CANT_SET_BITMAP = "Can't set a bitmap into view. You should call ImageLoader on UI thread for it.";
protected Reference<View> viewRef;
protected boolean checkActualViewSize;
public BgImageAware(View view) {
this(view, true);
}
public BgImageAware(View view, boolean checkActualViewSize) {
this.viewRef = new WeakReference<View>(view);
this.checkActualViewSize = checkActualViewSize;
}
#Override
public int getWidth() {
View view = viewRef.get();
if (view != null) {
final ViewGroup.LayoutParams params = view.getLayoutParams();
int width = 0;
if (checkActualViewSize && params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT) {
width = view.getWidth(); // Get actual image width
}
if (width <= 0 && params != null) width = params.width; // Get layout width parameter
return width;
}
return 0;
}
#Override
public int getHeight() {
View view = viewRef.get();
if (view != null) {
final ViewGroup.LayoutParams params = view.getLayoutParams();
int height = 0;
if (checkActualViewSize && params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
height = view.getHeight(); // Get actual image height
}
if (height <= 0 && params != null) height = params.height; // Get layout height parameter
return height;
}
return 0;
}
#Override
public ViewScaleType getScaleType() {
return ViewScaleType.CROP;
}
#Override
public View getWrappedView() {
return viewRef.get();
}
#Override
public boolean isCollected() {
return viewRef.get() == null;
}
#Override
public int getId() {
View view = viewRef.get();
return view == null ? super.hashCode() : view.hashCode();
}
#Override
public boolean setImageDrawable(Drawable drawable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
View view = viewRef.get();
if (view != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(drawable);
} else {
view.setBackgroundDrawable(drawable);
}
return true;
}
} else {
L.w(WARN_CANT_SET_DRAWABLE);
}
return false;
}
#Override
public boolean setImageBitmap(Bitmap bitmap) {
if (Looper.myLooper() == Looper.getMainLooper()) {
View view = viewRef.get();
if (view != null) {
Drawable drawable = bitmap == null ? null : new BitmapDrawable(view.getResources(), bitmap);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(drawable);
} else {
view.setBackgroundDrawable(drawable);
}
return true;
}
} else {
L.w(WARN_CANT_SET_BITMAP);
}
return false;
}
}
And then wrap your LinearLayout into it and pass to displayImage(...) method:
ImageAware imageAware = new BgImageAware(holder.imageView);
imageLoader.displayImage(mStrings[position], imageAware);

Categories