Trouble implementing a spinner - java

I'm fairly new to Java and android development. I am having trouble implementing a spinner in an android app. The spinner populates fine, but I cannot get it to the labels of the conversions variables to change when the index changes in the spinner. Essentially, the class I am having trouble getting to work is selectOption() or public void onItemSelected(AdapterView parent, View view, int position, long id) class.
Any help is extremely appreciated.
package com.example.conversion;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;
public class MainActivity extends ActionBarActivity implements OnEditorActionListener, AdapterView.OnItemSelectedListener{
//Graphical Variables
private Spinner option;
private TextView inputTextView;
private TextView outputTextView;
private EditText conversionInput;
private TextView conversionOutput;
//Conversions
private float
milesToKil = 1.6093f,
kilToMiles = 0.6214f,
inchToCent = 2.54f,
centToInch = 0.3937f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get IDs
option = (Spinner) findViewById(R.id.option);
inputTextView = (TextView) findViewById(R.id.inputTextView);
outputTextView = (TextView) findViewById(R.id.outputTextView);
conversionInput = (EditText) findViewById(R.id.conversionInput);
conversionOutput = (TextView) findViewById(R.id.conversionOutput);
conversionInput.setOnEditorActionListener(this);
//Add values to spinner
addToSpinner();
//selectOption();
display("");
}
//Spinner
public void addToSpinner() {
option = (Spinner) findViewById(R.id.option);
List<String> list1 = new ArrayList<String>();
list1.add("Miles To Kilometers");
list1.add("Kilometers To Miles");
list1.add("Inches To Centimeters");
list1.add("Centimeters to Inches");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
option.setAdapter(dataAdapter1);
}
/*public void selectOption()
{
int position;
position = option.getSelectedItemPosition();
String cAmountString = conversionInput.getText().toString();
float temp = Float.parseFloat(cAmountString);
if(position == 0)
{
inputTextView.setText("Miles");
outputTextView.setText("Kilometers");
convertMilesToKilometers(temp);
}
else if(position == 1)
{
inputTextView.setText("Kilometers");
outputTextView.setText("Miles");
convertKilometersToMiles(temp);
}
else if(position == 2)
{
inputTextView.setText("Inches");
outputTextView.setText("Centimeters");
//convertInchesToCentimeters(cAmountString);
}
else if(position == 3)
{
inputTextView.setText("Centimeters");
outputTextView.setText("Inches");
//convertCentimetersToInches(cAmountString);
}
}*/
#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);
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
display("");
return false;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
TextView myText = (TextView) view;
Toast.makeText(this, "You selected " + myText.getText() + " ", Toast.LENGTH_LONG).show();
String cAmountString = conversionInput.getText().toString();
float temp = Float.parseFloat(cAmountString);
if(position == 0)
{
inputTextView.setText("Miles");
outputTextView.setText("Kilometers");
convertMilesToKilometers(temp);
}
else if(position == 1)
{
inputTextView.setText("Kilometers");
outputTextView.setText("Miles");
convertKilometersToMiles(temp);
}
else if(position == 2)
{
inputTextView.setText("Inches");
outputTextView.setText("Centimeters");
//convertInchesToCentimeters(cAmountString);
}
else if(position == 3)
{
inputTextView.setText("Centimeters");
outputTextView.setText("Inches");
//convertCentimetersToInches(cAmountString);
}
}
public void display(String displayText)
{
if(displayText.equals(""))
{
conversionOutput.setText("0.0");
}
else
{
conversionOutput.setText(displayText);
}
}
private void convertMilesToKilometers(float cAmount) {
float total;
total = cAmount * milesToKil;
String temp2 = total + "";
display(temp2);
}
private void convertKilometersToMiles(float cAmount) {
float total;
total = cAmount * kilToMiles;
String temp2 = total + "";
display(temp2);
}
private void convertInchesToCentimeters(String cAmount) {
float temp;
float total;
temp = Float.parseFloat(cAmount);
total = temp * inchToCent;
String temp2 = total + "";
display(temp2);
}
private void convertCentimetersToInches(String cAmount) {
float temp;
float total;
temp = Float.parseFloat(cAmount);
total = temp * centToInch;
String temp2 = total + "";
display(temp2);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}

In your oncreate method, after the line addToSpinner();
add this line of code
option.setOnItemSelectedListener(this);
It would work.

You need to set an onItemSelectedListener to your spinner.
Override the onItemSelected method in the listener.
For example
option.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// if you have the spinner
String toastText = option.getSelectedItem().toString();
// if you havent
String toastText = parent.getItemAtPosition(pos).toString();
});
Hope this can bring you further.

