I cannot add the one arraylist into another - java

Actually I have one filtered array. I want to store that ArrayList in another ArrayList, but it is not adding. I am saving one model to another. because I want only that filteredlist.
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ComboViewHolder> {
private ArrayList<Products> catList;
private ArrayList<FilteredCategorymodel> filterList;
Context context;
int count = 0;
// ArrayList<FilteredCategorymodel> filterModel;
SharedPrefrences sharedPrefrences;
boolean isClicked = true;
public ProductAdapter(Context context, ArrayList<Products> catList) {
this.catList = catList;
this.context = context;
}
#Override
public ComboViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.combo_list_item, parent, false);
return new ComboViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ComboViewHolder holder, final int position) {
final Products products = catList.get(position);
Log.e("Products Items::::", products + "");
holder.mProductName.setText(products.getProduct_name());
holder.mProductDescription.setText(products.getProduct_description());
holder.mDescription.setText(products.getRecipe_method());
holder.mPrice.setText(products.getPrice());
Picasso.with(context)
.load(Constants.Image_Path + products.getProduct_image())
.placeholder(R.drawable.common_signin_btn_icon_focus_light) // optional
.error(R.drawable.common_signin_btn_icon_dark) // optional
.into(holder.mPImage);
holder.mPImage.setTag(holder);
holder.btnIncrese.setTag(position);
holder.btnDecrese.setTag(position);
holder.btnIncrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mPosition = (int) v.getTag();
Log.e("mPosition~", mPosition + "~" + position);
count = catList.get(mPosition).getCount() + 1;
for (int i = 0; i < catList.size(); i++) {
filterList = new ArrayList<FilteredCategorymodel>();
filterList.add(catList.get(i));
}
basketCount = basketCount + 1;
catList.get(mPosition).setCount(count);
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
}
});
holder.btnDecrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// int position = (Integer) v.getTag();
int mPosition = (int) v.getTag();
if (catList.get(mPosition).getCount() < 1) {
holder.mQuantity.setText("0");
} else {
count = catList.get(mPosition).getCount() - 1;
basketCount = basketCount - 1;
catList.get(position).setCount(count);
Log.e("COUNT::::", count + "");
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
// sharedPrefrences = new SharedPrefrences();
// sharedPrefrences.addFavorite(context, catList.get(mPosition));
// Toast.makeText(context, "Fave",
// Toast.LENGTH_SHORT).show();
// Log.e("COUNT::::", count + "");
}
}
});
}
#Override
public int getItemCount() {
return catList.size();
}

Because every time you create new arraylist in loop.
Do it in this way.
holder.btnIncrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mPosition = (int) v.getTag();
Log.e("mPosition~", mPosition + "~" + position);
count = catList.get(mPosition).getCount() + 1;
filterList = new ArrayList<FilteredCategorymodel>();
for (int i = 0; i < catList.size(); i++) {
filterList.add(catList.get(i));
}
basketCount = basketCount + 1;
catList.get(mPosition).setCount(count);
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
}
});

From this too less information, I guess You are trying to add some values to Your filterList. The problem is, that everytime Your are going through the loop, You are creating a new ArrayList:
for (int i = 0; i < catList.size(); i++) {
filterList = new ArrayList<FilteredCategorymodel>();
filterList.add(catList.get(i));
}
You have to init the filterList first, don´t do this inside the loop. Your loop must look like this:
for (int i = 0; i < catList.size(); i++) {
filterList.add(catList.get(i));
}
it´s also important what You trying to reach. If You just want to fill a new list if the button is clicked, then init Your list inside onButtonClick outside the loop. But if You want to fill that list again and again and the values should persist, then init the list inside Your constructor.
But also, in Your case, this will not work, because filterList is from type "FilteredCategoryModel" and catList is from type "Product". You cannot fill an ArrayList with a wrong type.

If you want to add one ArrayList data into another you don't need to use loop, Use addAll() of ArrayList. Please check below example.
ArrayList<YourClass> a = new ArrayList<>();
ArrayList<YourClass> b = new ArrayList<>();
b.addAll(a);
It will add all data of b into a.

Related

Update Arraylist with the value of HashMap present

