How to add a different icon in slidemenu listview - android

I am using slidemenu example from github and it's showing slide menu only with text and header but I need to add different icon with it. I am trying to use a custom adapter but it's not working...
slidemenu.java:
public class SlideMenu implements SlideMenuAnimationContainer.Listener {
public final static String[] slideMenuOptions = { "Recent Update", "Notification", "Wardrobe" };
public final static String TAG = "SlideMenu";
protected static final String TextView = null;
Intent intent;
private Context context;
private SlideMenuAnimationContainer slideMenuAnimationContainer;
public SlideMenu( Context context, SlideMenuAnimationContainer mainAnimationLayout){
this.context = context;
this.slideMenuAnimationContainer = mainAnimationLayout;
}
public void init(){
final Activity activity = (Activity) context;
//Set Content's show menu button's action
ImageView showMenuButton = (ImageView) activity.findViewById( R.id.content_button);
showMenuButton.setOnClickListener( new OnClickListener(){
#Override
public void onClick( View v){
slideMenuAnimationContainer.toggleSlideMenu();
}
});
//Contruct the SlideMenu items here, you can replace this ArrayAdapter with your customr ArrayAdapter
List<SlideMenuItem> slideMenuList = new ArrayList<SlideMenuItem>();
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Updates"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Recent Update"));
// slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Header 2"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Notification"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Header, "Category"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Wardrobe"));
slideMenuList.add( new SlideMenuItem( SlideMenuItemType.Activity, "Gadgets"));
SlideMenuArrayAdapter slideMenuArrayAdaptar = new SlideMenuArrayAdapter( context, android.R.layout.simple_list_item_1, slideMenuList);
ListView menuListView = (ListView) activity.findViewById( R.id.slideMenuListView);
menuListView.setAdapter( slideMenuArrayAdaptar);
menuListView.setOnItemClickListener( new OnItemClickListener(){
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id){
// Close sidebar
slideMenuAnimationContainer.closeSlideMenuAndActOnClick( parent, view, position, id);
}
});
//Implement your logic here within the execute() function when an item is clicked with in the SlideMenu
//Called after the SlideMenu collapses.
slideMenuAnimationContainer.setMenuItemSelectedAction( new MenuItemSelectedAction(){
#Override
public void execute( AdapterView<?> parent, View view, int position, long id){
//Only act when a ListViewItem with type Activity is clicked
TextView textView = (TextView)view.findViewById( R.id.MenuActivityListViewItem_text);
if( textView != null && textView.getId() == R.id.MenuActivityListViewItem_text){
//Start new activity
CharSequence selectedActivityName = textView.getText();
if( selectedActivityName.equals( "Recent Update")) {
intent = new Intent( activity, Activity1.class);
}
else if( selectedActivityName.equals( "Notification")) {
intent = new Intent( activity, Activity2.class);
}
else if( selectedActivityName.equals( "Wardrobe")) {
intent = new Intent( activity, Activity3.class);
}
else if( selectedActivityName.equals( "Gadgets")) {
intent = new Intent( activity, Gadgets_Activity.class);
}
intent =intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.startActivity( intent);
}
}
});
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public void onSlideMenuOpened(){
Log.d( TAG, "opened");
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public void onSlideMenuClosed(){
Log.d( TAG, "closed");
}
//Callback of SlideMenuAnimationContainer.Listener to monitor status of SlideMenu
#Override
public boolean onContentTouchedWhenOpening(){
//The content area is touched when sidebar opening, close sidebar
Log.d( TAG, "going to close sidebar");
slideMenuAnimationContainer.closeSlideMenu();
return true;
}
}
and Adapter:
public class SlideMenuArrayAdapter extends ArrayAdapter<SlideMenuItem> {
private List<SlideMenuItem> slideMenuItemList;
public SlideMenuArrayAdapter( Context context, int textViewResourceId, List<SlideMenuItem> slideMenuItemList) {
super( context, textViewResourceId, slideMenuItemList);
this.slideMenuItemList = slideMenuItemList;
}
#Override
public View getView( int position, View view, ViewGroup parent) {
SlideMenuItem slideMenuItem = slideMenuItemList.get( position);
LayoutInflater layoutInflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if( slideMenuItem.getSlideMenuItemType() == SlideMenuItemType.Header){
view = layoutInflater.inflate( R.layout.menu_header_listview_item, null);
TextView textView = (TextView) view.findViewById( R.id.MenuListHeaderListViewItem_text);
textView.setText( slideMenuItem.getText());
}
else if( slideMenuItem.getSlideMenuItemType() == SlideMenuItemType.Activity){
view = layoutInflater.inflate( R.layout.menu_activity_listview_item, null);
TextView textView = (TextView) view.findViewById( R.id.MenuActivityListViewItem_text);
textView.setText( slideMenuItem.getText());
}
else{
view = null; //Left for operation
}
return view;
}
}

