how to pass map values to adapter - java

I have this adapter
public class BookcaseAdapter extends SectionableAdapter implements
View.OnClickListener {
private Activity activity;
private Map<String, List<Sponsor>> mSponsorMap;
public BookcaseAdapter(Activity activity, LayoutInflater inflater,
int rowLayoutID, int headerID, int itemHolderID, int resizeMode, Map<String, List<Sponsor>> sponsorMap) {
super(inflater, rowLayoutID, headerID, itemHolderID, resizeMode);
this.activity = activity;
mSponsorMap = sponsorMap;
}
#Override
public Object getItem(int position) {
for (int i = 0; i < mSponsorMap.size(); ++i) {
if (position < mSponsorMap.get(i).size()) {
return mSponsorMap.get(i).get(position);
}
position -= mSponsorMap.get(i).size();
}
// This will never happen.
return null;
}
#Override
protected int getDataCount() {
int total = 0;
for (int i = 0; i < mSponsorMap.size(); ++i) {
total += mSponsorMap.get(i).size();
}
return total;
}
#Override
protected int getSectionsCount() {
return mSponsorMap.size();
}
#Override
protected int getCountInSection(int index) {
return mSponsorMap.get(index).size();
}
#Override
protected int getTypeFor(int position) {
int runningTotal = 0;
int i = 0;
for (i = 0; i < mSponsorMap.size(); ++i) {
int sectionCount = mSponsorMap.get(i).size();
if (position < runningTotal + sectionCount)
return i;
runningTotal += sectionCount;
}
// This will never happen.
return -1;
}
#Override
protected String getHeaderForSection(int section) {
List<List<Sponsor>> l = new ArrayList<List<Sponsor>>(mSponsorMap.values());
String string = l.get(section).get(0).getCountry_name();
return string;
}
#Override
protected void bindView(View convertView, int position) {
String title = (String) getItem(position);
ImageView label = (ImageView) convertView
.findViewById(R.id.bookItem_title);
label.setImageResource(R.drawable.place_holder_thumb);
convertView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEARCH);
ImageView label = (ImageView) v.findViewById(R.id.bookItem_title);
// String text = label.getText().toString();
// i.putExtra(SearchManager.QUERY, text);
// activity.startActivity(i);
label.setImageResource(R.drawable.place_holder_thumb);
}
}
When from my activity I call this adapter and pass to sponsorMap values it's getting null and I have null pointer exceptoin.
I debug it found that when I call adapter and it's reach to super(inflater, rowLayoutID, headerID, itemHolderID, resizeMode); and after that called
#Override
protected int getSectionsCount() {
return mSponsorMap.size();
}
I'am sure that mSponsorMap=sponsormap not called ever. Why this is happening?

It will be called but later, the exception you got when the the super constructor is invoked prevent your constructor code from being actually reached.
Just add an NPE guard in your overriden method:
#Override
protected int getSectionsCount() {
return mSponsorMap == null ? 0 : mSponsorMap.size();
}
Alternatively you could also initialize your mSponsorMap to an empty Map:
private Map<String, List<Sponsor>> mSponsorMap = Collections.emptyMap();
And then in your constructor do:
mSponsorMap.putAll(sponsorMap);
Cheers,

Related

ListView Scrolling Problem and Performance Tips