I have an ArrayList<Model> type and having fields id,name,isSelected and I have one HashMap which can store only selected items means if the item is clicked it will be stored in HashMap<Intere,Model>, Integer will be id , Model is that object which can be selected. I want to update Arraylist item field isSeleted to true which is present in hashmap. How can i do? I have tried many condition but nothing is working fine.
ArrayList<MainInterestModel> mainInterestList;
public static HashMap<Integer, MainInterestModel> mainIntrestHash = new HashMap<>();
Iterator myVeryOwnIterator = mainIntrestHash.keySet().iterator();
while (myVeryOwnIterator.hasNext()) {
int key = (int) myVeryOwnIterator.next();
MainInterestModel value = (MainInterestModel) mainIntrestHash.get(key);
int id = value.getId();
for (int i = 0; i < mainInterestList.size(); i++) {
MainInterestModel model = mainInterestList.get(i);
if (model.getId() == id) {
model.setSelected(true);
mainInterestList.set(i, model);
} else {
model.setSelected(false);
mainInterestList.set(i, model);
}
}
}
By Default isSelected is false but when the user will click that item will be stored in HashMap later i want to update selection so user interface will show selected items. HashMap has selected items and arraylist have all items but isSelected are false. at the time of showing selected items, I'm taking isSelected is true or not, which working fine, but arraylist update is not working.
My adapter class code
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final MainInterestModel mainInterestModel = mainInterestModels.get(position);
holder.tvName.setText(mainInterestModel.getName());
holder.ivMainInterest.setImageResource(mainInterestModel.getImage());
// here isSelected is always false because in activity infalting adpter with arraylist, i want to setSeletced by hash object
boolean isSelected = mainInterestModel.isSelected();
if (isSelected) {
holder.ivMainInterest.setImageResource(R.drawable.bath_selector);
Log.e("Is Item selected ::", "" + mainInterestModel.getId());
} else {
holder.ivMainInterest.setImageResource(R.drawable.ic_bath);
Log.e("Is Item deselected ::", "" + mainInterestModel.getId());
}
holder.ivMainInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean selection = mainInterestModel.isSelected();
if (selection) {
holder.ivMainInterest.setImageResource(R.drawable.ic_bath);
mainInterestModel.setSelected(false);
mainIntrestHash.remove(mainInterestModel.getId());
Log.e("After Remove SIZE:---", "" + mainIntrestHash.size());
} else {
mainInterestModel.setSelected(true);
holder.ivMainInterest.setImageResource(R.drawable.bath_selector);
mainIntrestHash.put(mainInterestModel.getId(), mainInterestModel);
Log.e("After Adding SIZE:---", "" + mainIntrestHash.size());
}
}
});
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.ivMainInterest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean selection = mainInterestModel.isSelected();
if (selection) {
holder.ivMainInterest.setImageResource(R.drawable.ic_bath);
mainInterestModel.setSelected(false);
} else {
mainInterestModel.setSelected(true);
holder.ivMainInterest.setImageResource(R.drawable.bath_selector);
}
notifyDataSetChanged();
}
});
}
remove hashmap and try to use this.
use this
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class ModelIterator {
public static void main(String arg[]) {
ArrayList<mainModel> mainmoldelList = new ArrayList<mainModel>();
for (int i = 1; i <= 3; i++) {
mainModel m = new mainModel();
m.setId(i);
m.setName("Rajendra" + i);
m.setSelected(false);
mainmoldelList.add(m);
}
mainModel m = new mainModel();
m.setId(0);
m.setName("Rajendra0");
m.setSelected(false);
HashMap<Integer, mainModel> mMap = new HashMap<Integer, mainModel>();
mMap.put(1, m);
Iterator<Entry<Integer, mainModel>> ite = mMap.entrySet().iterator();
while (ite.hasNext()) {
Map.Entry<Integer, mainModel> pair = (Map.Entry<Integer, mainModel>) ite
.next();
int key = pair.getKey();
mainModel mObj = (mainModel) mMap.get(key);
for (int i = 0; i < mainmoldelList.size(); i++) {
if (mainmoldelList.get(i).id == key) {
mainModel tmp = new mainModel();
tmp.setId(mainmoldelList.get(i).id);
tmp.setName(mainmoldelList.get(i).name);
tmp.setSelected(true);
mainmoldelList.add(tmp);
mainmoldelList.remove(i);
}
}
}
for (int i = 0; i < mainmoldelList.size(); i++) {
System.out.println(mainmoldelList.get(i).id + " "
+ mainmoldelList.get(i).name + " "
+ mainmoldelList.get(i).isSelected);
}
}
}