Try like this
ListView listView = (ListView) menu.findViewById(R.id.list);
ArrayList<String[]> datavalues=new ArrayList<String[]>();
String[] menuhome=new String[2];
menuhome[0]=""+R.drawable.home_sidebar;
menuhome[1]="Home";
datavalues.add(menuhome);
String[] menuprofile=new String[2];
menuprofile[0]=""+R.drawable.profile_sidebar;
menuprofile[1]="Profile";
datavalues.add(menuprofile);
String[] menusearch=new String[2];
menusearch[0]=""+R.drawable.search_sidebar;
menusearch[1]="Search";
datavalues.add(menusearch);
String[] menugallery=new String[2];
menugallery[0]=""+R.drawable.gallery_sidebar;
menugallery[1]="Gallery";
datavalues.add(menugallery);
String[] menulogout=new String[2];
menulogout[0]=""+R.drawable.logout_sidebar;
menulogout[1]="Logout";
datavalues.add(menulogout);
SlideMenuAdapter menuadapter=new SlideMenuAdapter(datavalues, this);
listView.setAdapter(menuadapter);
private class SlideMenuAdapter extends BaseAdapter{
ArrayList<String[]> data;
ActivityListing context;
public SlideMenuAdapter(ArrayList<String[]> datavalues,
ActivityListing contextobj) {
// TODO Auto-generated constructor stub
data=datavalues;
context=contextobj;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
final int pos=arg0;
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View convertView = inflater.inflate(R.layout.menurow, null, false);
int drawable=Integer.parseInt(data.get(arg0)[0].trim());
Button btnOption=(Button) convertView.findViewById(R.id.btnoption);
btnOption.setCompoundDrawablesWithIntrinsicBounds(context.getResources().getDrawable(drawable), null, null, null);
btnOption.setText(data.get(arg0)[1].trim());
btnOption.setTextColor(Color.rgb(143, 7, 0));
btnOption.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
callOptions(data.get(pos));
}
});
return convertView;
}

Related

Custom spinner is not invoke custom listview?