I want to know something...
What's wrong about my ListView, the problem is when I perform a fast scroll sometimes my application stopped...
In my MainActivity extending the a4 class ----> that extends Activity class:
ArrayList<a> AL;
static ListView LV;
SearchView SV;
Toast TOAST;
TextView TV;
static boolean isEnglish;
private static boolean isSearching, canClear;
static MultiList newAdapter;
LinearLayout NV;
static RelativeLayout.LayoutParams PR;
ImageButton IB;
ImageView IV;
public void closeSearch(View view) {
if (!isSearching) return;
TV.setVisibility(0);
IB.setVisibility(8);
SV.onActionViewCollapsed();
PR.removeRule(9);
isSearching = false;
}
public void d(View view) {
num(true, 5, 0, 8);
}
public void e(View view) {
num(false, 6, 8, 0);
}
public void goInfo(View view) {
co(3);
}
public void goIns(View view) {
co(2);
}
public void goSet(View view) {
co(4);
}
public void goTools(View view) {
co(1);
}
void num(boolean bl, final int n, int n2, int n3) {
int n4 = 0;
isEnglish = bl;
AL = new ArrayList<a>();
newAdapter = new MultiList(this, true, AL);
findViewById(R.id.l1).setVisibility(n2);
findViewById(R.id.l2).setVisibility(n3);
LV.setAdapter(newAdapter);
LV.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> adapterView, View view, int ol, long l) {
rt(n, ol);
}
});
do {
if(bl){
if(n4 >= songs_e.length || n4 >= singers_e.length) return;
AL.add(new a(songs_e[n4], singers_e[n4]));
} else {
if(n4 >= artists.length) return;
AL.add(new a(artists[n4]));
}
++n4;
} while (true);
}
public void onBackPressed() {
if(isSearching) {
closeSearch(isViewed);
} else {
if (b0 < System.currentTimeMillis() - 1600L) {
TOAST = Toast.makeText(this, "Tap again to exit " + app, 0);
TOAST.show();
b0 = System.currentTimeMillis();
return;
} else {
if (TOAST != null) {
TOAST.cancel();
finish();
return;
}
}
}
}
#Override
protected void onCreate(Bundle bundle) {
show(4, R.layout.slist, q + app, 0);
LV = findViewById(R.id.lv);
SV = findViewById(R.id.search);
TV = findViewById(R.id.mytv);
NV = findViewById(R.id.llp);
PR = (RelativeLayout.LayoutParams)SV.getLayoutParams();
IB = findViewById(R.id.search_close);
IV = (ImageView)findViewById((View)SV, "android:id/search_close_btn");
final TextView actv = (TextView)findViewById(SV, "android:id/search_src_text");
actv.setBackgroundColor(-1);
ImageView imageView2 = (ImageView)findViewById((View)SV, "android:id/search_button");
imageView2.setImageResource(R.drawable.ic_search);
imageView2.setBackgroundColor(-12369085);
LV.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> av, View v, int n, long l){
return true;
}
});
IV.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
if(canClear){
actv.setText("");
}
}
});
d(isViewed);
newAdapter.initForMulti(R.layout.abc_listview, R.id.txt1, R.id.txt2, R.id.image, R.drawable.abc_tab);
SV.setLayoutParams(PR);
SV.setQueryHint(" Search songs and artists . . .");
SV.setOnSearchClickListener(new View.OnClickListener(){
public void onClick(View view) {
IV.setImageResource(R.drawable.search_clear_inactive);
TV.setVisibility(8);
canClear = false;
isSearching = true;
IB.setVisibility(0);
PR.addRule(9);
}
});
SV.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
public boolean onQueryTextChange(String string2) {
ArrayList<a> arrayList = new ArrayList<a>();
if(string2.equals((Object)"")) {
IV.setImageResource(R.drawable.search_clear_inactive);
canClear = false;
} else {
IV.setImageResource(R.drawable.search_clear_active);
canClear = true;
}
//Error for Tagalog, text is not for multi
for (a aa : MainActivity.this.AL) {
if (isEnglish && !aa.getFirst().toLowerCase().contains(string2) && !aa.getFirst().toUpperCase().contains(string2) && !aa.getFirst().contains(string2) && !aa.getLast().toLowerCase().contains(string2) && !aa.getLast().toUpperCase().contains(string2) && !aa.getLast().contains(string2) || !isEnglish && !aa.getLast().toLowerCase().contains(string2) && !aa.getLast().toUpperCase().contains(string2) && !aa.getLast().contains(string2)) continue;
arrayList.add(aa);
}
newAdapter.filterResult((ArrayList<a>)arrayList);
return false;
}
public boolean onQueryTextSubmit(String string2) {
return true;
}
});
MusicUtils.playAsset(this, "audios/a.ogg");
IV.setBackgroundColor(-12369085);
super.onCreate(bundle);
}
public void onPause() {
super.onPause();
closeSearch(isViewed);
if (in != 5 && in != 6) {
LV.setVisibility(4);
int n = 0;
do {
if (n >= 10) return;
LV.scrollListBy(-999999999);
++n;
} while (true);
}
}
//onRestart not included because it basically contains setVisibility
final void rt(int n, int n2) {
in = n;
Bundle bundle = new Bundle();
newAdapter.getLC(n2);
bundle.putString("First", newAdapter.list.getFirst());
bundle.putString("Last", newAdapter.list.getLast());
go(new Intent(this, ContProv.class).putExtras(bundle));
}
And for the custom list adapter:
private static Context Context;
private static ArrayList<a> ab;
private static int view, mText, mText1, mText2, mImage, mDrawable;
private static boolean listType;
public a list;
public MultiList(Context c, boolean isMultiText, ArrayList<a> array) {
if(c != null || array != null) {
Context = c;
listType = isMultiText;
ab = array;
}
}
public final void initForMulti(int layout, int text1ID, int text2ID, int imageID, int imageDrawable) {
view = layout;
mText1 = text1ID;
mText2 = text2ID;
mImage = imageID;
mDrawable = imageDrawable;
}
public final void initForNonMulti(int layout, int textID, int imageID, int imageDrawable){
view = layout;
mText = textID;
mImage = imageID;
mDrawable = imageDrawable;
}
public void filterResult(ArrayList<a> arrayList) {
ab = new ArrayList<a>();
ab.addAll((ArrayList<a>)arrayList);
notifyDataSetChanged();
}
public int getCount() {
return ab.size();
}
public Object getItem(int n) {
return null;
}
public long getItemId(int n) {
return 0L;
}
public a getLC(int n) {
return list = ab.get(n);
}
public View getView(int n, View v, ViewGroup vg) {
a newList = getLC(n);
v = View.inflate(Context, view, null);
((ImageView)v.findViewById(mImage)).setImageResource(mDrawable);
if(listType) {
((TextView)v.findViewById(mText1)).setText(newList.getFirst());
((TextView)v.findViewById(mText2)).setText(newList.getLast());
} else ((TextView)v.findViewById(mText)).setText(newList.getText());
return v;
}
Thank you for your help... I will really appreciate it... Also I need tips about the performance of my existing code and please write your answer in java and don't use support libraries cuz I want my application work for android phones below android 5...
Final:
I've found out that the problem is at my list adapter so I edited it into this:
package dn.widget;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import dn.widget.ListAdapter;
import dn.widget.a.a;
import java.util.ArrayList;
public class ListAdapter extends BaseAdapter {
private ArrayList<a> AR;
private static int N, N2, N3, N4, N5, N6;
private boolean LT;
public a L;
public ListAdapter(ArrayList<a> ar, boolean b) {
AR = ar;
LT = b;
}
public void isDual(int n, int n2, int n3, int n4, int n5) {
if (LT) {
N = n;
N3 = n2;
N4 = n3;
N5 = n4;
N6 = n5;
}
}
public void isSingle(int n, int n2, int n3, int n4){
if (!LT) {
N = n;
N2 = n2;
N4 = n3;
N5 = n4;
}
}
public void filterResult(ArrayList<a> ar) {
if(AR != null) {
AR = new ArrayList<a>();
AR.addAll((ArrayList<a>)ar);
notifyDataSetChanged();
}
}
public int getCount() {
return AR.size();
}
public Object getItem(int n) {
return null;
}
public long getItemId(int n) {
return 0L;
}
public a getLC(int n) {
L = AR.get(n);
return L;
}
static class LH {
private ImageView I;
private TextView T, T1, T2;
}
#Override
public View getView(int n, View v, ViewGroup g) {
getLC(n);
final LH h;
if(v == null) {
v = View.inflate(g.getContext(), N, null);
h = new LH();
h.I = v.findViewById(N5);
h.T = v.findViewById(N2);
h.T1 = v.findViewById(N3);
h.T2 = v.findViewById(N4);
h.I.setImageResource(N6);
v.setTag(h);
} else {
h = (LH)v.getTag();
}
if(LT) {
h.T1.setText(L.f());
h.T2.setText(L.l());
} else h.T.setText(L.t());
return v;
}
}