Common TextWatcher Saving Values in JSON Improperly (Replacing old values)

I have created Adapter to store Cart Items with there dynamic quantities.
Adding custom views which Contains Size, No. of Print, Price. In that I have to take No. of Print in EditText from User Input.
onBindViewHolder() of Adapter: In that I have added common TextWatcher for every EditText which is separated by ID passed in Constructor.
/*
* Add Custom View For Size and Price
* */
if (cart.getCartPhotoPrintSize() != null) {
try {
data = cart.getCartPhotoPrintSize().get(position);
if (data != null) {
// Remove the custom view
holder.cartPhotoSizrPriceCustome.removeAllViews();
holder.cartPhotoSizrPriceCustome.setVisibility(View.VISIBLE);
// Local Variable for Storing the size of StudioData Size
int size = cart.getCartPhotoPrintSize().size();
// Loop for set the custom layout
for (int i = 0; i < size; i++) {
// inner Loacl Variable
Studio.StudioSize studioSize = cart.getCartPhotoPrintSize().get(i);
// Layout Inflater For Targeting The RootView Of Context
LayoutInflater inflater = LayoutInflater.from(mContext);
View sizePriceView = inflater.inflate(R.layout.size_price_quantity_layout, null, false);
// Binding the id of TextView
studioSizeTextView = (TextView) sizePriceView.findViewById(R.id.studio_photo_album_size);
studioPriceTextView = (TextView) sizePriceView.findViewById(R.id.studio_photo_album_price);
photoQuantity = (EditText) sizePriceView.findViewById(R.id.photo_quantity);
studioSizeTextView.setId(i);
studioSizeTextView.setText(studioSize.getSize());
studioPriceTextView.setText("" + studioSize.getPrice());
holder.cartPhotoSizrPriceCustome.setTag(cart.getId());
holder.cartPhotoSizrPriceCustome.addView(sizePriceView);
//Add TextWacher For Every EditTextView
photoQuantity.addTextChangedListener(new GeneralTextWatcher(holder, i));
}
}
} catch (Exception e) {
Log.w("TAG", e.getMessage());
}
}
GeneralTextWatcher
private class GeneralTextWatcher implements TextWatcher {
ViewHolder viewHolder;
int id;
public GeneralTextWatcher(ViewHolder viewHolder, int i) {
this.viewHolder = viewHolder;
this.id = i;
Log.e(TAG, "Constructor Calling..");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
totalAmount = 0;
int child = viewHolder.cartPhotoSizrPriceCustome.getChildCount();
int pos = viewHolder.getAdapterPosition();
Log.i("size position : ", "" + id);
Log.i("cart item position : ", "" + pos);
Cart tCart = tempValue.get(pos);
Studio.StudioSize ssTemp = tCart.getCartPhotoPrintSize().get(id);
ssTemp.setQuantity(!TextUtils.isEmpty(s) ? Integer.parseInt(s.toString()) : 0);
for (int j = 0; j < child; j++) {
View view = viewHolder.cartPhotoSizrPriceCustome.getChildAt(j);
EditText editText = (EditText) view.findViewById(R.id.photo_quantity);
TextView textView = (TextView) view.findViewById(R.id.studio_photo_album_price);
Double quantity = 0.0;
if (!editText.getText().toString().equals(""))
quantity = Double.parseDouble(editText.getText().toString());
Double price = Double.parseDouble(textView.getText().toString());
if (printAmount != 0)
tempTotal = printAmount;
printAmount = quantity * price;
totalAmount += printAmount;
}
tempValue.get(pos).setTotal(totalAmount);
((CartActivity) mContext).mValues = tempValue;
Log.e("Tag", "After tmpStr " + new Gson().toJson(
tempValue,
new TypeToken<ArrayList<Cart>>() {
}.getType()));
((CartActivity) mContext).findTotalAmount(tempValue);
}
#Override
public void afterTextChanged(Editable s) {
}
}
When I Change First Cart Item with all three EditText values and Saving new JSON is like Click to see JSON after 3rd EditText filled up Its Working Fine,
But
After changing Second Cart Item fourth EditText Value and Saving JSON like as Click to see after changing 4th EditText in Second Cart Its replacing old Values.
I am getting this problem since last two days. Any help would be appreciated.
Thank you.

How to generate 24 string values randomly on textview in android?