I have a custom listview and spinner.First of all i am filling the listview and then i am clicking dropdown spinner.I am choosing a item(city).I want to update listview with new result.But whatever i can custom adapter getview is not call. So listview is not update. This is my screen
How can i do it?
I am filling spinner here
private void getCityListWithSpinner() {
cityListRequest = new CityListRequest(new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
System.out.println("Objemizzz " + obj.toString());
cityArrayList = (ArrayList<CityList>) obj;
Spinner ss = (Spinner) findViewById(R.id.cityfilmspinner);
CinemaCitySelector2 citySelector = new CinemaCitySelector2();
cityList.add("Seçiniz");
for (int i = 0; i < cityArrayList.size(); i++) {
cityList.add(cityArrayList.get(i).getCinemaCity());
citySelector.CinemaCitySelector2(
CinemaCityMoviePickerActivity.this, ss, cityList,2);
}
}
CinemaCitySelector:
public class CinemaCitySelector2 implements OnItemSelectedListener {
Context context2;
Spinner spinner2;
CityListInCityRequest cityListInCityRequest2;
ArrayList<Cinema> cityListInCityArrayList2;
ListView list_cinema_movie_selectorr2;
CinemaListViewAdapter2 adapter2;
View row2;
int act2 = 0;
Spinner cityspinner;
public void CinemaCitySelector2(Context context, Spinner spinner,
ArrayList<String> cityList, int activityfrom) {
this.context2 = context;
this.spinner2 = spinner;
act2 = activityfrom;
// Declaring an Adapter and initializing it to the data pump
ArrayAdapter adapter = new ArrayAdapter(context,
android.R.layout.simple_list_item_1, cityList);
// Setting Adapter to the Spinner
spinner.setAdapter(adapter);
// Setting OnItemClickListener to the Spinner
spinner.setOnItemSelectedListener(CinemaCitySelector2.this);
}
// Defining the Callback methods here
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
String city = spinner2.getItemAtPosition(pos).toString();
LayoutInflater layoutInflater = LayoutInflater.from(context2);
row2 = layoutInflater.inflate(
R.layout.activity_cinemacitymoviepicker, null, false);
list_cinema_movie_selectorr2 = (ListView) row2
.findViewById(R.id.listfilmincinema);
if (!city.equals("Seçiniz")) {
cityListInCityRequest2 = new CityListInCityRequest(
new AsyncListener() {
#Override
public void asyncOperationSucceded(Object obj, int queue) {
// adapter.clear();
// adapter.notifyDataSetChanged();
// list_cinema_movie_selector.setAdapter(adapter);
System.out.println("Objemizzz " + obj.toString());
cityListInCityArrayList2 = (ArrayList<Cinema>) obj;
// adapter.notifyDataSetChanged();
adapter2 = new CinemaListViewAdapter2(context2,
R.layout.cinema_list,
cityListInCityArrayList2);
list_cinema_movie_selectorr2
.setAdapter(adapter2);
}
#Override
public void asyncOperationFailed(Object obj, int queue) {
// TODO Auto-generated method stub
System.out.println("Objemizzz2 " + obj.toString());
}
}, city);
}
}
public void onNothingSelected(AdapterView arg0) {
// TODO Auto-generated method stub
}
}
CinemaListViewAdapter2:
public class CinemaListViewAdapter2 extends ArrayAdapter<Cinema> {
Context context;
int arraycount=0;
public CinemaListViewAdapter2(Context context, int resourceId,
ArrayList<Cinema> items) {
super(context, resourceId, items);
this.context = context;
arraycount=items.size();
}
/*private view holder class*/
private class ViewHolder {
BlackBrandTextview cinemaName;
RelativeLayout cinemalist;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Cinema rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.cinema_list, null);
holder = new ViewHolder();
holder.cinemaName = (BlackBrandTextview) convertView.findViewById(R.id.txt_cinema_name);
holder.cinemalist=(RelativeLayout)convertView.findViewById(R.id.cinemalist);
holder.cinemaName.setText(rowItem.getCinemaName());
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
convertView.setTag(holder);
} else{
holder = (ViewHolder) convertView.getTag();
holder.cinemaName.setText(rowItem.getCinemaName());
}
if(rowItem.getCinemaDistance()<5000){
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Pink));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.Cinema_Black));
}
else{
holder.cinemalist.setBackgroundColor(context.getResources().getColor(R.color.Cinema_Black));
holder.cinemaName.setTextColor(context.getResources().getColor(R.color.White));
}
holder.cinemaName.setText(rowItem.getCinemaName());
return convertView;
}
I'd create a method to update the adapter once an item on your spinner is chosen:
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
city = (String) parent.getItemAtPosition(position);
resetCinema(city); //or onRestart();
}
public void onNothingSelected(AdapterView<?> parent){
}
});
And resetCinema(city) rechages the view depending on the city value. You can do this manually:
public void resetCinema(String city) {
//show list view elements depending on city
}
or just call a refresh of the whole Activity:
protected void onRestart() {
Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.
}
I suggest you to call
adapter2.notifyDataSetChange();
But anyway there is no need to initialize a new adapter every time.
you should create a method inside the adapter like this:
public void setMyArray(ArrayList<Cinema> items) {
myArray.clear();
myArray.addAll(items);
notifyDataSetChange();
}

How to add dymnamically selected gridview items in listview

