I am trying to get the index of the card which is active on the screen with this code.
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.glass.app.Card;
import com.google.android.glass.touchpad.Gesture;
import com.google.android.glass.touchpad.GestureDetector;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import com.google.api.services.mirror.model.TimelineItem;
public class MainActivity extends Activity {
private GestureDetector mGestureDetector;
String identifysource;
int cardindex;
private static ArrayList<Card> sourceCard = new ArrayList<Card>();
private ArrayList<String> sourceText = new ArrayList<String>(Arrays.asList("PCWorld", "TechCrunch"));
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for(int i=0;i<sourceText.size();i++)
{
System.out.println("whats up");
Card card = new Card(this);
identifysource=sourceText.get(i);
card.setText(identifysource);
sourceCard.add(card);
}
System.out.println(this);
mGestureDetector = createGestureDetector(this);
CardScrollView csvCardsView = new CardScrollView(this);
csaAdapter cvAdapter = new csaAdapter();
csvCardsView.setAdapter(cvAdapter);
csvCardsView.activate();
setContentView(csvCardsView);
cardindex=csvCardsView.getSelectedItemPosition();
}
private static class csaAdapter extends CardScrollAdapter
{
#Override
public int findIdPosition(Object id)
{
return -1;
}
#Override
public int findItemPosition(Object item)
{
return sourceCard.indexOf(item);
}
#Override
public int getCount()
{
return sourceCard.size();
}
#Override
public Object getItem(int position)
{
return sourceCard.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
return sourceCard.get(position).toView();
}
}
}
This results in the same cardindex output every time i.e 0
I tried getting the position with cvAdapter.findItemPosition() but that also returns -1 everytime.
Implement the onClickListener from the CardScrollView. Within you'll be able to determine which item was selected.
Related
description:
the page have 4 tabs, when i first open the page. The getOrders(null, type) function will run once, type='all',
when i slip to the second,third or forth tab, The getOrders(null, type) function always will run twice, type='all' and type='paid' | 'settled' | 'invalid',
but then when i slip back, The getOrders(null, type) function always run once, and the type is correct.It is very strange,i want the getOrders always run once.
and when i do not slip but clcik the top tab,the getOrders(null, type) run normal. I need some help
the code is below
// activity
package com.sugar.sugarmall.app.pages.order;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.OrderViewPagerAdapter;
import com.sugar.sugarmall.app.base.BaseActivity;
import com.sugar.sugarmall.app.config.Router;
import com.sugar.sugarmall.app.pages.mine.FragmentSetting;
import java.util.ArrayList;
import java.util.Arrays;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
#Route(path = Router.ORDER_LIST)
public class OrderActivity extends BaseActivity {
#BindView(R.id.orderPage)
ViewPager2 viewPager2;
#BindView(R.id.tabLayout)
TabLayout tabLayout;
#BindView(R.id.tv_left)
TextView backBtn;
#BindView(R.id.tv_title)
TextView topTitle;
#BindView(R.id.tv_right)
TextView topRight;
#BindView(R.id.bg_head)
LinearLayout topBox;
#BindView(R.id.topSearchCenterView)
EditText topSearchCenterView;
private final ArrayList<String> tabTitles = new ArrayList<>(Arrays.asList("全部", "已付款", "已结算", "已失效"));
private String topType = "title";
private Context context;
#Override
protected void initUI() {
setContentView(R.layout.order);
ButterKnife.bind(this);
context = getApplication();
OrderViewPagerAdapter orderViewPagerAdapter = new OrderViewPagerAdapter(this, context);
viewPager2.setAdapter(orderViewPagerAdapter);
viewPager2.setUserInputEnabled(false);
new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int i) {
tab.setText(tabTitles.get(i));
}
}).attach();
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
backBtn.setVisibility(View.VISIBLE);
topTitle.setVisibility(View.VISIBLE);
topRight.setVisibility(View.VISIBLE);
topTitle.setText("订单明细");
topRight.setText("搜索");
}
#OnClick({R.id.tv_left, R.id.tv_right})
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_left:
onBackPressed();
break;
case R.id.tv_right:
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
break;
}
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
}
#Override
protected void initData() {
}
#Override
protected void initListener() {
}
}
// OrderViewPagerAdapter
package com.sugar.sugarmall.app.adapter;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.pages.order.FragmentOrder;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import java.util.ArrayList;
public class OrderViewPagerAdapter extends FragmentStateAdapter {
private String searchType = "";
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private Context context;
private FragmentOrder fragmentOrder = new FragmentOrder("all");
private TabLayout tabLayout;
public OrderViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, Context context) {
super(fragmentActivity);
this.context = context;
}
#NonNull
#Override
public Fragment createFragment(int i) {
switch (i) {
case 0:
searchType = "all";
break;
case 1:
searchType = "paid";
break;
case 2:
searchType = "settled";
break;
default:
searchType = "invalid";
break;
}
System.out.println("-----createFragment" + searchType);
return new FragmentOrder(searchType);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public boolean containsItem(long itemId) {
return super.containsItem(itemId);
}
#Override
public int getItemCount() {
return 4;
}
}
// FragmentOrder
package com.sugar.sugarmall.app.pages.order;
import static com.sugar.sugarmall.config.ResStatusCode.STATUS_OK;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.ItemOrderAdapter;
import com.sugar.sugarmall.app.base.BaseLazyFragment;
import com.sugar.sugarmall.app.base.DefaultObserver;
import com.sugar.sugarmall.https.ApiManger;
import com.sugar.sugarmall.https.CheckResponse;
import com.sugar.sugarmall.https.response.OrderResponse;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import com.sugar.sugarmall.utils.RxTools;
import com.sugar.sugarmall.utils.T;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class FragmentOrder extends BaseLazyFragment {
#BindView(R.id.fragmentOrderList)
RecyclerView fragmentOrderList;
private ViewPager2 viewPager2;
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private String type = "all";
private ItemOrderAdapter itemOrderAdapter;
private TabLayout tabLayout;
private Context context;
private String[] typeArr = new String[]{"all", "paid", "settled", "invalid"};
public FragmentOrder(String type) {
this.type = type;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order, container, false);
ButterKnife.bind(this, view);
context = getContext();
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
fragmentOrderList.setLayoutManager(linearLayoutManager);
viewPager2 = getActivity().findViewById(R.id.orderPage);
itemOrderAdapter = new ItemOrderAdapter(orderList);
fragmentOrderList.setAdapter(itemOrderAdapter);
tabLayout.removeAllTabs();
tabLayout.clearOnTabSelectedListeners();
tabLayout.addTab(tabLayout.newTab().setText("all"));
tabLayout.addTab(tabLayout.newTab().setText("paid"));
tabLayout.addTab(tabLayout.newTab().setText("settled"));
tabLayout.addTab(tabLayout.newTab().setText("invalid"));
TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println("-----pageScroll4" + tab.getPosition());
String type = typeArr[tab.getPosition()];
getOrders(null, type); // type:"all" | "paid" | "settled" | "invalid"
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
onTabSelectedListener.onTabSelected(tabLayout.getTabAt(tabLayout.getSelectedTabPosition()));
tabLayout.setOnTabSelectedListener(onTabSelectedListener);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void lazyload() {
}
public void getOrders(String searchKey, String type) {
RxTools.setSubscribe(ApiManger.sugarApi().getOrderList(type, pageNo, searchKey), new DefaultObserver<OrderResponse>() {
#Override
public void onNext(#io.reactivex.rxjava3.annotations.NonNull OrderResponse orderResponse) {
CheckResponse.checkResponse(orderResponse);
orderList.clear();
if (orderResponse.code != STATUS_OK) {
T.showShort(getContext(), orderResponse.msg);
}
orderList.addAll(orderResponse.data);
itemOrderAdapter.notifyDataSetChanged();
}
#Override
public void onError(#Nullable #io.reactivex.rxjava3.annotations.NonNull Throwable e) {
super.onError(e);
}
});
}
}
I am trying to get the position of the item in a recycler view in order to pass it down to other activities, but after actually managing to get the item id, I found out that I'm getting a -1, therefore not getting a correct id there. What could be causing this?
The activity:
package com.gmproxy.pastilarma;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.recyclerview.*;
import com.gmproxy.Adapters.PathologyListAdapter;
import com.gmproxy.Adapters.PathologyViewHolder;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Util.PathologyViewModel;
public class PathologiesSearchScreen extends AppCompatActivity {
private PathologyViewModel viewModel;
SearchView searchView;
RecyclerView recyclerView;
private PathologyDAO pathDao;
private Pathology pathology;
private PathologyViewHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pathology_search_list);
searchView = findViewById(R.id.SearchView);
recyclerView = findViewById(R.id.recyclerview);
final PathologyListAdapter adapter = new PathologyListAdapter(new PathologyListAdapter.UserDiff());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
viewModel = new ViewModelProvider(this).get(PathologyViewModel.class);
viewModel.pathologies.observe(this, adapter::submitList);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
viewModel.setFilter(searchView.getQuery().toString());
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
long start;
start = System.currentTimeMillis();
if ((newText.length() > 3) && (System.currentTimeMillis() - start > 500)) {
viewModel.setFilter(searchView.getQuery().toString());
}
return false;
}
});
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
pathology = getSelectedPathology(findViewById(R.id.recyclerview));
Log.println(Log.INFO, "PathologyTest", pathology.toString());
final CharSequence[] options = {"Si", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(PathologiesSearchScreen.this);
builder.setTitle("¿Añadir la patología " + pathology.getPathologyName() + "?");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Si")) {
Toast.makeText(PathologiesSearchScreen.this, "Has añadido la patología " + pathology.getPathologyName() + ".", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(PathologiesSearchScreen.this, UserAddScreen.class);
mainAct.putExtra("path", pathology);
} else if (options[item].equals("No")) {
dialog.dismiss();
}
}
});
builder.show();
return true;
}
#Override
public void onTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public Pathology getSelectedPathology(View v){
holder = new PathologyViewHolder(v);
long idlongo = recyclerView.getAdapter().getItemId(holder.getAdapterPosition());
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}
}
The view holder:
package com.gmproxy.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.R;
import java.nio.file.Path;
public class PathologyViewHolder extends RecyclerView.ViewHolder {
public final TextView objItemView;
public PathologyViewHolder(View itemView) {
super(itemView);
objItemView = itemView.findViewById(R.id.textView);
}
public void bind(String text) {
objItemView.setText(text);
}
static PathologyViewHolder create(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pathologies_item, parent, false);
return new PathologyViewHolder(view);
}
}
The list adapter:
package com.gmproxy.Adapters;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.UserAddScreen;
public class PathologyListAdapter extends ListAdapter<Pathology, PathologyViewHolder> {
public PathologyListAdapter(#NonNull DiffUtil.ItemCallback<Pathology> diffCallback) {
super(diffCallback);
}
#Override
public PathologyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return PathologyViewHolder.create(parent);
}
#Override
public void onBindViewHolder(PathologyViewHolder holder, int position) {
Pathology current = getItem(position);
holder.bind(current.getPathologyName());
}
public static class UserDiff extends DiffUtil.ItemCallback<Pathology> {
#Override
public boolean areItemsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem == newItem;
}
#Override
public boolean areContentsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem.getPathologyName().equals(newItem.getPathologyName());
}
}
}
The entity DAO:
package com.gmproxy.DAO;
import androidx.lifecycle.LiveData;
import androidx.room.*;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
#Dao
public interface PathologyDAO {
#Query("SELECT * FROM condiciones")
LiveData<List<Pathology>> getAllObjects();
//This will come in handy for getting all those pathologies, will need to get them on a for loop since I'm not completely sure
//that the query will handle int[]
#Query("SELECT id_condiciones FROM condiciones WHERE id_condiciones LIKE :id_condiciones")
int getPathologiesForUser(int id_condiciones);
#Query("SELECT nombreCondicion FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
String getPathologiesForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
Pathology getPathologiesCompleteForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE id_condiciones = :id")
Pathology findObjectbyId(int id);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE '%' || :filter || '%'")
LiveData<List<Pathology>> filterText(String filter);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllObjects(List<Pathology> listObjects);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertObject(Pathology object);
#Update
void updateObject(Pathology object);
#Delete
void delete(Pathology obj);
}
The entity repository:
package com.gmproxy.DAO;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class PathologyRepository {
private PathologyDAO concerningDao;
private LiveData<List<Pathology>> pathologyList;
public PathologyRepository(Application application) {
DatabaseHelper db = DatabaseHelper.getDatabase(application);
concerningDao = db.pathologyDao();
pathologyList = concerningDao.getAllObjects();
}
public LiveData<List<Pathology>> getAllObjects() {
return concerningDao.getAllObjects();
}
void insertAllObjects(List<Pathology> objectsList) {
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertAllObjects(objectsList);
});
}
public void insertObject(Pathology obj){
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertObject(obj);
});
}
public void deleteObject(Pathology obj) {
concerningDao.delete(obj);
}
public LiveData<List<Pathology>> filter(String input){
try{
return new FilterNoteAsyncTask(concerningDao).execute(input).get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
private static class FilterNoteAsyncTask extends AsyncTask<String, Void, LiveData<List<Pathology>>> {
private PathologyDAO pathologyDAO;
private FilterNoteAsyncTask(PathologyDAO pathologyDAO) {
this.pathologyDAO = pathologyDAO;
}
#Override
protected LiveData<List<Pathology>> doInBackground(String... strings) {
return pathologyDAO.filterText(strings[0]);
}
}
}
Move your PathologyListAdapter to global, and get adapter position using adapter object instead of getting adapter from recyclerview.
public Pathology getSelectedPathology(){
long idlongo = adapter.getAdapterPosition();
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}
Hi friends I am trying from long time to save dynamically added views of Viewpager in shardepreferences. So that when user next time open the app , his added pages or views should be there. But I have no success. I am trying to save the size of ArrayList in sharedpreferences and then trying to call regenerate the size of ArrayList next time when user open app. what I am doing is i am adding number of pages in pager with for loop that are equal to size of ArrayList. I dont know is this a right way or i am completely wrong. Please guide me someone through this. Thanks in advance. I am uploading the pic of my UI also enter image description here.I am pasting my code here. First below is code of my adapter.
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainPagerAdapter extends PagerAdapter
{
private ArrayList<View> views = new ArrayList<View>();
SharedPreferences preferences;
Context context;
LayoutInflater inflater;
final static String PREF_COUNT="com.savesampledata";
final static String PREF_KEY="com.savesampledata.key";
final static String PREF_LIST="com.savesampledata.list";
final static String PREF_LIST_KEY="com.savesampledata.listkey";
int numberofview;
public MainPagerAdapter(Context c){
context=c;
}
#Override
public int getItemPosition (Object object)
{
int index = views.indexOf (object);
if (index == -1)
return POSITION_NONE;
else
return index;
}
#Override
public Object instantiateItem (ViewGroup container, int position)
{
Log.v("instantiate is called","now");
View v;
v = views.get(position);
if(v.getParent()!=null)
((ViewGroup)v.getParent()).removeView(v);
container.addView(v);
return v;
}
#Override
public void destroyItem (ViewGroup container, int position, Object object)
{
container.removeView (views.get (position));
}
#Override
public int getCount ()
{
Log.d("view list size",views.size()+"");
Log.d("numofViews before save",numberofview+"");
return views.size();
}
#Override
public boolean isViewFromObject (View view, Object object)
{
return view == object;
}
public int addView (View v)
{
return addView (v, views.size());
}
public int addView (View v, int position)
{
views.add (position, v);
return position;
}
public int removeView (ViewPager pager, View v)
{
return removeView (pager, views.indexOf (v));
}
public int removeView (ViewPager pager, int position)
{
if (numberofview > 1)
position = numberofview - 1;
if(position>0) {
pager.setAdapter(null);
views.remove(position);
pager.setAdapter(this);
}
return position;
}
public View getView (int position)
{
return views.get (position);
}
public void setCount(){
//storing size of views list
SharedPreferences preferences=context.getSharedPreferences(PREF_COUNT,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putInt(PREF_KEY,views.size());
Log.d("shared stored val :",views.size()+"");
editor.apply();
}
public int getNumberOfView(){
//getting size of views list
SharedPreferences preferences=context.getSharedPreferences(PREF_COUNT, Context.MODE_PRIVATE);
numberofview=preferences.getInt(PREF_KEY,0);
return numberofview;
}
}
Code of my Activity:
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class ViewPagerActivity extends AppCompatActivity implements View.OnClickListener {
private ViewPager pager =null;
private MainPagerAdapter pageradapter=null;
Button addpagebtn,removebtn;
final static String PREF_COUNT="com.savesampledata";
final static String PREF_KEY="com.savesampledata.key";
int numberofview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager_activity);
addpagebtn=(Button)findViewById(R.id.addbtn) ;
removebtn=(Button)findViewById(R.id.removeButton);
removebtn.setOnClickListener(this);
addpagebtn.setOnClickListener(this);
pageradapter= new MainPagerAdapter(this);
pager=(ViewPager)findViewById(R.id.view_pager);
pager.setAdapter(pageradapter);
pager.setOffscreenPageLimit(3);
numberofview=pageradapter.getNumberOfView();//here i am getting the value
Log.d("value after saving",pageradapter.getNumberOfView()+"");
LayoutInflater inflater=getLayoutInflater();
FrameLayout v0=(FrameLayout)inflater.inflate(R.layout.sample_layout_page,null);
pageradapter.addView(v0,0);
pageradapter.notifyDataSetChanged();
if(numberofview>1) {
Log.d("ManyView","added");
for (int i = 1; i <= numberofview; i++) {
pageradapter.addView(v0,i);
pageradapter.notifyDataSetChanged();
}
}
}
public void addView(View newpage){
int pageIndex=pageradapter.addView(newpage);
Log.d("page added at",pageIndex+"");
pageradapter.notifyDataSetChanged();
pageradapter.setCount();
pager.setCurrentItem(pageIndex,true);
}
public void removeView(View defunctPage){
int pageindex=pageradapter.removeView(pager,defunctPage);
Log.d("page removed at",pageindex+"");
pageradapter.notifyDataSetChanged();
pageradapter.setCount();
if(pageindex==pageradapter.getCount())
pageindex--;
pager.setCurrentItem(pageindex);
}
public View getCurrentPage(){
return pageradapter.getView(pager.getCurrentItem());
}
public void setCurrentPage(View pageToShow){
pager.setCurrentItem(pageradapter.getItemPosition(pageToShow),true);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.addbtn) {
LayoutInflater inflater=getLayoutInflater();
FrameLayout v0=(FrameLayout)inflater.inflate(R.layout.sample_layout_page,null);
addView(v0);
pageradapter.setCount();
}
if(v.getId()==R.id.removeButton){
View v1=getCurrentPage();
removeView(v1);
pageradapter.setCount();
}
}
#Override
protected void onStop() {
//here I am storing value
super.onStop();
pageradapter.setCount();
}
}
I used this tutorial to make a custom spinner but now I'm having a java.lang.OutOfMemoryError: Failed to allocate a 95976012 byte allocation with 16777120 free bytes and 31MB until OOMerror. I am aware that I should use bitmaps I just don't know how to include the bitmapFactory in my CustomAdapter. I have already compressed my images to sizes less than 16kb and put them in the mipmap folder because they are icons. I have also already tried
<application
android:largeHeap="true"
</application>
Here's my code :
MainActivity.java
package com.kathure.flags;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import static android.R.attr.id;
import static android.graphics.BitmapFactory.*;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String[] countryNames= {
"Kenya" , "Malawi", "Nigeria", "Rwanda", "Tanzania", "Uganda"
};
int [] flags = {
R.mipmap.kenyamin,R.mipmap.malawimin, R.mipmap.nigeriamin, R.mipmap.rwandamin, R.mipmap.tanzaniamin, R.mipmap.ugandamin
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),flags,countryNames);
spin.setAdapter(customAdapter);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), countryNames[i], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
CustomAdapter.java
package com.kathure.flags;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by kathure on 28/09/16.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
int flags[];
String[] countryNames;
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, int[] flags, String[] countryNames) {
this.context = applicationContext;
this.flags = flags;
this.countryNames = countryNames;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return flags.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.custom_spinner_items, null);
ImageView icon = (ImageView) view.findViewById(R.id.imageView);
TextView names = (TextView) view.findViewById(R.id.textView);
icon.setImageResource(flags[i]);
names.setText(countryNames[i]);
return view;
}
}
I'm trying to populate a recycle adapter from a controller class, to split the logic in the app. But I can't seem to get it working.. Do to the request is running on another thread, the view is not updated before it is shown. What am I doing wrong ?
FragmentClass:
package lassebjoerklund.homecontrol.views.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.controllers.FridgeController;
import lassebjoerklund.homecontrol.decorations.DividerItemDecoration;
import lassebjoerklund.homecontrol.model.Product;
import lassebjoerklund.homecontrol.utils.FragmentUtil;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverView extends Fragment {
private final FridgeController fridgeController = new FridgeController();
private RecyclerView recyclerView;
private LinkedList<String> types;
private FridgeFragmentOverViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_layout, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productOverviewRecycleView);
recyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new FridgeFragmentOverViewAdapter(fridgeController.getProductsTypes());
recyclerView.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
fridgeController.refresh(getContext(), adapter);
}
}
Controller Class:
package lassebjoerklund.homecontrol.controllers;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.interfaces.OnSucsess;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeController implements OnSucsess {
private RequestQueue rQueue;
private ArrayList<Product> products;
private List<String> productsTypes;
public ArrayList<Product> getProducts() {
return products;
}
public List<String> getProductsTypes() {
return productsTypes;
}
public void refresh(Context context, final FridgeFragmentOverViewAdapter adapter) {
String fetchProducts = "http://87.52.28.25:900/index.php";
rQueue = Volley.newRequestQueue(context);
final JsonArrayRequest getProductsRequest = new JsonArrayRequest(fetchProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
products = new ArrayList<>();
productsTypes = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) response.get(i);
String barcode = jsonObject.getString("code");
String name = jsonObject.getString("name");
String ex_date = jsonObject.getString("ex_date");
String add_date = jsonObject.getString("add_date");
String type = jsonObject.getString("type");
Product product = new Product(barcode, name, ex_date, add_date, type);
products.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (products.size() != 0) {
for (int i = 0; i < products.size(); i++) {
if (!productsTypes.contains(products.get(i).getType())) {
productsTypes.add(products.get(i).getType());
}
}
}
getProductsOnsucsess(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQueue.add(getProductsRequest);
}
#Override
public void getProductsOnsucsess(FridgeFragmentOverViewAdapter adapter) {
adapter.refreshAdapter(productsTypes);
}
}
Adapter:
package lassebjoerklund.homecontrol.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverViewAdapter extends RecyclerView.Adapter {
private List<String> types;
public FridgeFragmentOverViewAdapter(List<String> types) {
this.types = types;
}
#Override
public int getItemCount() {
return 0;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_overview_card_layout, null);
return new ProductsGroupedHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public class ProductsGroupedHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTypeOfProduct, tvCount, tvExpired;
public ProductsGroupedHolder(View itemView) {
super(itemView);
tvTypeOfProduct = (TextView) itemView.findViewById(R.id.tvTypeOfProduct);
tvCount = (TextView) itemView.findViewById(R.id.tvCount);
tvExpired = (TextView) itemView.findViewById(R.id.tvExpired);
}
#Override
public void onClick(View v) {
}
}
public void refreshAdapter(List<String> types) {
if(this.types != null) {
this.types.clear();
this.types = types;
notifyDataSetChanged();
}else {
this.types = types;
notifyDataSetChanged();
}
}
}
Try calling:
adapter.notifyDataSetChanged();
after updating it.
Edit 1:
Return actual size of adapter items in getItemCount() as #prathamkesarkar said.
Simple looks like you have set the getItemType() method return 0.
That method determines how much item your RecyclerView have.
#Override
public int getItemCount() {
return type.size();
}