i would like to generate 24 string values on 24 textview which i created the xml file in android and also i code for the getid and set listener but not mentioned here.
In the override oncick method i define the click fun method.
In this code i simply code for the integer values but now i would like to compare from the string array which has static values like
String[] value = {11,12,13,14,15,16,17,18,19,20,21,22,11,12,13,14,15,16,17,18,19,20,21,22};
Please help me to resolve my problem.
public class GameDemo extends Activity implements AnimationListener, OnClickListener
{
FrameLayout iv1,iv2,iv3,iv4,iv5,iv6,iv7,iv8,iv9,iv10,iv11,iv12,iv13,iv14,iv15,iv16,iv17,iv18,iv19,iv20,iv21,iv22,iv23,iv24;
TextView tv1,tv2,tv3,tv4,tv5,tv6,tv7,tv8,tv9,tv10,tv11,tv12,tv13,tv14,tv15,tv16,tv17,tv18,tv19,tv20,tv21,tv22,tv23,tv24;
Animation an1,an2;
int i1,counter,score,rev_count,level_counter;
boolean r_c,s_c;
Integer[] no;
FrameLayout[] count,rem,revise;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_demo);
an1 = AnimationUtils.loadAnimation(this,R.anim.flip1);
an1.setAnimationListener(this);
an2 = AnimationUtils.loadAnimation(this,R.anim.flip1);
an2.setAnimationListener(this);
level_counter=24;
getIDForAll();
setListnerForAll();
counter=1;
rev_count=0;
no = new Integer[25];
count = new FrameLayout[3];
rem = new FrameLayout[3];
revise = new FrameLayout[8];
int i=0;
for(i=0 ; i<24 ; i++)
{
Random r = new Random();
i1 = r.nextInt(25 - 1) + 1;
if(i!=0)
{
while(Arrays.asList(no).contains(i1))
{
r = new Random();
i1 = r.nextInt(25 - 1) + 1;
}
no[i]= i1 ;
}
else
{
no[i]= i1 ;
}
}
public void click_fun(FrameLayout arg0, TextView arg1, int n)
{
if(counter<2)
{
arg0.setAnimation(an1);
if(no[n]<=12)
{
arg1.setText(""+no[n]);
arg0.setBackgroundResource(android.R.color.white);
}
else
{
arg1.setText(""+(no[n]-12));
arg0.setBackgroundResource(android.R.color.white);
}
arg0.setTag(no[n]);
count[counter] = arg0;
counter++;
Log.i("animate", "anim2");
}
else
{
Log.i("animate", "animo1");
arg0.setAnimation(an1);
if(no[n]<=12)
{
arg1.setText(""+no[n]);
arg0.setBackgroundResource(android.R.color.white);
}
else
{
arg1.setText(""+(no[n]-12));
arg0.setBackgroundResource(android.R.color.white);
}
arg0.setTag(no[n]);
count[counter] = arg0;
counter++;
Log.i("animate", "animo2");
Uri uri = Uri.parse("android.resource://com.game/drawable/ic_launcher");
int temp1 = (Integer) count[1].getTag();
int temp2 = (Integer) arg0.getTag();
Log.i("animate", "animo3");
if((temp1-temp2)==-12 || temp1-temp2==12)
{
rem[1]=count[1];
rem[2]=count[2];
s_c=true;
score=score+10;
score_lbl.setText("Score : "+score);
score=score+10;
score_lbl.setText("Score : "+score);
level_counter=level_counter-2;
}
else
{
rev_count++;
revise[rev_count]=count[1];
rev_count++;
revise[rev_count]=count[2];
r_c=true;
score=score-2;
score_lbl.setText("Score : "+score);
}
counter=1;
}
}
I don't think I understand your situation fully.
1. Create an array of String resources:
private Integer[] Strings = { many, strings, R.string.stringa };
2. Call a method to get a random resource:
getRandomString(int);
3. Return a random String:
private String getRandomString(int random)
return getString( Strings[ random ] );

Check ArrayList contains any data