First activity : gridview, whenever u click on gridview item dialogBox is opened which contains spinner. Now, I want to display Selected Gridview item and selected spinner values in Second Activity contains Listview. When u click on secondtime the values are replaced in listview but not added.
Can anyone plz help me...........
MainActivity...
public class MainActivity extends Activity implements OnClickListener {
SharedPreferences SharedPrefs;
String sp_selected;
Spinner sp;
String s1;
String partname;
String partname1;
Button Parts_history;
Imageadapter image_adapter;
private static final String[] paths = { "Select Your Choice", "Type1",
"Type2", "Type3", "Type4" };
private static final int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.partsrepair);
image_adapter = new Imageadapter(this);
SharedPrefs = getSharedPreferences("Preference", MODE_PRIVATE);
GridView gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(new Imageadapter(this));
Parts_history = (Button) findViewById(R.id.partshistory_button);
Parts_history.setOnClickListener((this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, View v,
int position, long id) {
SharedPreferences.Editor edit = SharedPrefs.edit();
// partname = parent.getItemAtPosition(position).toString();
partname1 = image_adapter.names[position].toString();
image_adapter.names[position].toString();
Toast.makeText(MainActivity.this, "you Selected:" + partname1,
Toast.LENGTH_SHORT).show();
// edit.putString("SelectPart", partname1);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.repairtype_spinner);
dialog.setCancelable(true);
Spinner sp = (Spinner) dialog.findViewById(R.id.spinner_1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_item,paths);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
if (position > 0) {
sp_selected = parent.getItemAtPosition(position)
.toString();
}
}
#Override
public void onNothingSelected(AdapterView<?>arg0) {
// TODO Auto-generated method stub
}
});
Button btnOk = (Button)dialog.findViewById(R.id.Button_sms_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor edit = SharedPrefs.edit();
if ((sp_selected != null)
&& !sp_selected.equals("Select Your Choice")) { //
edit.putString("SelectType", sp_selected);
Toast.makeText(getApplicationContext(),
"You selected:" + sp_selected,
Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"Thank You!", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this,
"plz Select your Choice",
Toast.LENGTH_SHORT).show();
}} });
dialog.show(); }});}
public void onClick(View v) {
switch (v.getId()) {
case R.id.partshistory_button:
Intent intent = new Intent(MainActivity.this, ListViewItems.class);
intent.putExtra("Part", partname1);
intent.putExtra("Type", sp_selected);
startActivity(intent);
finish();
}}}
listview.class
public class ListViewItems extends Activity {
ArrayList<String> part, type;
ListView list;
public ListViewItems() {
// TODO Auto-generated constructor stub
part = new ArrayList<String>();
type = new ArrayList<String>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_summary);
Intent i = getIntent();
part.add(i.getStringExtra("Part"));
type.add(i.getStringExtra("Type"));
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.listview, type);
list.setAdapter(new CustomViewAdapter(ListViewItems.this));
adapter.notifyDataSetChanged();
}
public class CustomViewAdapter extends BaseAdapter {
Context context;
public CustomViewAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
private class ViewHolder {
TextView text_part;
TextView text_type;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
// Log.d("hao",""+position);
LayoutInflater minflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = minflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.text_part = (TextView) convertView
.findViewById(R.id.textView1);
// Log.d("hao", ""+holder.text_desc);
holder.text_type = (TextView) convertView
.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.text_type.setText(type.get(position));
holder.text_part.setText(part.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return part.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}}
Imageadapter.class
public class Imageadapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mlayoutinflater;
public Imageadapter(Context c) {
mContext = c;
mlayoutinflater = LayoutInflater.from(c);
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
class ViewHolder {
ImageView imageView;
TextView textView;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
ViewHolder childHolder;
if (convertView == null) {
// if it's not recycled, initialize some
convertView = mlayoutinflater.inflate(R.layout.partsnames, null);
childHolder = new ViewHolder();
childHolder.imageView = (ImageView) convertView
.findViewById(R.id.imageView1);
childHolder.textView = (TextView) convertView
.findViewById(R.id.textView1);
convertView.setTag(childHolder);
} else {
childHolder = (ViewHolder) convertView.getTag();
}
childHolder.imageView.setImageResource(mThumbIds[position]);
childHolder.textView.setText(names[position]);
return convertView;
}
public Integer[] mThumbIds = { R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher, };
public String[] names = { "First", "Second", "Third", "Fourth",
"Fifth", "Sixth", "Seventh" };
}
It seems the values are not really being overwritten. Each time the second activity is loaded new part and type ArrayLists are being created. In these new lists only the latest part and type are added (in the onCreate Function) which have travelled with the intent.
If you want the list to keep adding the part and type selected by the user you can maintain the lists on the MainActivity. So upon selection of each item and type add it to the list on the MainActivity and then pass it to the ListViewItems activity.
This way the list will always have all the items selected by you.
I must admit I am not 100% sure if I understood your question correctly. But I have tried to answer with as much as I did.
EDIT:
MainActivity:
public class MainActivity extends ActionBarActivity {
ArrayList<String> list;
int clickCount = 0;
static TextView textViewHelloWorld;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
list = new ArrayList<String>();
textViewHelloWorld = (TextView) findViewById(R.id.textViewHelloWorld);
Button buttonAddElements = (Button) findViewById(R.id.buttonAddElement);
buttonAddElements.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
clickCount = clickCount + 1;
textViewHelloWorld.setText("Click Count" + clickCount);
list.add("Click number " + clickCount);
}
});
Button buttonStartNewActivity = (Button) findViewById (R.id.buttonStartNewActivity);
buttonStartNewActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle = new Bundle();
bundle.putStringArrayList("list", list);
startActivity(new Intent(MainActivity.this, Main2Activity.class).putExtras(bundle));
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Main2Activity: (ListView Activity):
public class Main2Activity extends ActionBarActivity {
ArrayList<String> list;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
list = getIntent().getStringArrayListExtra("list");
listView = (ListView) findViewById(R.id.listViewList);
String []dsf = new String[list.size()];
list.toArray(dsf);
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, dsf));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main2,
container, false);
return rootView;
}
}
}
EDIT2:
MainActivity.Java
public class MainActivity extends Activity implements OnClickListener {
SharedPreferences SharedPrefs;
String sp_selected;
Spinner sp;
String s1;
String partname;
String partname1;
Button Parts_history;
private ArrayList<String> parts;
private ArrayList<String> types;
Imageadapter image_adapter;
private static final String[] paths = { "Select Your Choice", "Type1",
"Type2", "Type3", "Type4" };
private static final int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.partsrepair);
image_adapter = new Imageadapter(this);
parts = new ArrayList<String>();
types = new ArrayList<String>();
SharedPrefs = getSharedPreferences("Preference", MODE_PRIVATE);
GridView gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(new Imageadapter(this));
Parts_history = (Button) findViewById(R.id.partshistory_button);
Parts_history.setOnClickListener((this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, View v,
int position, long id) {
SharedPreferences.Editor edit = SharedPrefs.edit();
// partname = parent.getItemAtPosition(position).toString();
partname1 = image_adapter.names[position].toString();
parts.add(partname1);
image_adapter.names[position].toString();
Toast.makeText(MainActivity.this, "you Selected:" + partname1,
Toast.LENGTH_SHORT).show();
// edit.putString("SelectPart", partname1);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.repairtype_spinner);
dialog.setCancelable(true);
Spinner sp = (Spinner) dialog.findViewById(R.id.spinner_1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_spinner_item,paths);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
if (position > 0) {
sp_selected = parent.getItemAtPosition(position)
.toString();
types.add(sp_selected);
}
}
#Override
public void onNothingSelected(AdapterView<?>arg0) {
// TODO Auto-generated method stub
}
});
Button btnOk = (Button)dialog.findViewById(R.id.Button_sms_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor edit = SharedPrefs.edit();
if ((sp_selected != null)
&& !sp_selected.equals("Select Your Choice")) { //
edit.putString("SelectType", sp_selected);
Toast.makeText(getApplicationContext(),
"You selected:" + sp_selected,
Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"Thank You!", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this,
"plz Select your Choice",
Toast.LENGTH_SHORT).show();
}} });
dialog.show(); }});}
public void onClick(View v) {
switch (v.getId()) {
case R.id.partshistory_button:
Bundle bundle = new Bundle();
bundle.putStringArrayList("parts", parts);
bundle.putStringArrayList("type", types);
Intent intent = new Intent(MainActivity.this, ListViewItems.class);
intent.putExtra("Part", partname1);
intent.putExtra("Type", sp_selected);
intent.putExtra("bundle", bundle);
startActivity(intent);
finish();
}}}
ListView:
public class ListViewItems extends Activity {
ArrayList<String> part, type;
ListView list;
public ListViewItems() {
// TODO Auto-generated constructor stub
part = new ArrayList<String>();
type = new ArrayList<String>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_summary);
Intent i = getIntent();
// part.add(i.getStringExtra("Part"));
// type.add(i.getStringExtra("Type"));
part = i.getExtras().getBundle("bundle").getStringArrayList("parts");
type = i.getExtras().getBundle("bundle").getStringArrayList("types");
list = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), R.layout.listview, type);
list.setAdapter(new CustomViewAdapter(ListViewItems.this));
adapter.notifyDataSetChanged();
}
public class CustomViewAdapter extends BaseAdapter {
Context context;
public CustomViewAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
private class ViewHolder {
TextView text_part;
TextView text_type;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
// Log.d("hao",""+position);
LayoutInflater minflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = minflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.text_part = (TextView) convertView
.findViewById(R.id.textView1);
// Log.d("hao", ""+holder.text_desc);
holder.text_type = (TextView) convertView
.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.text_type.setText(type.get(position));
holder.text_part.setText(part.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return part.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}}

Custom BaseAdapter wont add new Data - Android

I have a custom baseadapter that creates comment boxes. Everything works great on it until I want to add data. When I try to add the data it deletes the previous data and adds the new data. How do I make it so it keeps all the data? Is my Add method incorrect? Here is my baseadapter,
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
Setting the adapter:
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
This is what how I call the add method,
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
In your add method you're setting the arrays to new values listComments = comments; That's replacing your old data with the new data.
You could use System.arrayCopy() to resize your listArrays to the new size and append the new items. A much less tedious approach, however, would be to store your arrays as List<String>, allowing you to add more items without worrying about resizing lists.
The result would look something like this...
public class CommentsAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private List<String> comments;
private List<String> numbers;
private List<String> usernames;
public CommentsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
comments = new ArrayList<String>();
numbers = new ArrayList<String>();
usernames = new ArrayList<String>();
}
public void add(String[] comments, String[] numbers, String[] usernames)
{
this.comments.addAll(Arrays.asList(comments));
this.numbers.addAll(Arrays.asList(numbers));
this.usernames.addAll(Arrays.asList(usernames));
notifyDataSetChanged();
}
#Override
public int getCount()
{
if (comments == null)
return 0;
return comments.size();
}
#Override
public String getItem(int position)
{
return comments.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.commentView.setText(comments.get(position));
//Other view bind logic here...
return convertView;
}
private static class ViewHolder
{
public TextView commentView;
public TextView numbersView;
public TextView usernamesView;
public Button usernameButton;
public Button numberButton;
public ViewHolder(View v)
{
commentView = (TextView) v.findViewById(R.id.listComment);
numbersView = (TextView) v.findViewById(R.id.listNumber);
usernamesView = (TextView) v.findViewById(R.id.listPostedBy);
usernameButton = (Button) v.findViewById(R.id.listUsernameButton);
numberButton = (Button) v.findViewById(R.id.listNumberButton);
}
}
}
I also highly recommend reading this page on the Android Developer's site: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Your current adapter implementation is very inefficient, and that page should help you iron out some kinks.
You probably need to add the String[] array to the existing one, instead of replacing it.
Add this function which joins two arrays (Sadly there is no already-implemented method for Java):
String[] concat(String[] A, String[] B) {
String[] C= new String[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
Credits: Sun Forum
And then change the add method to this:
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = concat(listComments, comments);
listUsernames = concat(listUsernames, usernames);
listNumbers = concat(listNumbers, numbers);
}
And you had a typo in your code. In the add method, the listUsernames and listNumbers should be swapped I think.. I fixed it for you.

How to assign different values to buttons in a listView - Android

I have a ListView Item that has 2 buttons in it. There are multiple ListView items so there are many buttons. How can I assign a different value to each button? What I want to happen is every button leads to the same activity, but when it goes to the new activity it sends a value that the button was assigned. Then the activity can handled the value. I want the values assigned to the buttons to be the same as what the text is set to, here is my baseAdapter
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setText("Go to " + listUsernames[position]);
numberButton.setText("Go to " + listNumbers[position]);
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
usernameButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("param", listUsernames[position]);
startActivity(intent);
}
});
}

My ListView consist an ImageView and a TextView i need to get the Text from the TextView

My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..

Categories

Resources