Related

How to update my view when I click search button in Android app?

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.

Problem with Clicking Items in RecyclerView

This is one of my tab fragment.
I just wanted to show the list of Movies & Tv Shows that includes the word in SearchView
And when I click one of the images, it moves to the Detail Activity.
The problem happens when I search two or more words continuously.
It moves to proper Detail Activity and when I close that Activity it comes with several other unrelated Detail Activity.
I need you guys help
First code is the Fragment Code
package com.example.endterm.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.endterm.ItemAdapter;
import com.example.endterm.Items;
import com.example.endterm.MovieDetail;
import com.example.endterm.R;
import com.example.endterm.TVDetail;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
// 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;
SearchView searchView;
TextView tVQuery;
String queryWord;
//RecyclerView recyclerView7, recyclerView8;
ItemAdapter adapter7 = new ItemAdapter(7);
ItemAdapter adapter8 = new ItemAdapter(8);
public SearchFragment() {
// Required empty public constructor
}
class MyItmeDecoration extends RecyclerView.ItemDecoration{
#Override
public void getItemOffsets(#NonNull Rect outRect, #NonNull View view, #NonNull RecyclerView parent, #NonNull RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
outRect.set(10, 10, 10, 10);
view.setBackgroundColor(Color.BLACK);
}
}
// TODO: Rename and change types and number of parameters
public static SearchFragment newInstance(String param1, String param2) {
SearchFragment fragment = new SearchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_search, container, false);
tVQuery = (TextView) rootView.findViewById(R.id.query);
searchView = (SearchView) rootView.findViewById(R.id.search);
//final MyItmeDecoration Deco = new MyItmeDecoration();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
queryWord = s;
tVQuery.setText("Searched by : " + s);
// 입력받은 문자열 처리
searchView.onActionViewCollapsed();
adapter7.empty();
adapter8.empty();
adapter7.notifyDataSetChanged();
adapter8.notifyDataSetChanged();
exp(adapter7, "https://api.themoviedb.org/3/search/movie?api_key=0a9a6b6bcc6ed2a798fb5401045dd81f&language=ko&query=" + s + "&page=1&include_adult=false", true);
exp(adapter8, "https://api.themoviedb.org/3/search/tv?api_key=0a9a6b6bcc6ed2a798fb5401045dd81f&language=ko&page=1&query=" + s + "&include_adult=false", false);
return true;
}
#Override
public boolean onQueryTextChange(String s) {
// 입력란의 문자열이 바뀔 때 처리
return false;
}
});
return rootView;
}
private void exp(final ItemAdapter adapterS, String urlE, final boolean movieortv){
final RecyclerView rec;
if(movieortv) {
rec = (RecyclerView) getActivity().findViewById(R.id.searchedMovie);
}
else{
rec = (RecyclerView) getActivity().findViewById(R.id.searchedTV);
}
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rec.setLayoutManager(linearLayoutManager);
MyItmeDecoration Deco = new MyItmeDecoration();
if(Deco != null){
rec.removeItemDecoration(Deco);
}
rec.addItemDecoration(Deco);
rec.setAdapter(adapterS);
RequestQueue queue= Volley.newRequestQueue(getActivity());
StringRequest fR=new StringRequest(Request.Method.GET, urlE, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
parseXMLForecast(rec, response, adapterS, movieortv);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(fR);
}
private void parseXMLForecast(RecyclerView rec, String response, ItemAdapter adaptersample, final boolean movieortv){
try{
final ArrayList<Items> items = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
String results = jsonObject.getString("results");
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject subJsonObject = jsonArray.getJSONObject(i);
String url = "https://image.tmdb.org/t/p/w300" + subJsonObject.getString("poster_path");
String title;
if(movieortv) {
title = subJsonObject.getString("title");
}
else{
title = subJsonObject.getString("name");
}
String id = subJsonObject.getString("id");
Items jump = new Items(url, title, id);
items.add(jump);
}
adaptersample.setItems(items);
adaptersample.notifyDataSetChanged();
rec.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), rec, new ClickListener() {
#Override
public void onClick(View view, int position) {
Items dict = items.get(position);
Intent intent;
if(movieortv == true) {
intent = new Intent(getActivity(), MovieDetail.class);
}
else{
intent = new Intent(getActivity(), TVDetail.class);
}
intent.putExtra("id", dict.getId());
intent.putExtra("url", dict.getUrl());
intent.putExtra("title", dict.getTitle());
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
Items dict = items.get(position);
Toast.makeText(getActivity(), dict.getTitle()+' '+dict.getId()+' '+dict.getUrl(), Toast.LENGTH_LONG).show();
}
}));
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private SearchFragment.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final SearchFragment.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent 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));
}
}
});
}
#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) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
And the Second one is the Adapter Code if you need
package com.example.endterm;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.endterm.Items;
import java.util.ArrayList;
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{
private ArrayList<Items> items = new ArrayList<>();
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
private int wheree;
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public ItemAdapter(int wheree){
this.wheree = wheree;
}
public ItemAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View itemView = null;
if(wheree == 1) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork1, parent, false);
}
else if(wheree == 2){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork2, parent, false);
}
else if(wheree == 3){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork3, parent, false);
}
else if(wheree == 4){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork4, parent, false);
}
else if(wheree == 5){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork5, parent, false);
}
else if(wheree == 6){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork6, parent, false);
}
else if(wheree == 7){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork7, parent, false);
}
else if(wheree == 8){
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.imageswork8, parent, false);
}
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
public void onBindViewHolder(#NonNull ItemAdapter.ViewHolder viewHolder, int position) {
Items item = items.get(position);
Glide.with(viewHolder.itemView.getContext())
.load(item.getUrl())
.into(viewHolder.weatherImageView);
}
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView weatherImageView;
public ViewHolder(View itemView){
super(itemView);
if(wheree == 1){
weatherImageView=(ImageView)itemView.findViewById(R.id.item_image1);
}
else if(wheree == 2){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image2);
}
else if(wheree == 3){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image3);
}
else if(wheree == 4){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image4);
}
else if(wheree == 5){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image5);
}
else if(wheree == 6){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image6);
}
else if(wheree == 7){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image7);
}
else if(wheree == 8){
weatherImageView = (ImageView)itemView.findViewById(R.id.item_image8);
}
}
}
public void empty(){
for(int i = 0; i < getItemCount(); i++){
items.remove(0);
}
}
public int getItemCount() {
return items.size();
}
public void setItems(ArrayList<Items> items){
this.items = items;
}
}
First of all, remove this code, you do not need this here
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
}
Then, you did not implement getItemId() correctly. You can change this like that:
#Override
public long getItemId(int position) {
return items.get(position).getId(); //if you have item id, of course
}
I think the problem is because you are not specifying the items id, that is why it is opening several activities. Try this out. Hope it helps

