After i click "more" button, it suppose will extend the listview from 10 to 20.
However after clicked, the list view did not extend and remain original size.
It only can keep the position of scroll bar. This is half of what i need.
newsid = new int[webservice.news.size()];
title = new String[webservice.news.size()];
date = new String[webservice.news.size()];
imagepath = new String[webservice.news.size()];
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter = new CustomAdapter_ParticularCategoryAllNews(this, title,
date, imagepath);
lv.addFooterView(footermore);
if (constant.isOnline()) {
lv.addFooterView(constant.AdMob());
}
TextView titletext = (TextView) findViewById(R.id.text_pagetitle);
titletext.setText(pagetitletext.toString());
lv.setAdapter(adapter);
This is call when launch activity.
btnmore.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter.setTitle(title);
adapter.setDate(date);
adapter.setImagepath(imagepath);
position = lv.getFirstVisiblePosition();
lv.smoothScrollToPosition(position);
adapter.notifyDataSetChanged();
This is what i call after i click "more button". However the list did not extend from 10 to 20 items.
public class CustomAdapter_ParticularCategoryAllNews extends BaseAdapter {
private Activity activity;
private String[] title, date, imagepath;
private static LayoutInflater inflater = null;
private ImageLoader_Loader imageLoader;
private WindowManager wm = null;
private Display display;
private Config_ConstantVariable constant;
public CustomAdapter_ParticularCategoryAllNews(Activity a, String[] title,
String[] date, String[] imagepath) {
activity = a;
this.title = title;
this.date = date;
this.imagepath = imagepath;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
imageLoader = new ImageLoader_Loader(activity.getApplicationContext());
constant = new Config_ConstantVariable(activity);
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.main_particularcategoryallnewslist,
parent, false);
LinearLayout linear = (LinearLayout) vi.findViewById(R.id.layout_image);
ImageView imageview = (ImageView) vi
.findViewById(R.id.image_categoryallnewstitle);
TextView titletext = (TextView) vi
.findViewById(R.id.text_categoryallnewstitle);
TextView datetext = (TextView) vi.findViewById(R.id.text_newsdate);
if (!imagepath[position].toString().equals("no picture")) {
imageview.setVisibility(View.VISIBLE);
linear.setVisibility(View.VISIBLE);
imageLoader.DisplayImage(imagepath[position], imageview);
} else {
imageview.setVisibility(View.GONE);
imageview.setImageDrawable(null);
linear.setVisibility(View.GONE);
display = wm.getDefaultDisplay();
int screenWidth = display.getWidth();
titletext.setWidth(screenWidth);
}
if (constant.getscreenresolution() >= 800 && constant.ScreenOrientation() == 1) {
titletext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
datetext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20);
}
titletext.setText(title[position].toString());
datetext.setText(date[position].toString());
return vi;
}
}
This is the CustomAdapter class.
In your adapter add:
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
When the more button is pressed call the three methods above with arrays containing 20 objects. Then call notifyDataSetChanged on your adapter.
Update:
This is working for me:
Activity:
public class HelpProjectActivity extends Activity {
private ArrayList<Item> items;
private boolean extend = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createArray();
ListView lv = (ListView)findViewById(R.id.list);
lv.setAdapter(new HelpListAdapter());
}
private void createArray() {
items = new ArrayList<Item>();
for(int i = 0; i < 20; i++) {
Item item = new Item();
item.title = "Title " + i;
item.subtitle = "Subtitle " + i;
item.image = "default";
items.add(item);
}
}
public void morePressed(View v) {
extend = !extend;
Button b = (Button) findViewById(R.id.button);
b.setText(extend ? R.string.less_button : R.string.more_button);
ListView lv = (ListView)findViewById(R.id.list);
((BaseAdapter)lv.getAdapter()).notifyDataSetChanged();
}
private class HelpListAdapter extends BaseAdapter {
#Override
public int getCount() {
if (extend) {
return items.size();
}
return items.size()/2;
}
#Override
public Object getItem(int pos) {
return items.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = View.inflate(getApplicationContext(), R.layout.litst_item, null);
}
Item item = items.get(pos);
TextView titleText = (TextView) v.findViewById(R.id.list_item_title);
titleText.setText(item.title);
TextView subtitleText = (TextView) v.findViewById(R.id.list_item_subtitle);
subtitleText.setText(item.subtitle);
ImageView image = (ImageView) v.findViewById(R.id.list_image);
if (item.image.equalsIgnoreCase("default")) {
image.setImageResource(R.drawable.default_list_image);
} else {
// what ever
}
return v;
}
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:onClick="morePressed"
android:text="#string/more_button" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/list_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_gravity="center_vertical"
android:contentDescription="#string/list_image" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/list_item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/list_item_subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="italic" />
</LinearLayout>
</LinearLayout>
Item.java:
public class Item {
String image;
String title;
String subtitle;
}
adapter.notifyDataSetChanged(); try this
Related
I am trying to build a listview which contains outlet address in 5 lines,along with a status indicator image and a button. The following is the functionality I am trying to build.
When the list text is clicked - I want to open a activity.
When the button (COMP) is clicked - I want to open a different activity.
The image (tickmark) is a status indicator to inform the user whether the activity in a outlet is complete or not.
The list is populated from a SqliteDatabase. On clicking the button, I want to take the reference of the outlet and show different attributes of the outlet.
How do I integrate the button into the list view.
I have written the following code so far:
LISTVIEW.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"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewFlag"
android:layout_rowSpan="2"
android:layout_width="25dp"
android:layout_height="25dp"
android:scaleType="fitXY"
android:layout_marginTop="20dp"
android:foregroundGravity="center"
android:layout_gravity="center"
android:background="#drawable/compliance_foreground"
android:layout_row="0"
android:layout_column="0" />
<Button
android:id="#+id/complianceButton"
android:layout_width="70dp"
android:layout_height="35dp"
android:text="COMP"
android:textSize="12sp"
></Button>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="5dp"
>
<TextView
android:id="#+id/tvOutletNamealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Outlet :"
android:textSize="15sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#04031A"
android:textAllCaps="true"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress1alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address1 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="1"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress2alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address2 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="2"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletCityalt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="3"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletPhonealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PhoneNumber :"
android:textSize="13sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="4"
android:layout_column="1" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class show_outlets_alt extends AppCompatActivity {
SQLiteHelper sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
AltOutletAdapter listAdapterOutlets ;
String lati;
String longi;
String projectName;
String usrname;
Button cButton;
ListView LISTVIEWOUTLETS;
ArrayList<String> Id_Array;
ArrayList<String> OutletName_Array;
ArrayList<String> OutletAddress1_Array;
ArrayList<String> OutletAddress2_Array;
ArrayList<String> City_Array;
ArrayList<String> Phone_Array;
ArrayList<String> ListViewClickItemArrayOutlets = new ArrayList<String>();
private String projectID;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_show_outlets_alt );
// Set toolbar for this screen
Toolbar sectoolbar = (Toolbar) findViewById( R.id.secondary_toolbar );
sectoolbar.setTitle("");
sectoolbar.setBackground(new ColorDrawable(getResources().getColor(R.color.primary_welcome_color)));
TextView main_title = (TextView) findViewById(R.id.secondary_toolbar_title);
main_title.setText("PROJECT LOCATIONS");
main_title.setTextColor( this.getResources().getColor( R.color.white ) );
setSupportActionBar( sectoolbar );
usrname = SaveSharedPreference.getUserName( show_outlets_alt.this );
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
LISTVIEWOUTLETS = this.findViewById( R.id.listView2alt );
imageView = this.findViewById( R.id.imageViewFlag );
cButton = findViewById( R.id.complianceButton );
Id_Array = new ArrayList<>();
OutletName_Array = new ArrayList<>();
OutletAddress1_Array = new ArrayList<>();
OutletAddress2_Array = new ArrayList<>();
City_Array = new ArrayList<>();
Phone_Array = new ArrayList<>();
sqLiteHelper = new SQLiteHelper(this);
LISTVIEWOUTLETS.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
projectName = SaveSharedPreference.getProjName( show_outlets_alt.this );
String outletName = ListViewClickItemArrayOutlets.get(position).toString();
SaveSharedPreference.setOutletName( getApplicationContext(),outletName );
Intent intent = new Intent(getApplicationContext(), ShowOutletParams.class);
startActivityForResult( intent,1 );
}
} );
} //end of oncreate
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult( requestCode, resultCode, data );
if (resultCode == RESULT_OK) {
Intent refresh = new Intent( this, ShowDataActivity.class );
startActivityForResult(refresh,1);
this.finish();
}
}
#Override
protected void onResume() {
ShowSQLiteOutletdata();
super.onResume();
}
private void ShowSQLiteOutletdata() {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteHelper.TABLE_NAME1+" where pid = (select projectId from "+SQLiteHelper.TABLE_NAME+ " where ProjectName = '"+projectID+"'"+") and Status=1;", null);
Id_Array.clear();
OutletName_Array.clear();
OutletAddress1_Array.clear();
OutletAddress2_Array.clear();
City_Array.clear();
Phone_Array.clear();
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Id_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_ID)));
ListViewClickItemArrayOutlets.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletName_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletAddress1_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress1)));
OutletAddress2_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress2)));
City_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_city)));
Phone_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_phone)));
} while (cursor.moveToNext());
}
}
listAdapterOutlets = new AltOutletAdapter(show_outlets_alt.this,
Id_Array,
OutletName_Array,
OutletAddress1_Array,
OutletAddress2_Array,
City_Array,
Phone_Array
);
LISTVIEWOUTLETS.setAdapter(listAdapterOutlets);
cursor.close();
} //end of ShowSqliteOutletData
#Override
public void onBackPressed() {
super.onBackPressed();
Intent backIntent = new Intent(getApplicationContext(), ShowDataActivity.class);
startActivity(backIntent);
}
}//end of public class
AltOutletAdapter.java
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
}
}
first I have question.
why don't you make Model for Items?
Anyway if you want to make click event by element, just add click listener in your adapter.
so Example is here
add id in your whole layout.
( android:id="#+id/layout" )
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants">
...
add click listener in your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone, AltOutletClickListener listener) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you call adapter in java, add click event as params.
ArrayList<String> test = new ArrayList<>();
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, test, test, test, test, test, test, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});
I just tested and use this.
But I think make Model is better.
ArrayList<String> test = new ArrayList<>();
ArrayList<Model> test = new ArrayList<>(); // it is better
**UPDATE : make Model **
simply, I make your Model Example.
make Model file.
public class AltOutlet {
private String name;
private String address1;
private String address2;
private String city;
private String phone;
public AltOutlet(String name, String address1, String address2, String city, String phone) {
this.name = name;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
change your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<AltOutlet> altOutletArrayList;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<AltOutlet> altOutletList, AltOutletClickListener listener) {
this.context = context;
altOutletArrayList = altOutletList;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return altOutletArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(altOutletArrayList.get(position).getName());
holder.O_Address1.setText(altOutletArrayList.get(position).getAddress1());
holder.O_Address2.setText(altOutletArrayList.get(position).getAddress2());
holder.City.setText(altOutletArrayList.get(position).getCity());
holder.Phone.setText(altOutletArrayList.get(position).getPhone());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you add item in java file, use Model
AltOutlet altOutlet = new AltOutlet("test", "address1", "address2", "city", "phone");
altOutlets.add(altOutlet);
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, altOutlets, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});
i using two expandable height grid view inside scroll view.i have facing this issue.when set dynamic texts in text view the grid view shows like below image.how to solve this issue?.when set static text in textview it view perfect.but using dynamic i got a issue.how can i fix it?
my layout code :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="#dimen/SIZE_5"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
>
<ImageView
android:id="#+id/iv_sub_categories_img"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.9"
android:layout_gravity="center"
android:gravity="center"
android:src="#drawable/download"
android:contentDescription="#null" />
<TextView
android:id="#+id/tv_sub_categories_name"
style="#android:style/TextAppearance.Small"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.1"
android:padding="#dimen/SIZE_5"
android:layout_gravity="center"
android:gravity="center"
android:text="hello world"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
My java code :
public class MyFragment extends Fragment implements View.OnClickListener {
private AQuery mAQuery;
private TransparentProgressDialog mTransparentProgressDialog;
private ExpandableHeightGridView mGridViewCategory, mGridViewProdcuts;
private CustomTextView mTvNoData;
private ArrayList<HomeSubCategoriesData> mArrayList;
private ArrayList<HomeSubProductsData> mArrayProductsList;
private String mSubCategoryGetDetails = "";
private TextView mTvTitle, mTvBack, mTvProductTitle;
private ScrollView mLinear;
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_seller_sub_category, container, false);
initialization(v);
return v;
}
private void initialization(View v) {
/* MainActivity dashboard = (MainActivity) getActivity();
mainDashbordInterface = dashboard.mainDashbordInterface;
mainDashbordInterface.setListener();*/
mAQuery = new AQuery(getActivity());
mTransparentProgressDialog = new TransparentProgressDialog(getActivity(), R.drawable.ic_loader_image);
mGridViewCategory = (ExpandableHeightGridView) v.findViewById(R.id.grid_fragment_sub_category);
mGridViewProdcuts = (ExpandableHeightGridView) v.findViewById(R.id.grid_fragment_sub_products);
mTvNoData = (CustomTextView) v.findViewById(R.id.tv_no_data_grid_home_sub_seller);
mTvTitle = (TextView) v.findViewById(R.id.tv_sub_category_title);
mTvProductTitle = (TextView) v.findViewById(R.id.tv_seller_sub_categories_product_title);
mTvBack = (TextView) v.findViewById(R.id.tv_sub_category_back);
mLinear = (ScrollView) v.findViewById(R.id.linear_seller_sub_category);
mArrayList = new ArrayList<>();
mArrayProductsList = new ArrayList<>();
mTransparentProgressDialog.show();
mLinear.setVisibility(View.INVISIBLE);
//auto fit column items in grid view
/* float scaleFactor = getResources().getDisplayMetrics().density * 100;
int number = getActivity().getWindowManager().getDefaultDisplay().getWidth();
int columns = (int) ((float) number / (float)scaleFactor);
mGridViewCategory.setNumColumns(columns);
mGridViewProdcuts.setNumColumns(columns);*/
getSubCategoriesData();
mGridViewCategory.setExpanded(true);
mGridViewProdcuts.setExpanded(true);
//before change below line : ajaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
AbstractAjaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
int newConfig = getActivity().getResources().getConfiguration().orientation;
mGridViewCategory.setNumColumns(newConfig == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
mGridViewProdcuts.setNumColumns(newConfig == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
mTvBack.setOnClickListener(this);
}
private void getSubCategoriesData() {
mSubCategoryGetDetails = getString(R.string.WS_HOST) + getString(R.string.WS_GET_CATEGORIES);
//mSubCategoryGetDetails = "http://www.json-generator.com/api/json/get/ckJkJopOdK?indent=2";
// mSubCategoryGetDetails = "http://www.json-generator.com/api/json/get/bSrFHjWEXS?indent=2";
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("order_id", getActivity().getIntent().getStringExtra("key"));
hashMap.put("seller_id", 266);
hashMap.put("category_id", getArguments().getString("id"));
Log.e("Categories list", "Hah map-->" + hashMap.toString());
if (AvailableNetwork.isConnectingToInternet(getActivity())) {
mAQuery./*progress(mTransparentProgressDialog).*/ajax(mSubCategoryGetDetails, hashMap, JSONObject.class, ajaxCallback);
} else {
//showAlert(getString(R.string.no_internt_connection), -1);
Snackbar snackbar = Snackbar
.make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
//setUI(view);
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
params.gravity = Gravity.TOP;
sbView.setLayoutParams(params);
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
mTvNoData.setVisibility(View.VISIBLE);
}
}
/*8SHow alert dialog box**/
private void showAlert(String message, int flg) {
AlertDialog.Builder aBuilder = new AlertDialog.Builder(getActivity());
aBuilder.setCancelable(false);
aBuilder.setMessage(message);
aBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
aBuilder.create();
aBuilder.show();
}
/*8Web service Rrespoce**/
AjaxCallback<JSONObject> ajaxCallback = new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
super.callback(url, object, status);
Log.e("buyer order", "url" + url);
Log.e("Buyer order", "Responce" + object);
if (status.getCode() == 200) {
if (object != null) {
if (url.equalsIgnoreCase(mSubCategoryGetDetails)) {
try {
if (object.getString("errorcode").equalsIgnoreCase("0")) {
JSONObject jsonObject = object.getJSONObject("category");
JSONArray jsonArrayParent = jsonObject.getJSONArray("parentcategory");
Gson gson = new Gson();
mTvBack.setVisibility(View.VISIBLE);
for (int i = 0; i < jsonArrayParent.length(); i++) {
JSONObject Object = jsonArrayParent.getJSONObject(i);
mTvTitle.setText(Object.getString("name"));
mTvProductTitle.setText(mTvTitle.getText().toString() + " Products");
// mainDashbordInterface.setTitle(Object.getString("name"));
}
JSONArray jsonArray = jsonObject.getJSONArray("childcategory");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
HomeSubCategoriesData subCategoriesModel = gson.fromJson(obj.toString(), HomeSubCategoriesData.class);
mArrayList.add(subCategoriesModel);
}
JSONArray jsonArray1 = jsonObject.getJSONArray("productdetails");
mTvProductTitle.setVisibility(View.VISIBLE);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject obj = jsonArray1.getJSONObject(i);
HomeSubProductsData subProductModel = gson.fromJson(obj.toString(), HomeSubProductsData.class);
mArrayProductsList.add(subProductModel);
}
} else if (object.getString("errorcode").equalsIgnoreCase("1")) {
showAlert("No order details found.", -1);
} else if (object.getString("errorcode").equalsIgnoreCase("0")) {
}
} catch (JSONException e) {
e.printStackTrace();
}
HorizontalSubCatAdapter adapter = new HorizontalSubCatAdapter(getActivity(), mArrayList);
mGridViewCategory.setAdapter(adapter);
HorizontalSubProductAdapter productAdapter = new HorizontalSubProductAdapter(getActivity(), mArrayProductsList);
mGridViewProdcuts.setAdapter(adapter);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mLinear.setVisibility(View.VISIBLE);
mTransparentProgressDialog.dismiss();
Log.e("progress bar", "Hah map-->" + "progress bar called");
}
}, 3000);
}
} else {
mTvNoData.setVisibility(View.VISIBLE);
}
}
}
};
#Override
public void onConfigurationChanged(Configuration newConfig) {
mGridViewCategory.setNumColumns(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
mGridViewProdcuts.setNumColumns(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
/* float scaleFactor = getResources().getDisplayMetrics().density * 100;
int number = getActivity().getWindowManager().getDefaultDisplay().getWidth();
int columns = (int) ((float) number / (float)scaleFactor);
mGridViewCategory.setNumColumns(columns);
mGridViewProdcuts.setNumColumns(columns);*/
super.onConfigurationChanged(newConfig);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_sub_category_back:
getActivity().onBackPressed();
mTvBack.setVisibility(View.GONE);
break;
}
}
#Override
public void onResume() {
super.onResume();
}
}
my Adapter class :
public class HorizontalSubCatAdapter extends BaseAdapter {
private ArrayList<HomeSubCategoriesData> mArrayList;
private Context mContext;
private LayoutInflater mLayoutInflater;
public HorizontalSubCatAdapter(FragmentActivity activity, ArrayList<HomeSubCategoriesData> mArrayList) {
this.mContext = activity;
this.mArrayList = mArrayList;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mArrayList.size();
}
#Override
public Object getItem(int position) {
return mArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
mViewHolder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.item_subcategories_list, parent,false);
mViewHolder.mTvName = (TextView) convertView.findViewById(R.id.tv_sub_categories_name);
mViewHolder.mIvimage = (ImageView) convertView.findViewById(R.id.iv_sub_categories_img);
mViewHolder.mIvimage.setAdjustViewBounds(true);
mViewHolder.mIvimage.setPadding(10,10,10,10);
convertView.setFocusableInTouchMode(true);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
Picasso.with(mContext).load(mArrayList.get(position).getCat_img()).resize(300,300).into(mViewHolder.mIvimage);
mViewHolder.mTvName.setText(mArrayList.get(position).getName());
/*String img = "http://app.joinerytrade.com/media/catalog/product/cache/1/small_image/210x/9df78eab33525d08d6e5fb8d27136e95/4/0/400_1_door_01.jpg";
Picasso.with(mContext).load(img).into(mViewHolder.mIvimage);*/
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(mContext, mArrayList.get(position).getName(), Toast.LENGTH_SHORT).show();
//calling fragment from adatper class...
SubCategoryProductsFragment fragment = new SubCategoryProductsFragment();
FragmentManager fm = ((MainActivity) mContext).getSupportFragmentManager();
Bundle bundle = new Bundle();
bundle.putString("id", String.valueOf(mArrayList.get(position).getId()));
fragment.setArguments(bundle);
fm.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();
}
});
return convertView;
}
private class ViewHolder {
TextView mTvName;
ImageView mIvimage;
}
}
use this one:
<LinearLayout
android:id="#+id/dashrowlin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/dashImg"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:layout_marginTop="15dp"
/>
<TextView
android:id="#+id/dashName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:gravity="center"
android:padding="7dp"
android:maxLines="2"
android:lines="2"
android:ellipsize="end"
android:textColor="#color/colorPrimary"
android:textSize="14sp" />
</LinearLayout>
i am create a list view for audio files there is listView is not showing data
only showing images 3 time not showing a audio i dont know where i am doing wrong please help me...
ListActivity
public class MainActivity extends Activity {
Cursor c;
int index;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.audio_list);
String cols[] = {MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA
};
c = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols, null, null, null);
String imagePath = Environment.getExternalStorageDirectory() + "/audio/recording.3gp`";
File f=new File(imagePath);
Uri uri = Uri.fromFile(f);
List<String> data = new ArrayList<String>();
for (int i = 0; i < c.getColumnCount(); i++){
data.add(String.valueOf(f));
}
CustomAdapter customAdapter = new CustomAdapter(this,data);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
}
Adapter
public class CustomAdapter extends BaseAdapter {
private final Context context;
private final List<String> items;
private final Map<View, Map<Integer, View>>
cache = new HashMap<View, Map<Integer, View>>();
public CustomAdapter(Context context, List<String> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tv;
ImageView iv;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item, parent, false);
}
Map<Integer, View> itemMap = cache.get(v);
if (itemMap == null) {
itemMap = new HashMap<Integer, View>();
tv = (TextView) v.findViewById(android.R.id.text1);
iv = (ImageView) v.findViewById(R.id.imageView);
itemMap.put(android.R.id.text1, tv);
itemMap.put(R.id.imageView, iv);
cache.put(v, itemMap);
} else {
tv = (TextView) itemMap.get(android.R.id.text1);
iv = (ImageView) itemMap.get(R.id.imageView);
}
final String item = (String) getItem(position);
tv.setText(item);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,
String.format("Image clicked: %s", item),
Toast.LENGTH_SHORT).show();
}
});
return v;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_width="match_parent" />
itm.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical">
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:id="#android:id/text1"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ImageView android:src="#mipmap/ic_launcher"
android:layout_width="wrap_content"
android:id="#+id/imageView"
android:layout_height="wrap_content"
android:clickable="true" />
You have not initialize any data to List "data"
You have to initialize data inside the for loop.
List<String> data = new ArrayList<String>();
for (int i = 0; i < c.getColumnCount(); i++){
}
CustomAdapter customAdapter = new CustomAdapter(this,data);
Edit:
Replace the for loop with the code bellow
if (c!=null && c.moveToFirst()) {
do{
String audio_name_with_path = c.getString(2).toString();
data.add(audio_name_with_path);
}while(c.moveToNext());
}
need your help with slow scrolling in ListView. When I run my app and scrolling ListView it doing very slow with breaks.
Here's my logcat:
07-07 14:27:17.682 30190-30190/com.nadolskiy.sergey.githubreader I/Choreographer﹕ Skipped 75 frames! The application may be doing too much work on its main thread.
07-07 14:27:22.550 30190-30190/com.nadolskiy.sergey.githubreader I/Choreographer﹕ Skipped 92 frames! The application may be doing too much work on its main thread.
07-07 14:27:30.116 30190-30190/com.nadolskiy.sergey.githubreader I/Choreographer﹕ Skipped 104 frames! The application may be doing too much work on its main thread.
07-07 14:27:32.023 30190-30190/com.nadolskiy.sergey.githubreader I/Choreographer﹕ Skipped 111 frames! The application may be doing too much work on its main thread.
07-07 14:27:33.828 30190-30190/com.nadolskiy.sergey.githubreader I/Choreographer﹕ Skipped 100 frames! The application may be doing too much work on its main thread.
custom_listview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="0.2"
android:orientation="vertical">
<TextView
android:id="#+id/custom_listview_tv_repositoryName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Github-Reader"
android:textSize="20dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/custom_listview_tv_languageLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Language: "
android:textSize="14dp" />
<TextView
android:id="#+id/custom_listview_tv_language"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:textSize="14dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="0.4"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/custom_listview_tv_branchCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="15"
android:textSize="20dp"
android:layout_weight="0.5"
android:gravity="right" />
<ImageView
android:id="#+id/custom_listview_iv_branch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_branch"
android:layout_weight="0.5" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="0.4"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/custom_listview_tv_inFavoriteCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="31"
android:textSize="20dp"
android:layout_weight="0.5"
android:gravity="right" />
<ImageView
android:id="#+id/custom_listview_iv_favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_star"
android:layout_weight="0.5" />
</LinearLayout>
</LinearLayout>
CustomAdapter.java
public class CustomAdapter extends BaseAdapter implements DialogInterface.OnClickListener {
private Activity activity;
private ArrayList data;
private static LayoutInflater inflater = null;
public Resources res;
ListModel tempValues = null;
int i = 0;
Typeface textFont;
public CustomAdapter(Activity a, ArrayList d, Resources resLocal) {
activity = a;
data = d;
res = resLocal;
textFont = Typeface.createFromAsset(activity.getAssets(), "fonts/DiamondGirl.ttf");
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView repositoryName;
public TextView language;
public TextView branchCount;
public TextView inFavoriteCount;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.custom_listview, null);
holder = new ViewHolder();
holder.repositoryName = (TextView) vi.findViewById(
R.id.custom_listview_tv_repositoryName);
holder.language = (TextView) vi.findViewById(
R.id.custom_listview_tv_language);
holder.branchCount = (TextView) vi.findViewById(
R.id.custom_listview_tv_branchCount);
holder.inFavoriteCount = (TextView) vi.findViewById(
R.id.custom_listview_tv_inFavoriteCount);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
;
if (data.size() <= 0) {
holder.repositoryName.setText("No Data");
} else {
tempValues = null;
tempValues = (ListModel) data.get(position);
holder.repositoryName.setText(tempValues.getRepositoryName());
holder.language.setText(tempValues.getLanguage());
holder.branchCount.setText(tempValues.getBranchCount());
holder.inFavoriteCount.setText(tempValues.getInFavoriteCount());
vi.setOnClickListener(new OnItemClickListener(position));
}
holder.repositoryName.setTypeface(textFont);
holder.language.setTypeface(textFont);
holder.branchCount.setTypeface(textFont);
holder.inFavoriteCount.setTypeface(textFont);
return vi;
}
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v("Custom Adapter", "Button Clicked");
}
private class OnItemClickListener implements View.OnClickListener {
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View v) {
UserActivity ua = (UserActivity) activity;
ua.onItemClick(mPosition);
}
}
ListModel.java
public class ListModel {
private String repositoryName = "";
private String language = "";
private String branchCount = "";
private String inFavoriteCount = "";
public void setRepositoryName(String repositoryName) {
this.repositoryName = repositoryName;
}
public void setLanguage(String language) {
this.language = language;
}
public void setBranchCount(String branchCount) {
this.branchCount = branchCount;
}
public void setInFavoriteCount(String inFavoriteCount) {
this.inFavoriteCount = inFavoriteCount;
}
public String getRepositoryName() {
return repositoryName;
}
public String getLanguage() {
return language;
}
public String getBranchCount() {
return branchCount;
}
public String getInFavoriteCount() {
return inFavoriteCount;
}
}
UserActivity.java
public class UserActivity extends AppCompatActivity {
ListView list;
CustomAdapter adapter;
public UserActivity userActivity = null;
public ArrayList<ListModel> customListViewValuesArr = new ArrayList<ListModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
userActivity = this;
setListData();
Resources res = getResources();
list = (ListView) findViewById(R.id.activitu_user_lv_repositoriesList);
adapter = new CustomAdapter(userActivity, customListViewValuesArr, res);
list.setAdapter(adapter);
}
private void setListData() {
for (int i = 0; i < 11; i++) {
final ListModel sched = new ListModel();
sched.setRepositoryName("Repository №" + i);
sched.setLanguage("Java");
sched.setBranchCount("" + (i+5));
sched.setInFavoriteCount("" + (i*12));
customListViewValuesArr.add(sched);
}
}
public void onItemClick(int mPosition) {
ListModel tempValues = (ListModel) customListViewValuesArr.get(mPosition);
Toast.makeText(userActivity, "" + tempValues.getRepositoryName(), Toast.LENGTH_LONG).show();
}
}
Thanks, =)
I cant find problem in this code and this is sad, but I find solution in tutorial. I rewrite my code and it helps. So, how it look now:
CustomAdapter.java rename to RepositoryAdapter.java and rewrite some code:
public class RepositoryAdapter extends BaseAdapter {
Context context;
Typeface textFont;
protected List<Repository> listRepository;
LayoutInflater inflater;
public RepositoryAdapter(Context context, List<Repository> listRepository){
this.listRepository = listRepository;
this.inflater = LayoutInflater.from(context);
this.context = context;
textFont = Typeface.createFromAsset(context.getAssets(), "fonts/DiamondGirl.ttf");
}
public int getCount(){
return listRepository.size();
}
#Override
public Repository getItem(int position) {
return listRepository.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.custom_listview, parent, false);
holder.tvRepositoryName =
(TextView) convertView.findViewById(R.id.custom_listview_tv_repositoryName);
holder.tvLanguage =
(TextView) convertView.findViewById(R.id.custom_listview_tv_language);
holder.tvBranchCount =
(TextView) convertView.findViewById(R.id.custom_listview_tv_branchCount);
holder.tvInFavoriteCount =
(TextView) convertView.findViewById(R.id.custom_listview_tv_inFavoriteCount);
holder.tvRepositoryName.setTypeface(textFont);
holder.tvLanguage.setTypeface(textFont);
holder.tvBranchCount.setTypeface(textFont);
holder.tvInFavoriteCount.setTypeface(textFont);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Repository repository = listRepository.get(position);
holder.tvRepositoryName.setText(repository.getRepositoryName());
holder.tvLanguage.setText(repository.getLanguage());
holder.tvBranchCount.setText(repository.getBranchCount());
holder.tvInFavoriteCount.setText(repository.getInFavoriteCount());
return convertView;
}
private class ViewHolder {
TextView tvRepositoryName;
TextView tvLanguage;
TextView tvBranchCount;
TextView tvInFavoriteCount;
}
}
ListModel.java now Repository.java:
public class Repository {
private String repositoryName = "";
private String language = "";
private String branchCount = "";
private String inFavoriteCount = "";
public Repository(String repositoryName, String language, String branchCount, String inFavoriteCount) {
super();
this.repositoryName = repositoryName;
this.language = language;
this.branchCount = branchCount;
this.inFavoriteCount = inFavoriteCount;
}
public void setRepositoryName(String repositoryName) {
this.repositoryName = repositoryName;
}
public void setLanguage(String language) {
this.language = language;
}
public void setBranchCount(String branchCount) {
this.branchCount = branchCount;
}
public void setInFavoriteCount(String inFavoriteCount) {
this.inFavoriteCount = inFavoriteCount;
}
public String getRepositoryName() {
return repositoryName;
}
public String getLanguage() {
return language;
}
public String getBranchCount() {
return branchCount;
}
public String getInFavoriteCount() {
return inFavoriteCount;
}
}
UserActivity.java:
public class UserActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<Repository> arrayRepositories;
ListView listViewRepositories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
arrayRepositories = new ArrayList<Repository>();
fillList();
listViewRepositories = (ListView) findViewById(R.id.activitu_user_lv_repositoriesList);
RepositoryAdapter adapter = new RepositoryAdapter(this, arrayRepositories);
listViewRepositories.setAdapter(adapter);
listViewRepositories.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Repository selectedRepository = arrayRepositories.get(position);
Toast.makeText(this, selectedRepository.getRepositoryName(), Toast.LENGTH_SHORT).show();
}
private void fillList() {
for (int i = 0; i < 12; i++) {
Repository repository = new Repository("Repository #"+i,"Java",""+ (i*5),"" + (i*12));
arrayRepositories.add(repository);
}
}
}
Now it's works, and work fast. Thanks all for help =)
Everything looking good to improve performance you can setTypeFace in first if block that is
if(convertview==null}
{
//at the end
holder.repositoryName.setTypeface(textFont);
holder.language.setTypeface(textFont);
holder.branchCount.setTypeface(textFont);
holder.inFavoriteCount.setTypeface(textFont);
}
If scrolling is to slow it is likely that something in
public View getView(int position, View convertView, ViewGroup parent)
is to slow. getView is called for every list-item that becomes visible.
Is this the slow part that needs expensive database/file system query?
tempValues = (ListModel) data.get(position);
I had the same problem with a list-view that contain images where calculating and caching the preview image from the original was expensive.
This can be solved using a ui synchronized WorkerThread or AsyncTask
I want to add quantity when the add button is clicked and subtract quantity when sub button is clicked here i am not showing my setter/getter class(RowItem) and my xml files
(main.xml,item_details_view)
This is my Adapter class
public class ItemListBaseAdapter extends ArrayAdapter<RowItem> {
Context context;
public ItemListBaseAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
Button add,sub;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_details_view, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.add = (Button) convertView
.findViewById(R.id.button1);
holder.sub = (Button) convertView
.findViewById(R.id.button2);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.add.setTag(position);
holder.sub.setTag(position);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Adds 1 to the counter
int counter=0;
counter = counter + 1;
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Subtract 1 from counter
int counter=0;
counter = counter - 1;
}
});
return convertView;
}
}
Thisi is my Activity class
public class ListViewImagesActivity extends Activity implements
OnItemClickListener {
public static final String[] titles = new String[] { "EggBurger",
"cheesBurger", "KingBurger", "Mixed" };
public static final String[] descriptions = new String[] {"Select 0 Item"
};
public static final Integer[] images = { R.drawable.burger1,
R.drawable.burger2, R.drawable.burger3, R.drawable.burger4 };
ListView listView;
List<RowItem> rowItems;
Button add,sub;
int counter=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[0]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
ItemListBaseAdapter adapter = new ItemListBaseAdapter(this,
R.layout.item_details_view, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
this is my RowItem class
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
this is my main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
this is my item_details_view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button2"
android:layout_marginRight="16dp"
android:layout_toLeftOf="#+id/button2"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/desc"
android:layout_alignParentRight="true"
android:text="Sub" />
</RelativeLayout>
First of all, if you want to change the quantity value, you should have a variable representing quantity which you can change. You have included quantity value in the description text, which is bad design. What you should do is have a quantity variable int in the RowItem class as shown. You desc should just return a string from the quantity value as shown:
public class RowItem {
private int imageId;
private String title;
private int quantity = 0;
public RowItem(int imageId, String title, int quantity) {
this.imageId = imageId;
this.title = title;
this.quantity = quantity;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return "Select " + quantity + " Item";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public String toString() {
return title + "\n" + quantity;
}
}
In your activity, instead of storing descriptions, store quantities:
public static final int[] quantities = new int[]{ 0 };
In onCreate initialize the rowItems as follows
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], quantities[0]);
rowItems.add(item);
}
Finally, in your OnClickListener, get the quantity value, update it and set the new description.
final ViewHolder viewHolderFinal = holder;
final RowItem finalRowItem = rowItem;
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity(); // get the quantity for this row item
finalRowItem.setQuantity(quantity + 1); // update it by adding 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc()); // set the new description (that uses the updated qunatity)
}
});
holder.sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int quantity = finalRowItem.getQuantity(); // get the quantity for this row item
finalRowItem.setQuantity(quantity - 1); // update it by subtracting 1
viewHolderFinal.txtDesc.setText(finalRowItem.getDesc()); // set the new description (that uses the updated qunatity)
}
});
*Note: * I have compiled and run this code. So if you do everything as I mentioned it will work.