I've 3 ScreenSlidePageFragment objects. I'm showing my data by parsing a json file. Here is my main activity code :
public class ScheduleMainActivity extends FragmentActivity {
/*
* Parsing JSON to get the array length
*/
private void getLength() {
try {
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
.getResources().openRawResource(R.raw.program)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
totalPages = jsonArray.length();
for(int counter = 0 ; counter < NUM_PAGES ; counter ++){
JSONObject jsonObject = jsonArray.getJSONObject(counter);
String getDate = jsonObject.getString("date");
ScheduleItem.dateWay.add(getDate);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static int totalPages; //value = 3
/**/
/**
* The pager widget, which handles animation and allows swiping horizontally
* to access previous and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
getLength();
mPager = (ViewPager)findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
supportInvalidateOptionsMenu();
}
});
}
/**
* A simple pager adapter that represents ScreenSlidePageFragment objects,
* in sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
//Log.e("#MA", position + "");
return ScheduleSlideFragment.create(position, mPager);
}
#Override
public int getCount() {
return totalPages;
}
}
}
Now, I want to check if any previous date contains in data ArrayList. So, I tried this
if(!ScheduleItem.dateWay.get(getPageNumber).contains(data.get(getPageNumber).getDate())){
jsonParseData(getPageNumber);
}
And It throws IndexOutOfBoundsException: Invalid index 0, size is 0.
Here is my ScheduleSlideFragment code
public class ScheduleSlideFragment extends Fragment {
final static String ARG_PAGE = "page";
private static ViewPager pager;
private static int pageNumber;
final static int totalPages = ScheduleMainActivity.totalPages;
//#SuppressWarnings("unchecked")
//public List<ScheduleItem>[] data = (ArrayList<ScheduleItem>[])new ArrayList[totalPages];
public ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
public int getPageNumber;
private void jsonParseData(int _getPageNumber) {
try {
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
.getResources().openRawResource(R.raw.program)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
// Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
_getPageNumber = getPageNumber;
JSONObject jsonObject = jsonArray.getJSONObject(_getPageNumber);
String getDate = jsonObject.getString("date");
JSONArray getFirstArray = new JSONArray(jsonObject.getString("events"));
for (int i = 0; i < getFirstArray.length(); i++) {
JSONObject getJSonObj = (JSONObject)getFirstArray.get(i);
String time = getJSonObj.getString("time");
//Log.e("Time Log",time);
String type = getJSonObj.getString("type");
String title = getJSonObj.getString("title");
int typeId = getJSonObj.getInt("type_id");
data.add(new ScheduleItem(time, title, typeId, getDate));
/*
* Get Events
*/
if (typeId == 0) {
JSONArray getEventsArray = new JSONArray(getJSonObj.getString("events"));
for (int j = 0; j < getEventsArray.length(); j++) {
JSONObject getJSonEventobj = (JSONObject)getEventsArray.get(j);
int typeEventId = getJSonEventobj.getInt("type_id");
if (typeEventId == 1) {
String EventInfo = getJSonEventobj.getString("info");
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, EventInfo,
typeEventId, getDate));
} else {
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, typeEventId,
getDate));
}
}
}
}
} catch (Exception e) {
Log.getStackTraceString(e);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.schedule, container, false);
getPageNumber = pageNumber;
/**
* JSON Parsing
*/
if(!ScheduleItem.dateWay.get(getPageNumber).contains(data.get(getPageNumber).getDate())){
jsonParseData(getPageNumber);
}
/**
* Set header date
*/
((TextView)rootView.findViewById(R.id.tvDay)).setText(data.get(pageNumber).getDate().toString());
final ListView list = (ListView)rootView.findViewById(R.id.list);
BinderData bindingData = new BinderData(this.getActivity(), data);
list.setAdapter(bindingData);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (data.get(position).getItemType() == 0
|| data.get(position).getItemType() == 3
|| data.get(position).getItemType() == 2)
return;
Intent intent = new Intent(ScheduleSlideFragment.this.getActivity(),
ContentExtended.class);
intent.putExtra("title", data.get(position).getTitle());
intent.putExtra("content", data.get(position).getContent());
startActivity(intent);
}
});
ImageButton ibLeft = (ImageButton)rootView.findViewById(R.id.ibLeft);
if (pageNumber == 0)
ibLeft.setVisibility(View.INVISIBLE);
else
ibLeft.setVisibility(View.VISIBLE);
ibLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() > 0)
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
});
ImageButton ibRight = (ImageButton)rootView.findViewById(R.id.ibRight);
if (pageNumber + 1 == totalPages)
ibRight.setVisibility(View.INVISIBLE);
else
ibRight.setVisibility(View.VISIBLE);
ibRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() < totalPages)
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
});
return rootView;
}
public static Fragment create(int position) {
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
public static Fragment create(int position, ViewPager _pager) {
pageNumber = position;
pager = _pager;
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARG_PAGE);
}
}
My main problem is :
The data array contains all the data for one day/page at each position. In the current implementation(Without If condition), whenever someone opens say page three all data for page three is loaded, converted and stored in data at position 2.If we use such a data array the individual entries should not be recreated all of the time. So, I want to use a if condition to check data is available.
My Question is :
1) What are the alternatives way to way to check if data ArrayList contains any data??
2)How can I solve the the IndexOutOfBoundsException problem?
1) What are the alternatives way to way to check if data ArrayList
contains any data??
To check if an ArrayList contains any data, use the isEmpty() method, like so:
ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
if (!data.isEmpty()) { //data is not empty, meaning there is data....
2)How can I solve the the IndexOutOfBoundsException problem?
IndexOutOfBoundsException is thrown when you try to get an item in an indexed position that is out of range.
Out of range is when between [0, size() - 1] where size() is the size of the ArrayList().
To simply check if you're out of bounds, do something of this effect...
if ( i < 0 || i >= size()) { // Don't get item from an ArrayList, it's out of bounds
In your case:
if ( _getPageNumber >=0 && _getPageNumber < data.size()) { //Get item from jsonArray...
I hope this helps.
Answering your questions
1) You can check if data has any data with if (data != null && data.size() > 0)
2) You can avoid IndexOutOfBoundsException by validating that if (getPageNumber > 0 && getPageNumber < data.size())
I think first place to look for general purpose java APIs is Apache Commons. For your particular case (check if a collection is not empty) - see http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections/CollectionUtils.html#isEmpty%28java.util.Collection%29.