How to make expandable cardview childlist in recycle view by reusing the same layout

I want to make view by adding child list on android using cardview in recycleview.
i have made class to store these item and make arraylist on each parent of object if the object have child item, so i can differentiate if the list has child or not.
But i have difficulties to render the same layout to make the child list below the parent list. I am pragmatically make the layout one by one but it will be difficult to make that. So i want to render the same layout to my adapter when i want to make a child list whenever the object/class has arraylist of child list in that object.
this is my adapter right now
public class NotificationListAdapter extends BaseListAdapter<NotificationData, NotificationListAdapter.CustomViewHolder> {
private List<NotificationData> notificationData;
private ArrayList<Integer> indexForHide;
public NotificationListAdapter(Context context) {
super(context);
}
#Override
public void addAll(List<NotificationData> items) {
super.addAll(items);
this.notificationData = items;
}
void setChildNotif(){
ArrayList<NotificationData> childDataItems;
List<NotificationData> notificationDataChild = new ArrayList<NotificationData>();
notificationDataChild.addAll(notificationData);
indexForHide = new ArrayList<Integer>();
for (int i = 0; i < notificationData.size(); i++) {
childDataItems = new ArrayList<>();
if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}
for (int j = i; j < notificationDataChild.size(); j++){
if(i==j){
continue;
}else if (notificationDataChild.size() == 1) {
notificationData.get(i).setChildNotification(childDataItems);
break;
}else{
if(notificationDataChild.get(j).getRfqId()!=0){
if(notificationDataChild.get(j).getRfqId()==notificationData.get(i).getRfqId()){
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
if(!notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase("")) {
if (notificationDataChild.get(j).getInvoiceNumber().equalsIgnoreCase(notificationData.get(i).getInvoiceNumber())) {
childDataItems.add(notificationDataChild.get(j));
indexForHide.add(j);
}
}
}
}
notificationData.get(i).setChildNotification(childDataItems);
Log.d("sizeNotif", i+" :"+notificationData.get(i).getChildNotification().size());
}
Log.d("sizeNotification", " :"+notificationData.size());
Log.d("sizeNotificationDummy", " :"+notificationData.size());
Log.d("isiHideAdapter", Arrays.toString(indexForHide.toArray()));
Log.d("isiHideAdapterSize", indexForHide.size()+"");
}
#Override
protected int getItemResourceLayout(int viewType) {
return R.layout.item_notification_list;
}
int position;
#Override
public int getItemViewType(int position) {
this.position = position;
return position;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
setChildNotif();
return new CustomViewHolder(getView(parent, viewType), onItemClickListener);
}
public class CustomViewHolder extends BaseViewHolder<NotificationData> {
private TextView tvNotifTitle, tvNotifBody, tvNotifStatus, tvNotifTime, tvSignUnread, tvHeaderTitle;
private CardView formContent;
private LinearLayout linearLayout_childItems;
private ImageView expandList;
public CustomViewHolder(View itemView, OnItemClickListener onItemClickListener) {
super(itemView, onItemClickListener);
tvNotifTitle = itemView.findViewById(R.id.tvNotifTitle);
tvNotifBody = itemView.findViewById(R.id.tvNotifBody);
// tvNotifStatus = itemView.findViewById(R.id.tvNotifStatus);
tvNotifTime = itemView.findViewById(R.id.tvNotificationTime);
formContent = itemView.findViewById(R.id.formContent);
tvSignUnread = itemView.findViewById(R.id.tvSignUnread);
tvHeaderTitle = itemView.findViewById(R.id.tvHeaderNotifList);
linearLayout_childItems = itemView.findViewById(R.id.ll_child_items);
expandList = itemView.findViewById(R.id.arrow_expand_notif_list);
//SET CHILD
int intMaxNoOfChild = 0;
for (int index = 0; index < notificationData.size(); index++) {
int intMaxSizeTemp = notificationData.get(index).getChildNotification().size();
if (intMaxSizeTemp > intMaxNoOfChild) intMaxNoOfChild = intMaxSizeTemp;
}
linearLayout_childItems.removeAllViews();
for (int indexView = 0; indexView < intMaxNoOfChild; indexView++) {
TextView textView = new TextView(context);
textView.setId(indexView);
textView.setPadding(20, 20, 0, 20);
textView.setGravity(Gravity.LEFT);
textView.setTextSize(14);
textView.setTextColor(ContextCompat.getColor(context, R.color.colorText));
textView.setBackground(ContextCompat.getDrawable(context, R.drawable.bg_sub_notif_text));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 16;
textView.setOnClickListener(this);
linearLayout_childItems.addView(textView, layoutParams);
}
}
#Override
public void bind(NotificationData item) {
String title = splitString(item.getTitle());
tvNotifTitle.setText(title);
tvNotifBody.setText(item.getContent());
String txtTime = item.getCreatedAtDisplay().replaceAll("WIB", "");
tvNotifTime.setText(txtTime);
if (position == 0) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).topMargin = dpToPx(12);
}
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(12);
if (position == getItemCount() - 1) {
((ViewGroup.MarginLayoutParams) formContent.getLayoutParams()).bottomMargin = dpToPx(80);
}
if(item.getIsRead()==1){
formContent.setCardBackgroundColor(context.getResources().getColor(R.color.gray1));
formContent.setCardElevation(5);
formContent.setRadius(15);
tvSignUnread.setVisibility(View.GONE);
}else if(item.getIsRead()==0){
}
//setHeader
Calendar calendar;
SimpleDateFormat dateFormat;
calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("yyyy-MM-dd") ;
String date, yesterdayDate, dateDisplayData, dateData;
date = dateFormat.format(calendar.getTime());
calendar.add(Calendar.DATE, -1);
yesterdayDate = dateFormat.format(calendar.getTime());
String[] arrDateDisplayData = item.getCreatedAtDisplay().split(",", 5);
dateDisplayData = arrDateDisplayData[0];
String[] arrDateData = item.getCreatedAt().split(" ", 5);
dateData = arrDateData[0];
Log.d("datenow", date);
Log.d("dateyesterday", yesterdayDate);
Log.d("dateDisplayData", dateDisplayData);
Log.d("dateData", dateData);
if(dateData.equalsIgnoreCase(date)){
tvHeaderTitle.setText("Hari ini");
}else if(dateData.equalsIgnoreCase(yesterdayDate)){
tvHeaderTitle.setText("Kemarin");
}else{
tvHeaderTitle.setText(dateDisplayData);
// tvHeaderTitle.setVisibility(View.GONE);
}
if (getAdapterPosition() > 0) {
String[] timePrev = notificationData.get(getAdapterPosition() - 1).getCreatedAt().split(" ");
if (dateData.equalsIgnoreCase(timePrev[0])) {
tvHeaderTitle.setVisibility(View.GONE);
}
}
if(indexForHide.contains(getAdapterPosition())){
formContent.setVisibility(View.GONE);
}
//SET CHILD
NotificationData dummyParentDataItem = notificationData.get(position);
int noOfChildTextViews = linearLayout_childItems.getChildCount();
for (int index = 0; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
currentTextView.setVisibility(View.VISIBLE);
}
int noOfChild = 0;
if(dummyParentDataItem.getChildNotification()==null){
noOfChild = 0;
}else{
noOfChild = dummyParentDataItem.getChildNotification().size();
}
if (noOfChild < noOfChildTextViews) {
for (int index = noOfChild; index < noOfChildTextViews; index++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(index);
// currentTextView.setVisibility(View.GONE);
}
}
for (int textViewIndex = 0; textViewIndex < noOfChild; textViewIndex++) {
TextView currentTextView = (TextView) linearLayout_childItems.getChildAt(textViewIndex);
currentTextView.setText(dummyParentDataItem.getChildNotification().get(textViewIndex).getTitle());
/*currentTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "" + ((TextView) view).getText().toString(), Toast.LENGTH_SHORT).show();
}
});*/
}
if (noOfChild > 0) {
expandList.setVisibility(View.VISIBLE);
expandList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (linearLayout_childItems.getVisibility() == View.VISIBLE) {
linearLayout_childItems.setVisibility(View.GONE);
// Toast.makeText(context, "expand", Toast.LENGTH_SHORT).show();
expandList.setImageResource(R.drawable.ic_arrow_up_blue);
}
else {
linearLayout_childItems.setVisibility(View.VISIBLE);
expandList.setImageResource(R.drawable.ic_arrow_down_blue);
}
}
});
}else {
linearLayout_childItems.setVisibility(View.GONE);
}
}
public int dpToPx(int dp) {
Resources r = context.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp, r.getDisplayMetrics()
);
return px;
}
public String splitString(String tempString){
StringBuilder finalString = new StringBuilder(tempString);
int i = 0;
while ((i = finalString.indexOf(" ", i + 20)) != -1) {
finalString.replace(i, i + 1, "\n");
}
return finalString.toString();
}
}
}
please help me to render my layout whenever i want to make a child list under my parent list so i can simplify my code above and not making the child layout programatically

