How to save steps after clicking on List Items - java

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

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 speed up program that updates many UI items periodically?

I created a small application where I have a list of products and for each of the product I have an expiry time. If the user chooses to like a certain product(showTimerPost), the expiry time of the product will increase lets say 5 second. I tried it with a handler and it actually worked but my app started to run really slow maybe because it was changing the UI every second. I am really stuck with this problem for 1 month. Help will be appreciated.
package com.blueflair.incre;
import com.blueflair.incre.app.AppController;
import com.blueflair.incre.data.FeedItem;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
LocalUserData userLocalStore;
long postExpiry;
String timerFormat;
private int defaultPostIncrementation = 900000;
private List<FeedItem> feedItems;
boolean favourite;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private long timeDiff;
private final List<ViewHolder> lstHolders;
private int avatarSize;
Handler handler = new Handler();
private Runnable timerRunnable = new Runnable() {
#Override
public void run() {
for (final ViewHolder holder : lstHolders) {
holder.showTimerPost.postDelayed(new Runnable() {
#Override
public void run() {
long currentTime = System.currentTimeMillis();
currentTime--;
holder.showTimerPost.setText(String.valueOf(holder.updateTimeRemaining(currentTime)));
notifyDataSetChanged();
}
}, 2000);
}
}
};
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
lstHolders = new ArrayList<>();
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.feed_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final FeedItem item = feedItems.get(position);
holder = new ViewHolder();
userLocalStore = new LocalUserData(activity);
final User user = userLocalStore.getLoggedInUser();
postExpiry = item.getPostExpiry();
avatarSize = activity.getResources().getDimensionPixelSize(R.dimen.feed_avater_size);
holder.name = (TextView) convertView.findViewById(R.id.userFeedName);
holder.timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
holder.statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
holder.profilePic = (ImageView) convertView
.findViewById(R.id.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args= new Bundle();
args.putInt("userId", item.getUserId());
Fragment profileViewFragment = new ProfileViewFragment();
profileViewFragment.setArguments(args);
FragmentTransaction ft = ((MainActivity)activity).getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_done, R.anim.slide_out_send);
ft.replace(R.id.container_body, profileViewFragment);
ft.addToBackStack(null);
ft.commit();
}
});
holder.feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
String username = "#"+item.getUserName();
holder.name.setText(username);
convertView.setTag(holder);
synchronized ( lstHolders) {
lstHolders.add(holder);
}
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeCreated()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.timestamp.setText(timeAgo);
holder.showTimerPost = (Button) convertView.findViewById(R.id.showPostTimer);
handler.post(timerRunnable);
holder.showTimerPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
item.setIncrementToExpiry(50000);
notifyDataSetChanged();
}
});
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getPostMessage())) {
holder.statusMsg.setText(item.getPostMessage());
holder.statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.statusMsg.setVisibility(View.GONE);
}
// Feed image
if (item.getUserImage() != null) {
holder.feedImageView.setImageUrl(item.getUserImage(), imageLoader);
holder.feedImageView.setVisibility(View.VISIBLE);
holder.feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.feedImageView.setVisibility(View.GONE);
}
//Setting the timer adapter for the post and their respective contents
holder.setData(item);
return convertView;
}
private class ViewHolder {
FeedItem item;
public TextView name;
public TextView timestamp;
public TextView statusMsg;
public ImageView profilePic;
public FeedImageView feedImageView;
public Button showTimerPost;
public void setData(FeedItem item) {
this.item = item;
updateTimeRemaining(System.currentTimeMillis());
}
public String updateTimeRemaining(long currentTime) {
timeDiff = (item.getPostExpiry()+400000000) - currentTime;
if (timeDiff > 0) {
timerFormat = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeDiff)));
showTimerPost.setText(timerFormat);
return timerFormat;
} else {
//Delete feed items when post is expired
showTimerPost.setText("Expired!");//only to explimify
}
return timerFormat;
}
}
}

Add TextView to ListView Item