How to save steps after clicking on List Items

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

Cannot cast CheckableLayout and highlight selected items

I want a multiple selection on this GridView, but I've a casting problem. This is my code:
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivityTest extends ActionBarActivity {
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setMultiChoiceModeListener(new MultiChoiceModeListener());
gridView.setAdapter(new NumberAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int numero = position+1;
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.custom_toast_layout,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView selectedNumber = (TextView) layout.findViewById(R.id.selected_number);
selectedNumber.setText(""+numero);
Context context = getBaseContext();
String text = ""+numero;
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 600);
}
});
}
#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);
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);
}
public class CheckableLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
#SuppressWarnings("deprecation")
public void setChecked(boolean checked) {
mChecked = checked;
setBackgroundDrawable(checked ? getResources().getDrawable(
R.drawable.rounded_edittext_denim) : null);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
public class MultiChoiceModeListener implements GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return true;
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount + " items selected");
break;
}
}
}
public class NumberAdapter extends BaseAdapter {
private Context context;
public NumberAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return 60;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckableLayout checkableLayout;
TextView numberView;
if (convertView == null) {
numberView = new TextView(context);
numberView.setLayoutParams(new GridView.LayoutParams(110, 110));
numberView.setPadding(0, 0, 0, 0);
numberView.setTextColor(Color.WHITE);
numberView.setBackgroundResource(R.drawable.rounded_edittext_zaffiro);
numberView.setGravity(Gravity.CENTER);
numberView.setTextSize(25);
checkableLayout = new CheckableLayout(MainActivityTest.this);
checkableLayout.addView(numberView);
} else {
//ERROR AT THIS POINT
checkableLayout = (CheckableLayout) convertView;
numberView = (TextView) checkableLayout.getChildAt(0);
}
numberView.setText("" + (position + 1));
return numberView;
}
}
}
java.lang.ClassCastException: android.widget.TextView cannot be cast to kangel.customtest.MainActivityTest$CheckableLayout
Anyone can help me to highlight selected item. Where is the error in my code?
you are returning the wrong object, that's the reason why you are getting the ClassCastException. In your custom getView's change
return numberView;
with
return checkableLayout;

Add new item to expandablelistview

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.

Categories

Resources