How to add parcelable arraylist to section recycler view adapter

In my application i'm trying to pass an parcelable array list to a sectioned recycler view adapter but inside the add method where we add sections it gives me required string error:
This is my parcelable class:
public class HostBean implements Parcelable {
public static final String EXTRA = ActivityMain.PKG + ".extra";
public static final String EXTRA_POSITION = ActivityMain.PKG + ".extra_position";
public static final String EXTRA_HOST = ActivityMain.PKG + ".extra_host";
public static final String EXTRA_TIMEOUT = ActivityMain.PKG + ".network.extra_timeout";
public static final String EXTRA_HOSTNAME = ActivityMain.PKG + ".extra_hostname";
public static final String EXTRA_BANNERS = ActivityMain.PKG + ".extra_banners";
public static final String EXTRA_PORTSO = ActivityMain.PKG + ".extra_ports_o";
public static final String EXTRA_PORTSC = ActivityMain.PKG + ".extra_ports_c";
public static final String EXTRA_SERVICES = ActivityMain.PKG + ".extra_services";
public static final int TYPE_GATEWAY = 0;
public static final int TYPE_COMPUTER = 1;
public int deviceType = TYPE_COMPUTER;
public int isAlive = 1;
public int position = 0;
public int responseTime = 0; // ms
public String ipAddress = null;
public String hostname = null;
public String hostsection = null;
public String hardwareAddress = NetInfo.NOMAC;
public String nicVendor = "Unknown";
public String os = "Unknown";
public HashMap<Integer, String> services = null;
public HashMap<Integer, String> banners = null;
public ArrayList<Integer> portsOpen = null;
public ArrayList<Integer> portsClosed = null;
public HostBean() {
// New object
}
public HostBean(Parcel in) {
// Object from parcel
readFromParcel(in);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(deviceType);
dest.writeInt(isAlive);
dest.writeString(ipAddress);
dest.writeString(hostname);
dest.writeString( hostsection );
dest.writeString(hardwareAddress);
dest.writeString(nicVendor);
dest.writeString(os);
dest.writeInt(responseTime);
dest.writeInt(position);
dest.writeMap(services);
dest.writeMap(banners);
dest.writeList(portsOpen);
dest.writeList(portsClosed);
}
private void readFromParcel(Parcel in) {
deviceType = in.readInt();
isAlive = in.readInt();
ipAddress = in.readString();
hostname = in.readString();
hardwareAddress = in.readString();
nicVendor = in.readString();
os = in.readString();
hostsection=in.readString();
responseTime = in.readInt();
position = in.readInt();
services = in.readHashMap(null);
banners = in.readHashMap(null);
portsOpen = in.readArrayList(Integer.class.getClassLoader());
portsClosed = in.readArrayList(Integer.class.getClassLoader());
}
#SuppressWarnings("unchecked")
public static final Creator CREATOR = new Creator() {
public HostBean createFromParcel(Parcel in) {
return new HostBean(in);
}
public HostBean[] newArray(int size) {
return new HostBean[size];
}
};
}
This is my simple adapter class:
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private ArrayList<HostBean> mData;
final HostBean host = new HostBean();
public void add(HostBean s,int position) {
position = position == -1 ? getItemCount() : position;
host.hostsection=s;
mData.add(position,s); //at this line of code i'm getting error
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView mac;
public final TextView vendor;
public final TextView ip;
public SimpleViewHolder(View view) {
super(view);
ip = (TextView) view.findViewById(R.id.ip);
mac = (TextView) view.findViewById(R.id.mac);
vendor = (TextView) view.findViewById(R.id.vendor);
}
}
public SimpleAdapter(Context context, List<HostBean> data) {
mContext = context;
if (data != null)
mData = new ArrayList<HostBean>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.list_host, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.ip.setText( (CharSequence) mData.get(position) );
holder.mac.setText( "" );
holder.vendor.setText( "" );
}
#Override
public int getItemCount() {
return mData.size();
}
}
This is my simple sectioned recyclerview adapter class:
public class SimpleSectionedRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private static final int SECTION_TYPE = 0;
private boolean mValid = true;
private int mSectionResourceId;
private int mTextResourceId;
private LayoutInflater mLayoutInflater;
private RecyclerView.Adapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
mBaseAdapter = baseAdapter;
mContext = context;
mBaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
mValid = mBaseAdapter.getItemCount()>0;
notifyDataSetChanged();
}
#Override
public void onItemRangeChanged(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeChanged(positionStart, itemCount);
}
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeInserted(positionStart, itemCount);
}
#Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeRemoved(positionStart, itemCount);
}
});
}
public static class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public SectionViewHolder(View view, int mTextResourceid) {
super(view);
title = (TextView) view.findViewById(mTextResourceid);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int typeView) {
if (typeView == SECTION_TYPE) {
final View view = LayoutInflater.from(mContext).inflate(mSectionResourceId, parent, false);
return new SectionViewHolder(view,mTextResourceId);
}else{
return mBaseAdapter.onCreateViewHolder(parent, typeView -1);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder sectionViewHolder, int position) {
if (isSectionHeaderPosition(position)) {
((SectionViewHolder)sectionViewHolder).title.setText(mSections.get(position).title);
}else{
mBaseAdapter.onBindViewHolder(sectionViewHolder,sectionedPositionToPosition(position));
}
}
#Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? SECTION_TYPE
: mBaseAdapter.getItemViewType(sectionedPositionToPosition(position)) +1 ;
}
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
#Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
#Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
#Override
public int getItemCount() {
return (mValid ? mBaseAdapter.getItemCount() + mSections.size() : 0);
}
}
This is how is initialize the arraylist:
hosts = new ArrayList<HostBean>();
This is my activity code for setting adapter to recyclerview:
RecyclerView list =findViewById(R.id.output);
list.setHasFixedSize( true );
list.setLayoutManager( new LinearLayoutManager( this ) );
list.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
SimpleAdapter mAdapter = new SimpleAdapter(this,hosts);
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0,"Know Devices"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5,"Unknown Devices"));
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(this,R.layout.section,R.id.section_text,mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
list.setAdapter( mSectionedAdapter );
Your mData is an ArrayList<>. Therefore you can not pass key, value for that. You can only pass one param, either key or value. List is not a map.
private ArrayList<HostBean> mData;
mData.add(position,s); // Can not do this
If you want a key value relationship, then use HashMap like this.
private HashMap<Integer, HostBean> mData;

How to get int value from one method to another

I need to carry my int value from one method to another, but I didnt find any solution. One method counts number of objects and the number needs to be "delivered" to another and check, if the count equals to something.
Do you have any idea, how to do it?
Check my codes below:
#Override
protected void onPostExecute(Void result) {
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.countInBackground(callcount = new CountCallback(){
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
//I need to export int count from "done" method to another
} else {
}
}
});
}
And the secont method, which has to recieve that value and use it:
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//i need to set int count from method above here
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter - threshold) {
updateData();
}
}
Whole code:
public class Fragment1 extends Fragment {
static ListView mListView;
static AnimalAdapter mAdapter;
static ProgressBar mProgressBar;
static EditText mEditText;
static LayoutInflater inflater;
CountCallback callcount;
int g_count = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.animalsfrag, container, false);
mListView = (ListView)rootView.findViewById(R.id.animal_list);
View header = getActivity().getLayoutInflater().inflate(R.layout.header, null);
header.setPadding(2, 8, 4, 2);
mListView.setVisibility(View.INVISIBLE);
mListView.requestFocus();
mListView.addHeaderView(header);
View footie = getActivity().getLayoutInflater().inflate(R.layout.footer, null);
mListView.addFooterView(footie);
footie.setVisibility(View.INVISIBLE);
mProgressBar = (ProgressBar) rootView.findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.VISIBLE);
RemoteDataTask task = new RemoteDataTask();
task.execute();
return rootView;
}
public void updateData() {
mListView = (ListView)getView().findViewById(R.id.animal_list);
final ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.setCachePolicy(CachePolicy.NETWORK_ONLY);
query.orderByAscending("animal");
query.setLimit(mListView.getCount() + 5);
Log.v("updateData", "uploading data from Parse.com");
query.findInBackground(new FindCallback<Animal>() {
#Override
public void done(List<Animal> animals, ParseException error) {
if(animals != null){
mAdapter.clear();
mProgressBar = (ProgressBar) getView().findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.INVISIBLE);
RelativeLayout footie = (RelativeLayout) getView().findViewById(R.id.footerview);
footie.setVisibility(View.VISIBLE);
mAdapter.clear();
for (int i = 0; i < animals.size(); i++) {
mAdapter.add(animals.get(i));
}
}
}
}); }
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute(); }
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.countInBackground(callcount = new CountCallback(){
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
if (mListView.getCount() == count) {
Log.v("all loaded", "executed");
g_count=count;
}
} else {
// The request failed
}
}
});
Log.v("onpostexecute", "executing");
mListView = (ListView) getView().findViewById(R.id.animal_list);
if(mListView.getCount() == 0){
updateData();
}
mEditText = (EditText) getView().findViewById(R.id.search_animal);
mAdapter = new AnimalAdapter(getActivity(), new ArrayList<Animal>());
mListView.setVisibility(View.VISIBLE);
mListView.setTextFilterEnabled(true);
mListView.setAdapter(mAdapter);
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter
- threshold){
updateData();
Log.v("count", "count is" + g_count);
}
}
if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
View currentFocus = getActivity().getCurrentFocus();
if(currentFocus != null) {
currentFocus.clearFocus();
}
}
}
});
mEditText.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
System.out.println("Text ["+s+"]");
mAdapter.getFilter().filter(s.toString());
}
});
}
}
}
I'd be glad for any advice.
Thanks in advance.
If you are not calling function from another then you need to create a global variable.
Declare a variable just after your class declaration i.e.
int g_count = 0;
then in
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
g_count=count;
}
Then in second fucntion
public void onScrollStateChanged(AbsListView view, int scrollState) {
int count=g_count; \\you dont really need to declare this, just use g_count
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter - threshold) {
updateData();
}
}