My method returns NULL instead of returning a 2D array

I defined my method as below and would like to return a 2D array but instead it returns a NULL . Can some one tell me whats wrong with this?
public String[][] parseInput150(String[] inputPercent150, String[][] input150Parsed ) {
String inputPer150fromXML = getResources().getString(R.string.InputPercent150);
inputPercent150 = inputPer150fromXML.split(Pattern.quote("|"));
input150Parsed = new String[inputPercent150.length-1][];
for (int i = 1; i < inputPercent150.length; i++) {
input150Parsed[i-1] = inputPercent150[i].split(Pattern.quote(" "));
}
for (int i = 0; i < input150Parsed.length; i++){
Log.e("TAG","Parsed Array value = " + Arrays.toString(input150Parsed[i]));
}
return input150Parsed;
}
The method call is below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
operationalSoldiers = (EditText) findViewById(R.id.operationalSoldiers);
operationalSoldiers.setText("150");
initialInput = setinitialInput(initialInput);
input150Parsed = parseInput150(inputPercent150, input150Parsed);
listView = (ListView) findViewById(R.id.list);
selectAll = (Button) findViewById(R.id.selectAll);
deselectAll = (Button) findViewById(R.id.deselectAll);
ArrayAdapter<String> adapter;
array = getResources().getStringArray(R.array.facilities);
strings1 = new ArrayList(Arrays.asList(array));
TopicSelectionListAdapter topicSelectionListAdapter = new TopicSelectionListAdapter(
second.this, R.layout.listrow, strings1);
listView.setAdapter(topicSelectionListAdapter);
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
for(int i=0;i<strings1.size();i++){
listView.setItemChecked(i, false);
}
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
CheckedTextView selectedItem = (CheckedTextView) view;
boolean isChecked = selectedItem.isChecked();
Log.e("TAG","item clicked position = " + position + " isChecked = " + isChecked);
for(int i=0; i< strings1.size(); i++){
if(!isChecked){
bArray[i]= 1;
}
else{
bArray[i]= 0;
}
System.out.print(bArray[i]);
}Log.e("TAG","boolean Array value = " + bArray);
}
});
selectAll.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
for(int i=0;i<strings1.size();i++){
listView.setItemChecked(i, true);
bArray[i]= 1;
}
totalSoldiers = (int) (operationalSoldiers.getAlpha() + (operationalSoldiers.getAlpha() * 0.13));
for (int r=0; r < input150Parsed.length; r++ ){
for(int c=0; c < input150Parsed[r].length; c++){
calculatedParValues[r][c] = ((totalSoldiers * (Integer.valueOf(input150Parsed[r][c]))) * Integer.valueOf(initialInput[c]));
}
}
for (int i = 0; i < calculatedParValues.length; i++){
Log.e("TAG","Parsed parameter value = " + Arrays.toString(calculatedParValues[i]));
}
}
});

Categories

Resources