I need to add ListView items that can contain different count of TextView and Imageview objects. How can I do it? And how to determine and setup the id's of this objects? When I try to add an ImageView or TextView to LinearLayout with id R.id.chat_message, the application crashes :(
package com.me.my_app;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FriendSendMessageActivity extends ListActivity {
ListView view;
public ContactAdapter contactAdapter;
LinearLayout LL;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_send_message);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
int index = Integer.parseInt(extras.get(getPackageName() + ".IndexInList").toString());
String sentFrom = extras.get(getPackageName() + ".SentFrom").toString();
int id = Integer.parseInt(extras.get(getPackageName() + ".Id").toString()); //либо id друга либо id друга
FriendItem.Friend item = TabFriendsActivity.getList().get(index);
view = getListView();
contactAdapter = new ContactAdapter();
contactAdapter.addItem(new MessageItem.Message(1, true, true, true, "123","13:31",new ArrayList<MessageItem.Message.Attachment>()));
ArrayList<MessageItem.Message.Attachment> list = new ArrayList<MessageItem.Message.Attachment>();
list.add(new MessageItem.Message.Attachment(MessageAttachmentType.PHOTO, RoundedImage.createRoundedPhoto(BitmapFactory.decodeResource(MainActivity.res,R.drawable.temp_user_photo))));
contactAdapter.addItem(new MessageItem.Message(1, true, true, true, "123","9:10",list));
view.setAdapter(contactAdapter);
}
}
class ContactAdapter extends BaseAdapter {
private ArrayList<MessageItem.Message> mData = new ArrayList<MessageItem.Message>();
private LayoutInflater mInflater;
private static final int IGNORE_ITEM_VIEW_TYPE = -1;
private static final int TYPE_ITEM = 0; //обычный item
private static final int TYPE_MAX_COUNT = 2; //макс. число layout'ов отображения item'ов
public ContactAdapter()
{
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final MessageItem.Message item) {
mData.add(item);
notifyDataSetChanged();
}
public int getItemViewType(int position)
{
return TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount()
{
return mData.size();
}
public MessageItem.Message getItem(int position)
{
return mData.get(position);
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int pos)
{
return true;
}
public View getView(int position, View convertView, ViewGroup parent) {
MessageItem.ViewHolder holder = null;
MessageItem.Message item = mData.get(position);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (convertView == null)
{
holder = new MessageItem.ViewHolder();
convertView = mInflater.inflate(item.in_out ? R.layout.chat_message_in_item : R.layout.chat_message_out_item, null, false);
if(item.listAttach.size() > 0)
holder.attachLL = (LinearLayout) findViewById(R.id.chat_message);
for(MessageItem.Message.Attachment attach : item.listAttach)
{
switch(attach.type)
{
case PHOTO:
if(attach.photo != null)
{
ImageView iv = new ImageView(convertView.getContext());
//iv.setLayoutParams(params);
iv.setId(0x7f000000 - 1);
holder.listAttach.add(new MessageItem.Message.Attachment(attach.type,iv));
Log.v("","1" + iv.getId() + " " + holder.listAttach.size());
}
else
Log.v("", "Null!");
break;
}
}
convertView.setTag(holder);
} else {
holder = (MessageItem.ViewHolder) convertView.getTag();
}
for(int i = 0; i < holder.listAttach.size();i++)
{
if(holder.listAttach.get(i).type == MessageAttachmentType.PHOTO && item.listAttach.get(i).photo != null && holder.listAttach.get(i).image != null)
{
holder.attachLL.addView(holder.listAttach.get(i).image);
holder.listAttach.get(i).image.setImageBitmap(item.listAttach.get(i).photo);
}
else
Log.v("", "Unable to add image!");
}
return convertView;
}
}
}
And MessageItem.java:
package com.me.my_app;
import java.util.ArrayList;
import java.util.Comparator;
import android.graphics.Bitmap;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MessageItem
{
public static class Message implements Comparator<Message>
{
int id;
boolean in_out;
boolean is_read;
boolean is_delivered;
String message;
String time;
ArrayList<Attachment> listAttach;
public Message(int id, boolean in_out, boolean is_read, boolean is_delivered, String message, String time, ArrayList<Attachment> list)
{
this.id = id;
this.in_out = in_out;
this.is_read = is_read;
this.is_delivered = is_delivered;
this.message = message;
this.time = time;
listAttach = new ArrayList<Attachment>();
if(list != null)
{
for(Attachment a : list)
listAttach.add(a);
}
}
public int compare(Message object1, Message object2) {
return object1.time.compareTo(object2.time);
}
public static class Attachment
{
ImageView image;
MessageAttachmentType type;
Bitmap photo;
String Uri;
public Attachment(MessageAttachmentType type, Bitmap photo)
{
this.type = type;
this.photo = photo;
}
public Attachment(MessageAttachmentType type, ImageView image)
{
this.type = type;
this.image = image;
}
}
}
public static class ViewHolder
{
LinearLayout attachLL;
TextView text, time;
ArrayList<MessageItem.Message.Attachment> listAttach;
public ViewHolder()
{
listAttach = new ArrayList<MessageItem.Message.Attachment>();
}
}
}
enter code here
You will most probably have to implement your own list view adapter. Then you can create any layout for your item and set it up. Here is how it's done in my code:
public class ExpAdapter extends BaseExpandableListAdapter {
/*SOME CODE HERE*/
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_row, null);
}
int groupId = ((ListTaskElement)this.getGroup(groupPosition)).id;
this.setupTaskView(convertView, this.childrenOfGroup(groupId, false).get(childPosition));
convertView.setTag(this.getChildId(groupPosition, childPosition));
return convertView;
}
/*SOME CODE HERE*/
}
You can find all the details here: http://jnastase.alner.net/archive/2010/12/19/custom-android-listadapter.aspx

New intent creates force close

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.

Categories

Resources