I separated my app in 3 classes. the main class where the user can choose which feature to use. The map feature works fine but my directions features doesn't when the user clicks on the button is causes a force close, I think it has something to do with the layout.
Main Class file
package com.sammy.umass;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
public class UMassGuide extends Activity {
/** Called when the activity is first created. */
//buttons
private Button goHereButton;
private Button mapButton;
private Button spireButton;
private Button sparkButton;
private Button websiteButton;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goHereButton = (Button) findViewById(R.id.button1);
goHereButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Intent i = new Intent(UMassGuide.this, DirectionsScreenActivity.class);
startActivity(i);
}
});
mapButton = (Button) findViewById(R.id.button2);
mapButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Intent i = new Intent(UMassGuide.this, UmassMap.class);
startActivity(i);
}
});
spireButton = (Button) findViewById(R.id.button3);
spireButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Uri uri = Uri.parse("https://spire.umass.edu/psp/heproda/EMPLOYEE/HRMS/?cmd=login&languageCd=ENG&");
Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
}
});
sparkButton = (Button) findViewById(R.id.button4);
sparkButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Uri uri = Uri.parse("https://spark.oit.umass.edu/webct/logonDisplay.dowebct");
Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
}
});
websiteButton = (Button) findViewById(R.id.button5);
websiteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
Uri uri = Uri.parse("http://www.umass.edu/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
}
});
}
}
Directions File (Force Close happens when this classes is being opened)
package com.sammy.umass;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
public class DirectionsScreenActivity extends ExpandableListActivity {
ExpandableListAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up our adapter
mAdapter = new MyExpandableListAdapter();
setListAdapter(mAdapter);
registerForContextMenu(getExpandableListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Sample menu");
menu.add(0, 0, 0, R.string.expandable_list_sample_action);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();
String title = ((TextView) info.targetView).getText().toString();
int type = ExpandableListView.getPackedPositionType(info.packedPosition);
if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,
Toast.LENGTH_SHORT).show();
return true;
} else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
/**
* A simple adapter which maintains an ArrayList of photo resource Ids.
* Each photo is displayed as an image. This adapter supports clearing the
* list of photos and adding a new photo.
*
*/
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
// Sample data set. children[i] contains the children (String[]) for groups[i].
private String[] groups = { " Academic Buildings", " Residential Buildings", " Dining Commons", " All Buildings A-Z" };
private String[][] children = {
{ "Agricultural Engineering Bldg", "Army ROTC Bldg", "Arnold House", "(Studio) Arts Building" },
{ "Baker Hall", "Brett Hall", "Brooks Hall", "Brown Hall" },
{ "Berkshire", "Franklin","Hampden","Hampshire","Worcester" },
{ "Agricultural Engineering Bldg", "Army ROTC Bldg", "Arnold House", "(Studio) Arts Building" }
};
public Object getChild(int groupPosition, int childPosition) {
return children[groupPosition][childPosition];
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return children[groupPosition].length;
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, 64);
TextView textView = new TextView(DirectionsScreenActivity.this);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setPadding(36, 0, 0, 0);
return textView;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getChild(groupPosition, childPosition).toString());
return textView;
}
public Object getGroup(int groupPosition) {
return groups[groupPosition];
}
public int getGroupCount() {
return groups.length;
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
}
Have you added the DirectionScreenActivity to your Manifest file? If not, that could cause a fatal crash.
Related
I'm currently learning Android programming. My task is to update view after clicking "search button" in the menu (onCreateOptionsMenu method).
Should I kill thread "ThumbnailDownloader" and start new one to update the view. Or maybe should I add listener to mPhotoRecyclerView? It's also could be something with cache. I don't realy know. Any advice or solution would be very helpful.
package com.bignerdranch.photogallery;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class PhotoGalleryFragment extends Fragment{
private static final String TAG = "PhotoGalleryFragment";
private RecyclerView mPhotoRecyclerView;
private TextView mCurrentPageText;
private List<GalleryItem> mItems = new ArrayList<>();
private int pageFetched = 0;
private GridLayoutManager mGridManager;
boolean asyncFetching = false;
int mCurrentPage = 1;
int mMaxPage = 1;
int mItemsPerPage = 1;
int mFirstItemPosition, mLastItemPosition;
private ThumbnailDownloader<Integer> mThumbnailDownloader;
public static Fragment newInstance() {
return new PhotoGalleryFragment();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
updateItems();
Handler responseHandler = new Handler();
mThumbnailDownloader = new ThumbnailDownloader<>(responseHandler);
mThumbnailDownloader.setThumbnailDownloadListener(
new ThumbnailDownloader.ThumbnailDownloadListener<Integer>() { //chanched to Integer
#Override
public void onThumbnailDownloaded(Integer position, Bitmap bitmap) {
mPhotoRecyclerView.getAdapter().notifyItemChanged(position);
}
}
);
mThumbnailDownloader.start();
mThumbnailDownloader.getLooper();
Log.i(TAG, "Background thread started");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
mCurrentPageText = (TextView) v.findViewById(R.id.currentPageText);
mPhotoRecyclerView = (RecyclerView) v.findViewById(R.id.photo_recycler_view);
mPhotoRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Context context;
float columnWidthInPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getActivity().getResources().getDisplayMetrics());
int width = mPhotoRecyclerView.getWidth();
int columnNumber = Math.round(width / columnWidthInPixels);
mGridManager = new GridLayoutManager(getActivity(), 3);
mPhotoRecyclerView.setLayoutManager(mGridManager);
mPhotoRecyclerView.scrollToPosition(mCurrentPage);
mPhotoRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
mPhotoRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
int lastVisibleItem = mGridManager.findLastVisibleItemPosition();
int firstVisibleItem = mGridManager.findFirstVisibleItemPosition();
if (mLastItemPosition != lastVisibleItem || mFirstItemPosition != firstVisibleItem) {
Log.d(TAG,"Showing item " + firstVisibleItem +" to " + lastVisibleItem);
updatePageText(firstVisibleItem);
mLastItemPosition = lastVisibleItem;
mFirstItemPosition = firstVisibleItem;
int begin = Math.max(firstVisibleItem-10,0 );
int end = Math.min(lastVisibleItem +10,mItems.size()-1);
for (int position = begin; position <= end; position++){
String url=mItems.get(position).getUrl();
if(mThumbnailDownloader.mPhotoCache.get(url)== null) {
Log.d(TAG,"Requesting Download at position: "+ position);
mThumbnailDownloader.queueThumbnail(position,url);
}
}
}
Log.d(TAG, "Scrolling, First Item: "+ firstVisibleItem + " Last item: " + lastVisibleItem);
if(!(asyncFetching) && (dy>0)&&(mCurrentPage<mMaxPage)&& (lastVisibleItem>=(mItems.size()-1))){
Log.d(TAG, "Fetching more");
updateItems();
} else updatePageText(firstVisibleItem);
}
});
if(mPhotoRecyclerView.getAdapter() == null)setupAdapter();
return v;
}
#Override
public void onDestroyView(){
super.onDestroyView();
mThumbnailDownloader.clearQueue();
mThumbnailDownloader.clearCache();
}
#Override
public void onDestroy(){
super.onDestroy();
mThumbnailDownloader.quit();
Log.i(TAG, "Background thread destroyed");
}
#Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater menuInflater){
super.onCreateOptionsMenu(menu, menuInflater);
menuInflater.inflate(R.menu.fragmen_photo_gallery, menu);
final MenuItem searchItem = menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
Log.d(TAG, "QueryTextSubmit: " + s);
QueryPreferences.setStoredQuery(getActivity(), s);
updateItems();
return true;
}
#Override
public boolean onQueryTextChange(String s) {
Log.d(TAG, "QueryTextChange: " +s);
return false;
}
});
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String query = QueryPreferences.getStoredQuery(getActivity());
searchView.setQuery(query, false);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menu_item_clear:
QueryPreferences.setStoredQuery(getActivity(), null);
updateItems();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateItems(){
String query = QueryPreferences.getStoredQuery(getActivity());
new FetchItemsTask(query).execute();
}
private void updatePageText(int pos){
mCurrentPage = pos / mItemsPerPage+1;
mCurrentPageText.setText("Page " + mCurrentPage + " of " + mMaxPage);
}
private void setupAdapter(){
if(isAdded()){
mPhotoRecyclerView.setAdapter(new PhotoAdapter(mItems));
}
}
private class PhotoHolder extends RecyclerView.ViewHolder{
private ImageView mItemImageView;
public PhotoHolder(View itemView){
super(itemView);
mItemImageView = (ImageView) itemView.findViewById(R.id.item_image_view);
}
public void bindDrawable (Drawable drawable){
mItemImageView.setImageDrawable(drawable); }
}
private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder>{
private List<GalleryItem> mGalleryItems;
public PhotoAdapter(List<GalleryItem> galleryItems){
mGalleryItems = galleryItems;
}
#NonNull
#Override
public PhotoHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
Context context;
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(R.layout.gallery_item, viewGroup, false);
return new PhotoHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PhotoHolder photoHolder, int position) {
Log.d(TAG,"Binding item "+ position + " to " + photoHolder.hashCode());
GalleryItem galleryItem = mGalleryItems.get(position);
String url = galleryItem.getUrl();
Bitmap bitmap = mThumbnailDownloader.mPhotoCache.get(url);
if(bitmap == null) {
Drawable placeholder = getResources().getDrawable(R.drawable.ic_launcher_background);
photoHolder.bindDrawable(placeholder);
}else {
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
photoHolder.bindDrawable(drawable);
}
}
#Override
public int getItemCount() {
return mGalleryItems.size();
}
}
private class FetchItemsTask extends AsyncTask<Void, Void, List<GalleryItem>>{
private String mQuery;
public FetchItemsTask(String query){
mQuery = query;
}
#Override
protected List<GalleryItem> doInBackground(Void...params){
asyncFetching = true;
if(mQuery == null){
return new FlickrFetch().fetchRecentPhotos(pageFetched+1);
} else{
return new FlickrFetch().searchPhotos(mQuery, pageFetched+1);
}
}
#Override
protected void onPostExecute(List<GalleryItem>items){
pageFetched++;
asyncFetching=false;
mItems.addAll(items);
GalleryPage pge = GalleryPage.getGalleryPage();
mMaxPage = pge.getTotalPages();
mItemsPerPage = pge.getItemPerPage();
if(mPhotoRecyclerView.getAdapter()==null)setupAdapter();
mPhotoRecyclerView.getAdapter().notifyDataSetChanged();
updatePageText(mGridManager.findFirstVisibleItemPosition());
}
}
}
The issue was in onPostExecute method in the very end of the class.
I deleted
mItems.addAll(items);
and added
mItems = items;
setupAdapter();
Now it works fine.
First of all sorry if the title is not suitable for my case,first I have a list view in fragment which have an adapter class components my list is looks like this ,thats if I click on menu Item it will increase the quantity by every click thats shown in that small orange box,my problem is that when I scroll this list or even change the activity it doesn't save the click that I did like this the quantity is backed to 0,all I need I just want to save this clicked action as
this is my adapter class
package abtech.waiteriano.com.waitrer.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.fragments.LVMenuFragment;
/**
* Created by dell on 3/7/2017.
*/
public class CustomMenuLVAdapter extends BaseAdapter {
ArrayList<String> resultMenuItems;
LVItemHolder lvItemHolder;
Context context;
private static LayoutInflater inflater = null;
public CustomMenuLVAdapter(LVMenuFragment lvMenuFragment, ArrayList<String> listMenuArray) {
resultMenuItems = listMenuArray;
context = lvMenuFragment.getActivity();
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultMenuItems.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class LVItemHolder {
TextView listMenuTV, txtQTY;
RelativeLayout qtyView;
Button minusBtn;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final LVItemHolder lvItemHolder = new LVItemHolder();
View rowView;
rowView = inflater.inflate(R.layout.menu_list_item, null);
lvItemHolder.listMenuTV = (TextView) rowView.findViewById(R.id.menulistTV2);
lvItemHolder.txtQTY = (TextView) rowView.findViewById(R.id.txtQTY);
lvItemHolder.minusBtn = (Button) rowView.findViewById(R.id.minusBtn);
lvItemHolder.listMenuTV.setText(resultMenuItems.get(position));
lvItemHolder.txtQTY.setText("0");
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
q++;
lvItemHolder.txtQTY.setText("" + q);
// Toast.makeText(context, "You Clicked "+resultMenuItems.get(position), Toast.LENGTH_LONG).show();
}
});
lvItemHolder.minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
if (q > 0)
q--;
lvItemHolder.txtQTY.setText("" + q);
}
});
return rowView;
}
}
this is my Activity
package abtech.waiteriano.com.waitrer.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import abtech.waiteriano.com.waitrer.MenuActivity;
import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.adapters.CustomMenuLVAdapter;
import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;
public class LVMenuFragment extends android.app.Fragment {
View rootView;
ListView menuListView;
public static ArrayList<String> listMenuArray = new ArrayList<String>();
public LVMenuFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_lvmenu, container, false);
menuListView=(ListView) rootView.findViewById(R.id.listView);
listMenuArray.clear();
String menuListSTR = "";
if (MenuActivity.Prst_ID.trim() == "-1")
menuListSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
else
menuListSTR = "select dbo.MenuItems.Item_ID, dbo.Items.Code, dbo.Items.Name, dbo.Items.Name2, dbo.Items.PrintOnChick, dbo.Items.Taxable, dbo.Items.NoServiceCharge, dbo.Items.PrintOnReport,Case { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), 0) } when 0 then dbo.Items.StaticPrice Else { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), dbo.Items.StaticPrice) } END AS Price From dbo.MenuItems LEFT OUTER JOIN dbo.Items ON dbo.MenuItems.Item_ID = dbo.Items.ID Where (dbo.MenuItems.Preset_ID = " + MenuActivity.Prst_ID + ") AND (dbo.MenuItems.Rest_ID_Active = " + ConnectionClass.Rest_ID + ") AND (dbo.MenuItems.OutLet_ID_Active = " + ConnectionClass.OutletID + ") AND (dbo.Items.Active = 1) ORDER BY dbo.MenuItems.SortNumber";
ResultSet rs = ConnectionClass.Ret_RS(menuListSTR);
try {
while (rs.next()) {
listMenuArray.add(rs.getString("Name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
menuListView.setAdapter(new CustomMenuLVAdapter(this,listMenuArray));
return rootView;
}
}
Sorry if any thing is unclear
Use this
public class CustomMenuLVAdapter extends BaseAdapter {
ArrayList<String> resultMenuItems;
LVItemHolder lvItemHolder;
Context context;
private static LayoutInflater inflater = null;
HashMap<Integer, Integer> map = new HashMap<>;
public CustomMenuLVAdapter(LVMenuFragment lvMenuFragment, ArrayList<String> listMenuArray) {
resultMenuItems = listMenuArray;
context = lvMenuFragment.getActivity();
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return resultMenuItems.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class LVItemHolder {
TextView listMenuTV, txtQTY;
RelativeLayout qtyView;
Button minusBtn;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final LVItemHolder lvItemHolder = new LVItemHolder();
View rowView;
rowView = inflater.inflate(R.layout.menu_list_item, null);
lvItemHolder.listMenuTV = (TextView) rowView.findViewById(R.id.menulistTV2);
lvItemHolder.txtQTY = (TextView) rowView.findViewById(R.id.txtQTY);
lvItemHolder.minusBtn = (Button) rowView.findViewById(R.id.minusBtn);
lvItemHolder.listMenuTV.setText(resultMenuItems.get(position));
if(map.containsKey(position)){
lvItemHolder.txtQTY.setText(""+map.get(position));
}else{
lvItemHolder.txtQTY.setText("0");
}
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
q++;
lvItemHolder.txtQTY.setText("" + q);
map.put(position,q)
// Toast.makeText(context, "You Clicked "+resultMenuItems.get(position), Toast.LENGTH_LONG).show();
}
});
lvItemHolder.minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int q = 0;
q = Integer.valueOf(lvItemHolder.txtQTY.getText().toString());
if (q > 0)
q--;
lvItemHolder.txtQTY.setText("" + q);
map.put(position,q)
}
});
return rowView;
}
in your adapter have a funtion like the following as an example;
public void setNumber(int number) {this.number = number}
Then when the user clicks on an item to increase it, you can save it by calling this setNumber function.
resultMenuItems.get(position).setNumber(//you number inputed here//);
//Then call notifydatasetChanged on your adapter//
Just make sure that the number is then gotten through a getter function in the apater.
I hope this makes sense
I would like to make an expandable list On clicking on an option take me to another activity. At the moment I only managed to make a message appear. I have only a few childrow, but I want to add more and they all take me to different activities
MainActivity.java
package com.example.gerardoalberto.lmx;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SearchView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private SearchManager searchManager;
private android.widget.SearchView searchView;
private MyExpandableListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<ParentRow> parentList = new ArrayList<ParentRow>();
private ArrayList<ParentRow> showTheseParentList = new ArrayList<ParentRow>();
private MenuItem searchItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
parentList = new ArrayList<ParentRow>();
showTheseParentList = new ArrayList<ParentRow>();
//The app will crash if display list is not called here.
displayList();
//This expands the list of continents.
expandAll();
}
private void loadData() {
ArrayList<ChildRow> childRows = new ArrayList<ChildRow>();
ParentRow parentRow = null;
childRows.add(new ChildRow(R.mipmap.generic_icon,"Charlie."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"James."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Carlos."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Alphonse."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Amelia."));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Olivia."));
parentRow = new ParentRow("Names", childRows);
parentList.add(parentRow);
childRows = new ArrayList<ChildRow>();
childRows.add(new ChildRow(R.mipmap.generic_icon,"Arcane"));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Fire."));
parentRow = new ParentRow("Magic", childRows);
parentList.add(parentRow);
childRows = new ArrayList<ChildRow>();
childRows.add(new ChildRow(R.mipmap.generic_icon,"red"));
childRows.add(new ChildRow(R.mipmap.generic_icon,"Yellow."));
parentRow = new ParentRow("Color", childRows);
parentList.add(parentRow);
}
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i=0; i<count; i++) {
myList.expandGroup(i);
}
}
private void displayList() {
loadData();
myList = (ExpandableListView) findViewById(R.id.expandableListView_search);
listAdapter = new MyExpandableListAdapter(MainActivity.this, parentList);
myList.setAdapter(listAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
searchItem = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setOnCloseListener(this);
searchView.requestFocus();
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
listAdapter.filterData(newText);
return false;
}
}
MyExpandableListAdapter.java
package com.example.gerardoalberto.lmx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by GerardoAlberto on 10/04/2016.
*/
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<ParentRow> parentRowList;
private ArrayList<ParentRow> originalList;
public MyExpandableListAdapter(Context context, ArrayList<ParentRow>originalList) {
this.context = context;
this.parentRowList = new ArrayList<>();
this.parentRowList.addAll(originalList);
this.originalList = new ArrayList<>();
this.originalList.addAll(originalList);
}
#Override
public int getGroupCount() {
return parentRowList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return parentRowList.get(groupPosition).getChildList().size();
}
#Override
public Object getGroup(int groupPosition) {
return parentRowList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return parentRowList.get(groupPosition).getChildList().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
ParentRow parentRow = (ParentRow) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.parent_row, null);
}
TextView heading = (TextView) convertView.findViewById(R.id.parent_text);
heading.setText(parentRow.getName().trim());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildRow childRow = (ChildRow) getChild(groupPosition, childPosition);
if(convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_row, null);
}
ImageView childIcon = (ImageView) convertView.findViewById(R.id.child_icon);
childIcon.setImageResource(R.mipmap.generic_icon);
final TextView childText = (TextView) convertView.findViewById(R.id.child_text);
childText.setText(childRow.getText().trim());
final View finalConvertView = convertView;
childText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(finalConvertView.getContext(), childText.getText(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
parentRowList.clear();
if (query.isEmpty()) {
parentRowList.addAll(originalList);
}
else {
for (ParentRow parentRow : originalList) {
ArrayList<ChildRow> childList = parentRow.getChildList();
ArrayList<ChildRow> newList = new ArrayList <ChildRow>();
for (ChildRow childRow: childList) {
if (childRow.getText().toLowerCase().contains(query)){
newList.add(childRow);
}
} //end for (childRow childRow: childList)
if (newList.size() > 0) {
ParentRow nParentRow = new ParentRow(parentRow.getName(),newList);
parentRowList.add(nParentRow);
}
} //end for (ParentRow parentRow : originalList)
} //end else
notifyDataSetChanged();
}
}
Im new to android programming so can you provide me the right code.
this is my code. the data is from sqlite. my problem is . How can i get the 3 textview from recyclerview and pass it to dialogbox when clicked? i finally made dialogbox but i can get only the position of the item i want to get all of the three textview data. please help me.
FragmentMeal.java
package inncharge.poy.madrigal.innchargev1.fragments;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.database.DatabaseHelper;
import inncharge.poy.madrigal.innchargev1.adapters.VivzAdapter;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentMeal#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentMeal extends Fragment {
private DatabaseHelper db;
private RecyclerView recyclerView;
private VivzAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentMeal.
*/
// TODO: Rename and change types and number of parameters
public static FragmentMeal newInstance(String param1, String param2) {
FragmentMeal fragment = new FragmentMeal();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentMeal() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
db = new DatabaseHelper(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_meal, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.mealList);
adapter = new VivzAdapter(getActivity(),db.getMealData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int postion) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.custom_dialog);
dialog.show();
final EditText editText = (EditText)dialog.findViewById(R.id.editText_pin);
Button submitButton = (Button)dialog.findViewById(R.id.submit_button);
Button cancelButton = (Button)dialog.findViewById(R.id.cancel_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText.getText().toString();
Toast.makeText(getActivity(), "Pin submitted is : " + text, Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(getActivity(), "onLongClick" + position, Toast.LENGTH_SHORT).show();
}
}));
return view;
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
Log.d("VIVZ", "constructor invoked ");
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("VIVZ","onSingleTapUp " + e);
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null){
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
Log.d("VIVZ", "onLongPress " + e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("VIVZ","onTouchEvent "+ e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View arg1, int arg2);
public void onLongClick(View view, int position);
}
}
VivzAdapter.java
package inncharge.poy.madrigal.innchargev1.adapters;
import android.content.ClipData;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.fragments.FragmentMeal;
import inncharge.poy.madrigal.innchargev1.pojo.Contact;
import inncharge.poy.madrigal.innchargev1.pojo.Information;
/**
* Created by Madrigal on 7/18/2015.
*/
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder> {
private Context context;
private final LayoutInflater inflater;
List<Contact> data = Collections.emptyList();
public VivzAdapter(Context context, List<Contact> data){
this.context=context;
inflater = LayoutInflater.from(context);
this.data=data;
}
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
Log.d("VIVZ","onCreateHolder called ");
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
Log.d("VIVZ", "onBindViewHolder called " + position);
holder.itemId.setText(String.valueOf(current.getId()));
holder.title.setText(current.getName());
holder.email.setText(current.getEmail());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public TextView email;
public TextView itemId;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listTextName);
email = (TextView) itemView.findViewById(R.id.listTextUname);
itemId = (TextView) itemView.findViewById(R.id.listTextId);
}
#Override
public void onClick(View v) {
}
}
}
Slidenerd makes some great videos, he helped me a lot as well when I started.
You might want to reconsider what you're trying to do and approach it differently... Why would you want to pass 3 textview from your UI into a dialog?
This is going to be painful.
Seems like you're going to have to extend DialogFragment (i'm assuming that's what you're using for a dialog, maybe an alert?). Create a static factory method inside the DialogFragment like this...
public class MyDialog extends DialogFragment {
private static tv1, tv2, tv3;
public static MyDialog newInstance(TextView tv1, TextView tv2, TextView tv3){
MyDialog.tv1 = tv1;
MyDialog.tv2 = tv2;
MyDialog.tv3 = tv3;
return new MyDialog();
}
}
Once you have this complete, create this dialog fragment inside that onClick method in the ViewHolder class. Instantiate the DialogFragment by doing this...
MyDialog.newInstance(title,email,itemId).show(getFragmentManager(),"dialog_tag");
Like i said before, it's seems sloppy and is probably error prone. There may be a better way of doing this but this is all I can think of off the top of my head. Let me know how it works out for you.. or perhaps revise your question so we can better help you reach a better solution to what you're trying to do.
I am trying to create an android app that takes information about an album and displays it in an expandable list view.The artist's name will be displayed as the parent item, and when artist is selected the albums by that artist will be displayed as the child. I have been able to get the list working so far by initializing the strings in the MyExpandableListAdapter class. However, I want to be able to press a button and add a new view to the List that contains the information.
Here is my code:
package droid.musiclibrary;
/**
* Some code taken from:
* http://www.dreamincode.net/forums/topic/270612-how-to-get-started-with-expandablelistview/
*/
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ExpandableListActivity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddContent extends Activity {
private Spinner spinArtist, spinGenre;
private EditText addArtist, addGenre, addTitle, addYear;
private ArrayAdapter<String> adapterArtist, adapterGenre;
private ArrayList<String> artists = new ArrayList<String>();
private ArrayList<String> genres = new ArrayList<String>();
private ArrayList<String> albums = new ArrayList<String>();
private ArrayList<String> albumList = new ArrayList<String>();
List<List<String>> albumArray = new ArrayList<List<String>>();
private ExpandableListView expList;
private MyExpandableListAdapter expAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.add_content);
expList = (ExpandableListView) findViewById(R.id.artistList);
expAdapter = new MyExpandableListAdapter(this);
expList.setAdapter(expAdapter);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed
// in the Action Bar.
Intent parentActivityIntent = new Intent(this, MainActivity.class);
parentActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(parentActivityIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public AddContent() {
}
public void addArtist(View view) {
spinArtist = (Spinner) findViewById(R.id.spinArtist);
addArtist = (EditText) findViewById(R.id.txtAddArtist);
if(addArtist.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter an artist.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
artists.add(addArtist.getText().toString());
adapterArtist = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, artists);
adapterArtist.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinArtist.setAdapter(adapterArtist);
addArtist.setText("");
}
public void addGenre(View view) {
spinGenre = (Spinner) findViewById(R.id.spinGenre);
addGenre = (EditText) findViewById(R.id.txtAddGenre);
if(addGenre.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter a genre.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
genres.add(addGenre.getText().toString());
adapterGenre = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, genres);
adapterGenre.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinGenre.setAdapter(adapterGenre);
addGenre.setText("");
}
public void addAlbum(View view) {
addTitle = (EditText) findViewById(R.id.txtAddTitle);
addYear = (EditText) findViewById(R.id.txtAddYear);
if(addTitle.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter a title.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else if(spinArtist.getSelectedItem().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to select an artist.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else if(spinGenre.getSelectedItem().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to select a genre.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else if(addYear.getText().toString().trim().equals(""))
{
Context context = getApplicationContext();
CharSequence text = "You need to enter a year.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
albums.add(addTitle.getText().toString().trim());
}
}
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
String[] groups = {"Silverstein"};
String[][] children = {{"Discovering the Waterfront"}};
public MyExpandableListAdapter(Context context) {
this.context = context;
}
public Object getChild(int groupPosition, int childPosition) {
return children[groupPosition][childPosition];
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return children[groupPosition].length;
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
TextView tv = new TextView(this.context);
tv.setLayoutParams(lp);
// Center the text vertically
tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
tv.setPadding(45, 0, 0, 0);
return tv;
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getChild(groupPosition, childPosition).toString());
return textView;
}
public Object getGroup(int groupPosition) {
return groups[groupPosition];
}
public int getGroupCount() {
return groups.length;
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
/*public void setArtist(ArrayList<String> artist) {
this.artists = artist;
}
public ArrayList<String> getArtist() {
return artist;
}
public void setAlbum(ArrayList<String> album) {
this.albums = album;
}
public ArrayList<String> getAlbum() {
return albums;
}
/**
* This will actually be used to sort the added content.
* For example, when sorting by artist, the parent will be the artist's name
* and the child entries will be the albums by that artist.
* This will probably have to moved to a separate class (Sort.java???)
*/
/*public void addItem(ExpandListChild item, ExpandListParent group) {
if(!artistList.contains(group)) {
artistList.add((group));
}
int index = artistList.indexOf(group);
ArrayList<ExpandListChild> ch = artistList.get(index).getItems();
ch.add(item);
artistList.get(index).setItems(ch);
}
public Object getChild(int parentPosition, int childPosition) {
ArrayList<ExpandListChild> chList = artistList.get(parentPosition).getItems();
return chList.get(childPosition);
}
public long getChildId(int parentPosition, int childPosition) {
return childPosition;
}*/
}
Is there some way to add the artists and albums ArrayList to the String[] in MyExpandableListAdpter class? I have tried that many different ways and each time I get a NullPointerException.
Any help would be appreciated, I have spent hours searching for an answer to this.