How to swipe zoomed image using ImageViews and PageAdapter

I am trying to create an image viewer which can load images from given URLs.The code below implement the User Interface.
My intention is to let user Zoom the image and move to next image with a Swipe event.But the problem is that when i zoom and then swipe , instead of showing the remaining portion , it moves to the next image.
I tried using requestDisallowInterceptTouchEvent in TouchImageView's(https://github.com/MikeOrtiz/TouchImageView) onTouchListener .After this the remaining portion could show but now i cannot go to the next page. I was wondering how this can be achieved as the event can only go to either TouchView or PageAdapter
public class PageActivity extends Activity {
private int numPages = 33;
private TouchImageView[] imageViews = new TouchImageView[numPages];
private String URL = "http://www.smbc-comics.com/comics/200905";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPager viewPager = new ViewPager(this);
for (int i = 0; i < numPages; i++) {
imageViews[i] = new TouchImageView(this);
imageViews[i].setBackgroundResource(R.drawable.banke);
imageViews[i].setMaxZoom(4f);
}
setContentView(viewPager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
}
#SuppressWarnings("unused")
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return numPages;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TouchImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = PageActivity.this;
String pageURL = URL;
if (imageViews[position].getDrawable() == null) {
ImageFetcher imagefetcher = new ImageFetcher();
imagefetcher.execute(
pageURL + String.format("%02d", position+1) + ".gif",
String.valueOf(position));
}
((ViewPager) container).addView(imageViews[position], 0);
return imageViews[position];
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TouchImageView) object);
imageViews[position].setImageDrawable(null);
}
}
public class ImageFetcher extends AsyncTask<String, Integer, Drawable> {
int fillthisPos;
public Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) new URL(urls[0]).getContent();
fillthisPos = Integer.parseInt(urls[1]);
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
imageViews[fillthisPos].setImageDrawable(result);
result = null;
}
}
}
You can add following code in TouchImageView class:
public boolean isZoomed () {
return (normalizedScale > minScale);
}
private void onSwipeEvent(MotionEvent event) {
boolean zoomed = this.isZoomed();
if (!zoomed && (swipeLen > 0)) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
swipeStartPos = (int) event.getRawX();
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
int distance = ((int) event.getRawX()) - swipeStartPos;
int swipeVector = SWIPE_RIGHT;
if (distance < 0) swipeVector = SWIPE_LEFT;
if (Math.abs(distance) > swipeLen) {
onSwipeHandler.onSwipe(swipeVector);
swipeStartPos = (int) event.getRawX();
this.setScaleX(1f);
}
else {
int swipeStDist = swipeLen - Math.round(((swipeLen / 100) * 50));
if (Math.abs(distance) > swipeStDist) {
this.setScaleX(0.98f);
}
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
swipeStartPos = (int) event.getRawX();
this.setScaleX(1f);
}
}
}
public static int SWIPE_LEFT = 0;
public static int SWIPE_RIGHT = 1;
public int swipeStartPos = 0;
public onSwipeListener onSwipeHandler = new onSwipeListener() {
public void onSwipe(int vector) {}
};
public static int swipeLen = 0;
public void setOnSwipeListener(onSwipeListener c, int swipeLength) {
onSwipeHandler = c;
swipeLen = swipeLength;
}
public interface onSwipeListener {
public void onSwipe(int vector);
}
And also in TouchImageView below line 636 add onSwipeEvent(event) like this:
......
setImageMatrix(matrix);
onSwipeEvent(event);
//
// indicate event was handled
//
return true;
...........
After this from you code you can add swipe event listener, like this:
imageView.setOnSwipeListener(new TouchImageView.onSwipeListener() {
#Override
public void onSwipe(int vector) {
if (vector == TouchImageView.SWIPE_LEFT) {
Log.d("swipe", "swipe left!");
}
else if (vector == TouchImageView.SWIPE_RIGHT) {
Log.d("swipe", "swipe right!");
}
}
}, 200); //length of swiping - 200 dip
This onSwipeListener ignore onswipe where image is zoomed+. It work for me.

Categories