I can't figure out why I am getting a NullPointerException with my custom BaseAdapter with different row types. I am using the ViewHolder pattern and when I get this NPE, the ViewHolder is null. But looking at my code below, wouldn't there always be a reference to a ViewHolder?
Using getItemViewType should always return a valid row layout, and I cover all of these types in the first switch statement which handles the inflating of the rows.
This line is the issues that is giving me the problem:
case TYPE_TEXT_YOU:
if (message != null) holder.message.setText(message);
It is weird because it was working fine before. I didn't change much but now it is giving me this issue. Please help!!!
public class ChatAdapter extends BaseAdapter {
private static final int TYPE_TEXT_YOU = 0;
private static final int TYPE_AUDIO_YOU = 1;
private static final int TYPE_TEXT_THEM = 2;
private static final int TYPE_AUDIO_THEM = 3;
private static final int TYPE_MATCH_NOTICE = 4;
private static final int TYPE_EMPTY_ROW = 5;
private Context mContext;
private List<ChatMessage> mMessages;
private String mPartnerUserId;
private SharedPrefs mPrefs;
private DatabaseHelper mDb;
private User mUser;
private User mPartnerUser;
private AudioHelper mAudioHelper;
public ChatAdapter(Context context, List<ChatMessage> messages, String partnerUserId) {
mContext = context;
mMessages = messages;
mPartnerUserId = partnerUserId;
mPrefs = new SharedPrefs(context);
mAudioHelper = AudioHelper.getInstance(context, partnerUserId);
mDb = DatabaseHelper.getInstance(context);
mUser = mDb.getUser(mPrefs.getUserId());
mPartnerUser = mDb.getUser(partnerUserId);
}
#Override
public int getCount() {
return mMessages.size();
}
#Override
public Object getItem(int position) {
return mMessages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
ChatMessage message = mMessages.get(position);
switch (message.getMessageType()) {
case ChatMessage.TYPE_GAME_DATE:
return TYPE_MATCH_NOTICE;
case ChatMessage.TYPE_TEXT:
if (message.getSenderUserId().equals(mPrefs.getUserId())) {
return TYPE_TEXT_YOU;
}
else {
return TYPE_TEXT_THEM;
}
case ChatMessage.TYPE_AUDIO:
if (message.getSenderUserId().equals(mPrefs.getUserId())) {
return TYPE_AUDIO_YOU;
}
else {
return TYPE_AUDIO_THEM;
}
default:
return TYPE_EMPTY_ROW;
}
}
#Override
public int getViewTypeCount() {
return 6;
}
public class ViewHolder {
private ImageView avatar;
private CustomTextView timestamp;
private CustomTextView message;
private CustomTextView date;
private CustomTextView time;
private LinearLayout btnPlayAudio;
private ImageView ivPlayAudio;
private ProgressBar spinPlayingAudio;
private CustomTextView tvPlayAudio;
private ImageView gameCover;
private ProgressBar spinGameCover;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
switch (type) {
case TYPE_TEXT_YOU:
convertView = inflater.inflate(R.layout.row_chat_you, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_you);
holder.message = (CustomTextView) convertView.findViewById(R.id.message_you);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_you);
break;
case TYPE_AUDIO_YOU:
convertView = inflater.inflate(R.layout.row_chat_audio_you, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_you);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_you);
holder.btnPlayAudio = (LinearLayout) convertView.findViewById(R.id.btn_play_audio_you);
holder.ivPlayAudio = (ImageView) convertView.findViewById(R.id.iv_play_audio);
holder.spinPlayingAudio = (ProgressBar) convertView.findViewById(R.id.spin_playing_audio);
holder.tvPlayAudio = (CustomTextView) convertView.findViewById(R.id.tv_play_audio);
break;
case TYPE_TEXT_THEM:
convertView = inflater.inflate(R.layout.row_chat_them, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_them);
holder.message = (CustomTextView) convertView.findViewById(R.id.message_them);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_them);
break;
case TYPE_AUDIO_THEM:
convertView = inflater.inflate(R.layout.row_chat_audio_them, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_them);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_them);
holder.btnPlayAudio = (LinearLayout) convertView.findViewById(R.id.btn_play_audio_them);
holder.ivPlayAudio = (ImageView) convertView.findViewById(R.id.iv_play_audio);
holder.spinPlayingAudio = (ProgressBar) convertView.findViewById(R.id.spin_playing_audio);
holder.tvPlayAudio = (CustomTextView) convertView.findViewById(R.id.tv_play_audio);
break;
case TYPE_MATCH_NOTICE:
convertView = inflater.inflate(R.layout.row_chat_match_notice, parent, false);
holder.gameCover = (ImageView) convertView.findViewById(R.id.game_cover);
holder.spinGameCover = (ProgressBar) convertView.findViewById(R.id.spin_game_cover);
holder.date = (CustomTextView) convertView.findViewById(R.id.date);
holder.time = (CustomTextView) convertView.findViewById(R.id.time);
break;
case TYPE_EMPTY_ROW:
convertView = inflater.inflate(R.layout.row_padding_10dp, parent, false);
break;
}
convertView.setTag(holder);
}
else holder = (ViewHolder) convertView.getTag();
String message = mMessages.get(position).getMessage();
String timestamp = mMessages.get(position).getTimeStamp();
final String audioFilepath = mMessages.get(position).getFilepath();
DateTime dateTime;
DateTimeFormatter formatter = DateTimeFormat.forPattern(GlobalVars.FORMAT_MESSAGE_TIMESTAMP);
final ViewHolder finalHolder = holder;
switch (type) {
case TYPE_TEXT_YOU:
if (message != null) holder.message.setText(message);
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mUser != null && mUser.getAvatarType() != null && !mUser.getAvatarType().isEmpty()) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
break;
case TYPE_AUDIO_YOU:
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mUser != null && mUser.getAvatarType() != null && !mUser.getAvatarType().isEmpty()) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
holder.btnPlayAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audioFilepath != null && !audioFilepath.isEmpty()) {
mAudioHelper.changeViewsOfStoppedAudioMessage();
mAudioHelper.setPlayingAudioViews(finalHolder.ivPlayAudio,
finalHolder.spinPlayingAudio, finalHolder.tvPlayAudio);
mAudioHelper.playAudio(audioFilepath);
}
}
});
break;
case TYPE_TEXT_THEM:
if (message != null) holder.message.setText(message);
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mPartnerUser != null && mPartnerUser.getAvatarType() != null) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mPartnerUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
break;
case TYPE_AUDIO_THEM:
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mPartnerUser != null && mPartnerUser.getAvatarType() != null) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mPartnerUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
holder.btnPlayAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audioFilepath != null && !audioFilepath.isEmpty()) {
mAudioHelper.changeViewsOfStoppedAudioMessage();
mAudioHelper.setPlayingAudioViews(finalHolder.ivPlayAudio,
finalHolder.spinPlayingAudio, finalHolder.tvPlayAudio);
mAudioHelper.playAudio(audioFilepath);
}
}
});
break;
case TYPE_MATCH_NOTICE:
if (message != null) {
if (message.contains("{")) {
Bundle info = null;
message = message.substring(message.indexOf("{"));
try {
JSONObject obj = new JSONObject(message);
info = JsonHelper.parseMatchNoticeMessageJson(obj);
}
catch (JSONException e) { e.printStackTrace(); }
if (info != null) {
if (info.containsKey(GlobalVars.KEY_GAME) && info.containsKey(GlobalVars
.KEY_PLATFORM)) {
Game game = mDb.getGame(info.getString(GlobalVars.KEY_GAME),
info.getString(GlobalVars.KEY_PLATFORM));
if (game != null && game.getCoverPhoto() != null) {
ViewHelper.loadOrDownloadGameCover(mContext, game.getCoverPhoto(),
holder.gameCover, holder.spinGameCover);
}
}
if (info.containsKey(GlobalVars.KEY_GAME_TIME)) {
String matchTime = info.getString(GlobalVars.KEY_GAME_TIME);
if (matchTime != null && !matchTime.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(matchTime);
if (dateTime != null) {
holder.date.setText(DateTimeFormat.forPattern(GlobalVars
.FORMAT_DATE_WITH_DAY_OF_WEEK).print(dateTime));
holder.time.setText(DateTimeFormat.forPattern(GlobalVars
.FORMAT_TIME).print(dateTime));
}
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
}
}
}
}
break;
}
return convertView;
}
public void refreshList(List<ChatMessage> updatedMessages) {
mMessages.clear();
mMessages.addAll(updatedMessages);
this.notifyDataSetChanged();
}
}
My Stacktrace
java.lang.NullPointerException
at com.walintukai.lovelup.adapters.ChatAdapter$ViewHolder.access$100(ChatAdapter.java:118)
at com.walintukai.lovelup.adapters.ChatAdapter.getView(ChatAdapter.java:201)
at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:230)
at android.widget.AbsListView.obtainView(AbsListView.java:2739)
at android.widget.ListView.makeAndAddView(ListView.java:1801)
at android.widget.ListView.fillUp(ListView.java:733)
at android.widget.ListView.fillGap(ListView.java:670)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:6747)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3988)
at android.widget.AbsListView.onTouchMove(AbsListView.java:4840)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:4668)
at android.view.View.dispatchTouchEvent(View.java:8135)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2417)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2141)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2295)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1622)
at android.app.Activity.dispatchTouchEvent(Activity.java:2565)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2243)
at android.view.View.dispatchPointerEvent(View.java:8343)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4743)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4609)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4167)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4221)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4190)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4301)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4198)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4358)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4167)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4221)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4190)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4198)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4167)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6517)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6434)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6405)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6370)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6597)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:138)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:5579)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(NativeStart.java)
Played around and found my answer. So I guess some of the tags of the rows were null so it would call the else statement with the convertView.getTag() which was coming up null.
The solution is to check also if convertView.getTag() == null like so:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
int type = getItemViewType(position);
if (convertView == null || convertView.getTag() == null) {
...
}
else {
holder = (ViewHolder) convertView.getTag();
}
Related
I am trying to handle multiple checkboxes in order to delete or edit elements from a list, the list has custom adapter with its custom layout, inside this layout I am creating the checkbox, however I am getting a IndexOutOfBounds exception when I am trying to evaluate a boolean array even if it has been initialized.
public MeasureTableAdapter(Activity context, ArrayList<MeasureEvi> myMeasureEvi)
{
super(context, R.layout.adapter_tablamedida_item, myMeasureEvi);
this.context = context;
this.myMeasureEvi = myMeasureEvi;
checked= new boolean[myMeasureEvi.size()]; //this is where I initialize the array
}
and this where i am getting the exception at:
in the adapter
public View getView
this
if (checked[position]) {
holder.checkBox.setChecked(true);
} else {
holder.checkBox.setChecked(false);
}
the log in debug window
checked[position]= java.lang.IndexOutOfBoundsException : Invalid array range: 0 to 0
the log in android monitor
03-22 17:18:03.121 2024-3372/com.google.android.gms.persistent W/GLSUser: [AppCertManager] IOException while requesting key:
java.io.IOException: Invalid device key response.
at evk.a(:com.google.android.gms:274)
at evk.a(:com.google.android.gms:4238)
at evj.a(:com.google.android.gms:45)
at evd.a(:com.google.android.gms:50)
at evc.a(:com.google.android.gms:104)
at com.google.android.gms.auth.account.be.legacy.AuthCronChimeraService.b(:com.google.android.gms:4049)
at ecm.call(:com.google.android.gms:2041)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at llt.run(:com.google.android.gms:450)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at lqc.run(:com.google.android.gms:17)
at java.lang.Thread.run(Thread.java:761)
I put a breakpoint and I can see that the size of myMeasureEvi is not 0, but for some reason, checked is always 0
Any hints on this? if you need more information please let me know
EDIT: Complete adapter code
public class MeasureTableAdapter extends ArrayAdapter<MeasureEvi> {
private final Activity context;
ArrayList<MeasureEvi> myMeasureEvi;
boolean[] checked;
public OnHeadlineSelectedListener mCallback;
public interface OnHeadlineSelectedListener { public void onMeasureInDrawActiom(int position, boolean delete); }
public void setCallback(OnHeadlineSelectedListener mCallback){ this.mCallback = mCallback; }
public MeasureTableAdapter(Activity context, ArrayList<MeasureEvi> myMeasureEvi) {
super(context, R.layout.adapter_tablamedida_item, myMeasureEvi);
this.context = context;
this.myMeasureEvi = myMeasureEvi;
checked= new boolean[myMeasureEvi.size()];
}
private class ViewHolder {
TextView txtIndex;
EditText txtCoordX;
EditText txtCoordY;
ImageView imgEvidence;
TextView txtEvidence;
TextView txtName;
TextView txtDescription;
CheckBox checkBox;
}
#Override
public View getView(final int position, View rowView, ViewGroup parent){
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if(rowView == null) {
rowView = inflater.inflate(R.layout.adapter_tablamedida_item, null, true);
holder = new ViewHolder();
holder.txtIndex = (TextView) rowView.findViewById(R.id.TxtIndex);
holder.txtCoordX = (EditText) rowView.findViewById(R.id.TxtCoordX);
holder.txtCoordY = (EditText) rowView.findViewById(R.id.TxtCoordY);
holder.imgEvidence = (ImageView) rowView.findViewById(R.id.ImgIcon);
holder.txtEvidence = (TextView) rowView.findViewById(R.id.TxtEvidenciaId);
holder.txtName = (TextView) rowView.findViewById(R.id.TxtCategory);
holder.txtDescription = (TextView) rowView.findViewById(R.id.TxtDescription);
holder.checkBox= (CheckBox) rowView.findViewById(R.id.checkBox);
rowView.setTag(holder);
} else {
holder= (ViewHolder) rowView.getTag();
}
MeasureEvi currentItem = getItem(position);
if (currentItem != null) {
int suma = currentItem.getmOrderIndex()+1;
Evidence myEvidence = DataIpat.evidencetArray.get(currentItem.geteIndex());
holder.checkBox.setChecked(false);
if (holder.txtIndex != null) holder.txtIndex.setText("" + suma );
if (holder.imgEvidence != null) holder.imgEvidence.setImageDrawable(myEvidence.geteImage().getDrawable());
if (holder.txtEvidence != null) holder.txtEvidence.setText("" + myEvidence.geteId());
if (holder.txtName != null) holder.txtName.setText(myEvidence.geteCategory() + " " + (myEvidence.getcIndex() + 1));
if (holder.txtDescription != null) holder.txtDescription.setText(currentItem.getmDescription() + " - " + currentItem.getmObservation());
if (holder.txtCoordX != null) {
holder.txtCoordX.setSelectAllOnFocus(true);
holder.txtCoordX.setText("" + currentItem.getmCoordenate().x);
holder.txtCoordX.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
if(!(setPosition(holder.txtCoordX.getText().toString(), holder.txtCoordY.getText().toString(), position))){
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
holder.txtCoordX.setText("" + coord.x);
}
}
});
}
if (holder.txtCoordY != null){
holder.txtCoordY.setSelectAllOnFocus(true);
holder.txtCoordY.setText("" + currentItem.getmCoordenate().y);
holder.txtCoordY.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus)
if(!(setPosition(holder.txtCoordX.getText().toString(), holder.txtCoordY.getText().toString(), position))){
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
holder.txtCoordY.setText("" + coord.y);
}
}
});
}
}
if (checked[position]) {
holder.checkBox.setChecked(true);
} else {
holder.checkBox.setChecked(false);
}
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.checkBox.isChecked())
checked[position] = true;
else
checked[position] = false;
}
});
return rowView;
}
private boolean setPosition(String coordX, String coordY, int position){
try {
float X = Float.parseFloat(coordX);
float Y = Float.parseFloat(coordY);
PointF coord = DataIpat.measureEviArray.get(position).getmCoordenate();
if (X != 0 && Y != 0 ) { // Valido que los x y y sean diferentes de cero
if(X != coord.x || Y != coord.y) { // valida que el dato alla cambiado
for(MeasureEvi myMeasure: DataIpat.measureEviArray){ //
if (myMeasure.geteIndex() == DataIpat.measureEviArray.get(position).geteIndex()
&& myMeasure.getmIndex() != DataIpat.measureEviArray.get(position).getmIndex()){
if(X == myMeasure.getmCoordenate().x && Y == myMeasure.getmCoordenate().y) {
Toast.makeText(getContext(), "Error no se permiten coordenadas iguales.", Toast.LENGTH_SHORT).show();
return false;
}
}
}
DataIpat.measureEviArray.get(position).setmCoordenate(new PointF(X, Y));
mCallback.onMeasureInDrawActiom(position, false); // true for delete
}
}
return true;
} catch (Exception ex) {
return false;
}
}
}
By doing a deeper debug at my app, I noticed that the adapter is being initialized way before, so it won´t go trhough the constructor anymore, unless is initialized again, therefore the size of the array will always be 0.
SOLUTION:
As the array ask for the size of itself, I decided to use an ArrayList
create variable to store the checked boxes:
public static ArrayList<MeasureEvi> myChecked = new ArrayList<MeasureEvi>();
create a listener event to store your choices:
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(holder.checkBox.isChecked()) {
myChecked.add(DataIpat.measureEviArray.get(position));
}
else {
myChecked.remove(DataIpat.measureEviArray.get(position));
}
for (int i=0; i<myChecked.size(); i++){
MeasureEvi e= myChecked.get(i);
Log.d("mOrder", String.valueOf(e.getmOrderIndex()));
}
}
});
and KABOOM, now I have the objets from where I checked!
I am creating an android application in which having one listview, inside that listview having expandable listview. When I run the application I'm getting the uncaught remote exception in logcat. Can any one tell me why this error occurs, what I have done wrong in following code?
ListAdapter:
public class Daybook_adapter extends BaseAdapter {
Context context;
private ArrayList<Daybook> entriesdaybook;
private ArrayList<Daybooklist> daybooklists = new ArrayList<Daybooklist>();
private boolean isListScrolling;
private LayoutInflater inflater;
public Daybook_adapter(Context context, ArrayList<Daybook> entriesdaybook) {
this.context = context;
this.entriesdaybook = entriesdaybook;
}
#Override
public int getCount() {
return entriesdaybook.size();
}
#Override
public Object getItem(int i) {
return entriesdaybook.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.model_daybook, null);
final TextView tv_date = (TextView) convertView.findViewById(R.id.tv_daybook_date);
final TextView tv_cashin = (TextView) convertView.findViewById(R.id.tv_daybook_cashin);
final TextView tv_cashout = (TextView) convertView.findViewById(R.id.tv_daybook_cashout);
final TextView tv_totalamt = (TextView) convertView.findViewById(R.id.daybook_total_amt);
final ImageView img_pdf = (ImageView) convertView.findViewById(R.id.img_printpdf);
LinearLayout emptyy = (LinearLayout) convertView.findViewById(R.id.empty);
ExpandableHeightListView daybookdetailviewlist = (ExpandableHeightListView) convertView.findViewById(R.id.detaillist_daybook);
final Daybook m = entriesdaybook.get(position);
String s = m.getDate();
String[] spiliter = s.split("-");
String year = spiliter[0];
String month = spiliter[1];
String date = spiliter[2];
if (month.startsWith("01")) {
tv_date.setText(date + "Jan" + year);
} else if (month.startsWith("02")) {
tv_date.setText(date + "Feb" + year);
} else if (month.startsWith("03")) {
tv_date.setText(date + "Mar" + year);
} else if (month.startsWith("04")) {
tv_date.setText(date + "Apr" + year);
} else if (month.startsWith("05")) {
tv_date.setText(date + "May" + year);
} else if (month.startsWith("06")) {
tv_date.setText(date + "Jun" + year);
} else if (month.startsWith("07")) {
tv_date.setText(date + "Jul" + year);
} else if (month.startsWith("08")) {
tv_date.setText(date + "Aug" + year);
} else if (month.startsWith("09")) {
tv_date.setText(date + "Sep" + year);
} else if (month.startsWith("10")) {
tv_date.setText(date + "Oct" + year);
} else if (month.startsWith("11")) {
tv_date.setText(date + "Nov" + year);
} else if (month.startsWith("12")) {
tv_date.setText(date + "Dec" + year);
}
tv_cashin.setText("\u20B9" + m.getCashin());
tv_cashout.setText("\u20B9" + m.getCashout());
double one = Double.parseDouble(m.getCashin());
double two = Double.parseDouble(m.getCashout());
double three = one + two;
tv_totalamt.setText("\u20B9" + String.valueOf(three));
DatabaseHandler databaseHandler = new DatabaseHandler(context);
daybooklists = databaseHandler.getAllDaywisedaybookdetails(s);
for (int i = 0; i < daybooklists.size(); i++) {
try {
Daybooklist_adapter adapter = new Daybooklist_adapter(context, daybooklists);
if (adapter != null) {
if (adapter.getCount() > 0) {
emptyy.setVisibility(View.GONE);
daybookdetailviewlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} else {
daybookdetailviewlist.setEmptyView(emptyy);
}
daybookdetailviewlist.setExpanded(true);
daybookdetailviewlist.setFastScrollEnabled(true);
if (!isListScrolling) {
img_pdf.setEnabled(false);
adapter.isScrolling(true);
} else {
img_pdf.setEnabled(true);
adapter.isScrolling(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
img_pdf.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage("Click yes to Print Report for : " + m.getDate())
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent pdfreport = new Intent(context, Activity_Daybookpdf.class);
pdfreport.putExtra("date", m.getDate());
context.startActivity(pdfreport);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(context.getResources().getColor(R.color.colorAccent));
Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
pbutton.setPadding(0, 10, 10, 0);
pbutton.setTextColor(Color.WHITE);
return false;
}
});
return convertView;
}
public void setTransactionList(ArrayList<Daybook> newList) {
entriesdaybook = newList;
notifyDataSetChanged();
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("scrollcheck", String.valueOf(isListScrolling));
}
}
Expandable ListAdapter:
public class Daybooklist_adapter extends BaseAdapter {
Context context;
private LayoutInflater inflater;
private ArrayList<Daybooklist> daybooklists;
DatabaseHandler databaseHandler;
boolean isListScrolling;
public Daybooklist_adapter(Context context, ArrayList<Daybooklist> daybooklists) {
this.context = context;
this.daybooklists = daybooklists;
}
#Override
public int getCount() {
return daybooklists.size();
}
#Override
public Object getItem(int i) {
return daybooklists.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertview == null)
convertview = inflater.inflate(R.layout.model_daybook_listentry, null);
final TextView day_name = (TextView) convertview.findViewById(R.id.tv_daybook_name);
final TextView day_description = (TextView) convertview.findViewById(R.id.tv_daybook_description);
final TextView day_type = (TextView) convertview.findViewById(R.id.tv_daybook_type);
final TextView day_amount = (TextView) convertview.findViewById(R.id.tv_daybook_amount);
final TextView day_usertype = (TextView) convertview.findViewById(R.id.tv_usertype);
final TextView day_time = (TextView) convertview.findViewById(R.id.tv_daybook_time);
final ImageView day_check = (ImageView) convertview.findViewById(R.id.img_doneall);
final TextView daybook_location = (TextView) convertview.findViewById(R.id.tv_daybook_location);
databaseHandler = new DatabaseHandler(context);
final Daybooklist m = daybooklists.get(position);
if (m.getUsertype() != null && !m.getUsertype().isEmpty()) {
if (m.getUsertype().startsWith("farmer") | m.getUsertype().startsWith("singleworker") | m.getUsertype().startsWith("groupworker") | m.getUsertype().startsWith("payvehicle")) {
if (m.getUsertype().startsWith("farmer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
String locat = String.valueOf(databaseHandler.getfarmerlocation(m.getMobileno()));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
day_type.setText(m.getType());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + m.getExtraamt());
if (m.getAmountout().startsWith("0.0") | m.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(m.getCtime());
} else {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
daybook_location.setText(m.getType());
day_type.setText(m.getType());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + m.getExtraamt());
if (m.getAmountout().startsWith("0.0") | m.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(m.getCtime());
}
} else if (m.getUsertype().startsWith("advancefarmer") | m.getUsertype().startsWith("workeradvance") | m.getUsertype().startsWith("kgroupadvance") | m.getUsertype().startsWith("otherexpense") | m.getUsertype().startsWith("vehicle")) {
if (m.getUsertype().startsWith("advancefarmer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
day_type.setText(m.getType());
String locat = String.valueOf(databaseHandler.getfarmerlocation(m.getMobileno()));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", m.getAmountout());
day_amount.setText("\u20B9" + m.getAmountout());
day_time.setText(m.getCtime());
} else {
day_name.setText(m.getName());
day_description.setText(m.getType());
day_type.setText(m.getType());
daybook_location.setText(m.getDescription());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", m.getAmountout());
day_amount.setText("\u20B9" + m.getAmountout());
day_time.setText(m.getCtime());
}
} else if (m.getUsertype().startsWith("buyer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
day_amount.setText("\u20B9" + m.getAmountin());
day_type.setText(" ");
day_time.setText(m.getCtime());
daybook_location.setText(m.getType());
}
if (m.getUsertype().startsWith("farmer")) {
day_usertype.setText("F");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (m.getUsertype().startsWith("advancefarmer")) {
day_usertype.setText("FA");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (m.getUsertype().startsWith("singleworker")) {
day_usertype.setText("W");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("workeradvance")) {
day_usertype.setText("WA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("groupworker")) {
day_usertype.setText("G");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("kgroupadvance")) {
day_usertype.setText("GA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("otherexpense")) {
day_usertype.setText("E");
day_usertype.setBackgroundResource(R.drawable.textview_otherexpense);
} else if (m.getUsertype().startsWith("vehicle")) {
day_usertype.setText("V");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (m.getUsertype().startsWith("gsalary")) {
day_usertype.setText("GS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("isalary")) {
day_usertype.setText("WS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("payvehicle")) {
day_usertype.setText("VP");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (m.getUsertype().startsWith("buyer")) {
day_usertype.setText("B");
day_usertype.setBackgroundResource(R.drawable.textview_buyer);
}
}
return convertview;
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("Innerscrollcheck", String.valueOf(isListScrolling));
}
}
Exception:
Uncaught remote exception! (Exceptions are not yet supported across
processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
Thanks in advance.
I trying to add admob native ads in recyclerview that uses resourcecursoradapter adapter .. the issues is
1 - it makes app crash
2 - it replaces recyclerview data item with admob ads
that is my code
public class EntriesCursorAdapter extends ResourceCursorAdapter {
private final Uri mUri;
private final boolean mShowFeedInfo;
private int mIdPos, mTitlePos, mMainImgPos, mDatePos, mIsReadPos, mFavoritePos, mFeedIdPos, mFeedNamePos;
public static final int Ads_view_type = 11;
public EntriesCursorAdapter(Context context, Uri uri, Cursor cursor, boolean showFeedInfo) {
super(context, PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int,R.layout.item_entry_list2), cursor, 0);
mUri = uri;
mShowFeedInfo = showFeedInfo;
reinit(cursor);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
View itemView ;
if(viewtype == Ads_view_type) {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.native_ads, parent, false);
if (itemView.getTag(R.id.holder) == null) {
AdsHolder ads_holder = new AdsHolder();
ads_holder.adView = (NativeExpressAdView) itemView.findViewById(R.id.adView2);
itemView.setTag(R.id.holder, ads_holder);
} return itemView;
}
else {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int, R.layout.item_entry_list2), parent, false);
if (itemView.getTag(R.id.holder) == null) {
ViewHolder holder = new ViewHolder();
holder.titleTextView = (TextView) itemView.findViewById(android.R.id.text1);
holder.dateTextView = (TextView) itemView.findViewById(android.R.id.text2);
holder.mainImgView = (ImageView) itemView.findViewById(R.id.main_icon);
holder.starImgView = (ImageView) itemView.findViewById(R.id.favorite_icon);
itemView.setTag(R.id.holder, holder);
}
return itemView;
}
}
#Override
public int getItemViewType(int position) {
if(position % 6 ==0)
{return Ads_view_type;}
else {
return super.getItemViewType(position);
}
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
if (viewtype == Ads_view_type) {
try {
AdsHolder adsHolder = (AdsHolder) view.getTag(R.id.holder);
AdRequest request = new AdRequest.Builder()
.addTestDevice("ca-app-pub-5647351014779121/8591922893")
.build();
adsHolder.adView.loadAd(request);
} catch (Exception e) {
}
} else {
try {
ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
String titleText = cursor.getString(mTitlePos);
holder.titleTextView.setText(titleText);
final long feedId = cursor.getLong(mFeedIdPos);
String feedName = cursor.getString(mFeedNamePos);
String mainImgUrl = cursor.getString(mMainImgPos);
mainImgUrl = TextUtils.isEmpty(mainImgUrl) ? null : NetworkUtils.getDownloadedOrDistantImageUrl(cursor.getLong(mIdPos), mainImgUrl);
ColorGenerator generator = ColorGenerator.DEFAULT;
int color = generator.getColor(feedId); // The color is specific to the feedId (which shouldn't change)
String lettersForName = feedName != null ? (feedName.length() < 2 ? feedName.toUpperCase() : feedName.substring(0, 2).toUpperCase()) : "";
TextDrawable letterDrawable = TextDrawable.builder().buildRect(lettersForName, color);
if (mainImgUrl != null) {
Glide.with(context).load(mainImgUrl).centerCrop().placeholder(letterDrawable).error(letterDrawable).into(holder.mainImgView);
} else {
Glide.clear(holder.mainImgView);
holder.mainImgView.setImageDrawable(letterDrawable);
}
holder.isFavorite = cursor.getInt(mFavoritePos) == 1;
holder.starImgView.setVisibility(holder.isFavorite ? View.VISIBLE : View.INVISIBLE);
if (mShowFeedInfo && mFeedNamePos > -1) {
if (feedName != null) {
holder.dateTextView.setText(Html.fromHtml("<font color='#247ab0'>" + feedName + "</font>" + Constants.COMMA_SPACE + StringUtils.getDateTimeString(cursor.getLong(mDatePos))));
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
if (cursor.isNull(mIsReadPos)) {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
holder.isRead = false;
} else {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
holder.isRead = true;
}
} catch (Exception e) {}
}
}
public void toggleReadState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isRead = !holder.isRead;
if (holder.isRead) {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
} else {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
}
new Thread() {
#Override
public void run() {
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, holder.isRead ? FeedData.getReadContentValues() : FeedData.getUnreadContentValues(), null, null);
}
}.start();
}
}
public void toggleFavoriteState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isFavorite = !holder.isFavorite;
if (holder.isFavorite) {
holder.starImgView.setVisibility(View.VISIBLE);
} else {
holder.starImgView.setVisibility(View.INVISIBLE);
}
new Thread() {
#Override
public void run() {
ContentValues values = new ContentValues();
values.put(EntryColumns.IS_FAVORITE, holder.isFavorite ? 1 : 0);
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, values, null, null);
}
}.start();
}
}
#Override
public void changeCursor(Cursor cursor) {
reinit(cursor);
super.changeCursor(cursor);
}
#Override
public Cursor swapCursor(Cursor newCursor) {
reinit(newCursor);
return super.swapCursor(newCursor);
}
#Override
public void notifyDataSetChanged() {
reinit(null);
super.notifyDataSetChanged();
}
#Override
public void notifyDataSetInvalidated() {
reinit(null);
super.notifyDataSetInvalidated();
}
private void reinit(Cursor cursor) {
if (cursor != null && cursor.getCount() > 0) {
mIdPos = cursor.getColumnIndex(EntryColumns._ID);
mTitlePos = cursor.getColumnIndex(EntryColumns.TITLE);
mMainImgPos = cursor.getColumnIndex(EntryColumns.IMAGE_URL);
mDatePos = cursor.getColumnIndex(EntryColumns.DATE);
mIsReadPos = cursor.getColumnIndex(EntryColumns.IS_READ);
mFavoritePos = cursor.getColumnIndex(EntryColumns.IS_FAVORITE);
mFeedNamePos = cursor.getColumnIndex(FeedColumns.NAME);
mFeedIdPos = cursor.getColumnIndex(EntryColumns.FEED_ID);
}
}
private static class ViewHolder {
public TextView titleTextView;
public TextView dateTextView;
public ImageView mainImgView;
public ImageView starImgView;
public boolean isRead, isFavorite;
}
private static class AdsHolder {
NativeExpressAdView adView;
}
}
What I am doing::
I have three buttons
When I click any one of the button, it must clear adapter & Assign
the newvalues.
The newvalues must reflect in the listview
Problem::
My listview is not reflecting the changes onclick of Button
No log Errors
DisplayBuffet_NotifyDataSetChanged_Fragment.java
public class DisplayBuffet_NotifyDataSetChanged_Fragment extends Fragment implements View.OnClickListener{
// Declaration
static ListView xmlFragmentListView;
static View layout;
static DisplayBuffetAsyncTask downloadTask=null;
Button btnRating,btnPrice,btnDistance;
private FileCache fileCache=null;
private MemoryCache memoryCache=null;
DisplayBuffetAdapter listViewAdapter;
static Bundle bundle=null;
DisplayBuffet_Json_Fragment fragment=null;
ArrayList<HashMap<String, String>> arrayListBuffet=null;
FindMyBuffetDatabaseHelper mHelper=null;;
SQLiteDatabase database=null;
public static DisplayBuffet_NotifyDataSetChanged_Fragment newInstance(FileCache _fileCache,MemoryCache _memoryCache) {
DisplayBuffet_NotifyDataSetChanged_Fragment fragment = new DisplayBuffet_NotifyDataSetChanged_Fragment();
bundle = new Bundle();
bundle.putSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY, _fileCache);
bundle.putSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY, _memoryCache);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.display_buffets_fragment,container, false);
return layout;
}
private void initViews() {
fileCache = (FileCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY);
memoryCache = (MemoryCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY);
xmlFragmentListView = ((ListView) layout.findViewById(R.id.sortrestaurantlistview));
btnRating=(Button) getActivity().findViewById(R.id.btnRating);
btnPrice=(Button) getActivity().findViewById(R.id.btnPrice);
btnDistance=(Button) getActivity().findViewById(R.id.btnDistance);
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
arrayListBuffet = new ArrayList<HashMap<String, String>>();
mHelper = new FindMyBuffetDatabaseHelper(FindMyBuffetApplication.currentActivityContext);
database = mHelper.getWritableDatabase();
initViews();
btnRating.setOnClickListener(this);
btnPrice.setOnClickListener(this);
btnDistance.setOnClickListener(this);
setListViewAdapter();
}
#Override
public void onClick(View v) {
String strOrder="asc";
if (FindMyBuffetApplication.isRatingOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isRatingOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
switch(v.getId()) {
case R.id.btnRating:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_RATING;
if (FindMyBuffetApplication.isRatingOrderByDesc == false)
FindMyBuffetApplication.isRatingOrderByDesc = true;
else
FindMyBuffetApplication.isRatingOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isRatingOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_RATING_1,strOrder);
break;
case R.id.btnPrice:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_PRICE;
if (FindMyBuffetApplication.isPriceOrderByDesc == false)
FindMyBuffetApplication.isPriceOrderByDesc = true;
else
FindMyBuffetApplication.isPriceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_PRICE_1,strOrder);
break;
case R.id.btnDistance:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_DISTANCE;
if (FindMyBuffetApplication.isDistanceOrderByDesc == false)
FindMyBuffetApplication.isDistanceOrderByDesc = true;
else
FindMyBuffetApplication.isDistanceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_DISTANCE_1,strOrder);
break;
}
}
private void setListViewAdapter(){
downloadTask = new DisplayBuffetAsyncTask();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
listViewAdapter = new DisplayBuffetAdapter(arrayListBuffet, fileCache,memoryCache);
xmlFragmentListView.setAdapter(listViewAdapter);
}
private void sortListView(String strSortBy,String strOrder) {
arrayListBuffet.clear();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING) {
SortBuffets(FindMyBuffetConstants.SORT_BY_RATING_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_PRICE_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_DISTANCE_1, strOrder);
}
listViewAdapter.notifyDataSetChanged();
}
/*#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}*/
private void displayView() {
Fragment objFragment = getFragmentManager().findFragmentById(getId());
if (objFragment != null) {
getFragmentManager().beginTransaction().remove(objFragment).commit();
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
} else {
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
}
}
/*
* Displays data from SQLite
*/
private void SortBuffets(String strSortBy,String strOrder){
Cursor mCursor = database.rawQuery("select * from " + BuffetTable.TABLE_NAME_BUFFET + " order by " + strSortBy +" "+strOrder, null);
try {
// looping through all rows and adding to list
if (mCursor.moveToFirst()) {
do {
HashMap<String, String> map=new HashMap<String, String>();
map.put(BuffetTable.COLUMN_ID,mCursor.getString(0));
map.put(BuffetTable.COLUMN_BUF_OFF_ID,mCursor.getString(1));
map.put(BuffetTable.COLUMN_FROM_TIME,mCursor.getString(2));
map.put(BuffetTable.COLUMN_TO_TIME,mCursor.getString(3));
map.put(BuffetTable.COLUMN_ONLINE_PRICE,mCursor.getString(4));
map.put(BuffetTable.COLUMN_RESERVED_PRICE,mCursor.getString(5));
map.put(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME,mCursor.getString(6));
map.put(BuffetTable.COLUMN_RES_NAME,mCursor.getString(7));
map.put(BuffetTable.COLUMN_RATING,mCursor.getString(8));
map.put(BuffetTable.COLUMN_LATITUDE,mCursor.getString(9));
map.put(BuffetTable.COLUMN_LONGITUDE,mCursor.getString(10));
map.put(BuffetTable.COLUMN_BUF_TYPE_NAME,mCursor.getString(11));
arrayListBuffet.add(map);
} while (mCursor.moveToNext());
}
}catch (SQLiteException e){
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}catch (Exception e) {
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}finally {
// Release the memory
mCursor.close();
}
}
#Override
public void onDestroy() {
super.onDestroy();
database.close();
//layout = null; // now cleaning up!
//bundle = null;
/*fragment = null;
if (downloadTask != null && downloadTask.getStatus() != AsyncTask.Status.FINISHED)
downloadTask=null;*/
}
}
DisplayBuffetAdapter.java
public class DisplayBuffetAdapter extends BaseAdapter {
// Declare Variables
ImageLoader imageLoader;
ArrayList<HashMap<String, String>> arrayListBuffet;
LayoutInflater inflater;
FileCache fileCache=null;
MemoryCache memoryCache=null;
int tmpLoopCnt=0;
public DisplayBuffetAdapter(ArrayList<HashMap<String, String>> _arraylist,FileCache _fileCache,MemoryCache _memoryCache) {
this.arrayListBuffet = _arraylist;
this.fileCache=_fileCache;
this.memoryCache=_memoryCache;
this.imageLoader=new ImageLoader(FindMyBuffetApplication.currentActivityContext,fileCache,memoryCache);
tmpLoopCnt=0;
}
public int getCount() {
return arrayListBuffet.size();
}
public Object getItem(int position) {
return arrayListBuffet.get(position);
}
public long getItemId(int position) {
return position;
}
private class ViewHolder {
// Declare Variables
ImageView imgRestBuffLogo;
TextView txtResName;
TextView txtRestBufType;
TextView txtRestTime;
TextView txtRestDistance;
TextView txtReservePrice;
TextView txtOnlinePrice;
RatingBar restRatingBar;
Button btnOnlinePrice;
Button btnReservedPrice;
}
public View getView(int position, View convertView, ViewGroup parent) {
tmpLoopCnt = tmpLoopCnt + 1;
Log.i("LIST VIEW ADAPATER COUNT", ""+tmpLoopCnt);
ViewHolder holder;
LayoutInflater inflater;
if (convertView == null) {
inflater = (LayoutInflater) FindMyBuffetApplication.currentActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.display_buffet_listview, null);
holder = new ViewHolder();
Typeface txtResnameFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestBufTypeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Medium.ttf");
Typeface txtRestTimeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
//Typeface txtReservePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
//Typeface txtOnlinePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
Typeface btnPrice=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestDistanceFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(),"Roboto-Light.ttf");
// Locate the TextViews in listview_item.xml
holder.txtResName = (TextView) convertView.findViewById(R.id.txtRestName);
holder.txtResName.setTypeface(txtResnameFontFace);
holder.txtRestBufType = (TextView) convertView.findViewById(R.id.txtRestBufType);
holder.txtRestBufType.setTypeface(txtRestBufTypeFontFace);
holder.txtRestTime = (TextView) convertView.findViewById(R.id.txtRestTime);
holder.txtRestTime.setTypeface(txtRestTimeFontFace);
holder.txtRestDistance = (TextView) convertView.findViewById(R.id.txtRestDistance);
holder.txtRestDistance.setTypeface(txtRestDistanceFontFace);
holder.restRatingBar=(RatingBar) convertView.findViewById(R.id.restRatingBar);
//holder.txtReservePrice = (TextView) convertView.findViewById(R.id.txtReservePrice);
//holder.txtReservePrice.setTypeface(txtReservePrice);
//holder.txtOnlinePrice = (TextView) convertView.findViewById(R.id.txtOnlinePrice);
//holder.txtOnlinePrice.setTypeface(txtOnlinePrice);
holder.btnOnlinePrice=(Button) convertView.findViewById(R.id.btnOnlinePrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
holder.btnReservedPrice=(Button) convertView.findViewById(R.id.btnReservedPrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
// Locate the ImageView in listview_item.xml
holder.imgRestBuffLogo = (ImageView) convertView.findViewById(R.id.imgRestBuffetLogo);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> objMap= arrayListBuffet.get(position);
holder.txtResName.setText(objMap.get(BuffetTable.COLUMN_RES_NAME));
holder.txtRestBufType.setText(objMap.get(BuffetTable.COLUMN_BUF_TYPE_NAME));
holder.restRatingBar.setRating(Float.valueOf(objMap.get(BuffetTable.COLUMN_RATING)));
holder.txtRestTime.setText(formatTime(objMap.get(BuffetTable.COLUMN_FROM_TIME))+" to "+formatTime(objMap.get(BuffetTable.COLUMN_TO_TIME)));
//txtOnlinePrice.setText(objMap.get("Online_Price"));
//txtReservePrice.setText(objMap.get("Reserved_Price"));
holder.btnOnlinePrice.setText(" Buy Now\n "+"Rs."+objMap.get(BuffetTable.COLUMN_ONLINE_PRICE)+" ");
holder.btnReservedPrice.setText(" Reserve\n "+"Rs."+objMap.get(BuffetTable.COLUMN_RESERVED_PRICE)+" ");
//double dist=objMap.get("Latitude")-objMap.get("Longitude");
//txtRestDistance.setText(String.valueOf(dist));
holder.txtRestDistance.setText(""+10+position+" Km");
String strUrl=FindMyBuffetApplication.URL+FindMyBuffetConstants.WEB_SERVER_PATH_BUF_IMAGE+objMap.get(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME);
imageLoader.DisplayImage(strUrl,holder.imgRestBuffLogo);
return convertView;
}
private String formatTime(String strTime){
//example For hour,minutes and seconds
// String strTime = "15:30:18 pm";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
strTime=strTime.substring(0,5)+" am";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
Date date = null;
try {
date = sdf.parse(strTime);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sdf.format(date);
}
}
in private void sortListView(
before calling notifyDataSetChanged, you should submit the new dataset to your adapter. Otherwise you are only chaining the data inside the fragment. You could this both creating a new Adapter and calling setListAdapter again, or creating a method inside the Adapter to update the dataset. For instance:
public void updateData(ArrayList<HashMap<String, String>> _arraylist) {
this.arrayListBuffet = _arraylist;
}
and call it before
listViewAdapter.notifyDataSetChanged();
When you sort you are in fact adding to arrayListBuffet but that may not be your only problem. What you're doing is sorting an array that's not inside the adapter, you need to pass the newly sorted data, in your case arrayListBuffet back to the adapter before calling notifyDataSetChanged
Why? Because if you don't, the data that the adapter is using is still the one from when you initialised it, and therefore you'll see no changes. In other words, you didn't really change the dataset it's using.
How? You can create a method in your adapter and pass the newly sorted data source as a parameter, replacing the original content, you can actually call the notifyDataSetChanged from within that same method.
Code
In your adapter:
public void updateDataSource(ArrayList<HashMap<String, String>> sortedArrayListBuffet) {
this.arrayListBuffet = sortedArrayListBuffet;
this.notifyDataSetChanged();
}
I need help with custom adapter with getView() method. When adapter create a list in getView() method called every time rendering like holder.textEpisode.setTextColor() etc. This gives heavy load and the list begins to slow down.
Please help me solve this problem. Thanks!
public class myAdapterDouble extends ArrayAdapter<Order> {
private int[] colorWhite = new int[] { -0x1 };
private int[] colors = new int[] { -0x1, -0x242425 };
private int[] colorBlack = new int[] { -0x1000000 };
private int[] colorTransparent = new int[] { android.R.color.transparent };
private LayoutInflater lInflater;
private ArrayList<Order> data;
private Order o;
private DisplayImageOptions options;
private ImageLoader imageLoader;
private ImageLoaderConfiguration config;
private Context ctx;
private Typeface tf;
public myAdapterDouble(Context c, int listItem, ArrayList<Order> data) {
super(c, listItem, data);
lInflater = LayoutInflater.from(c);
this.data = data;
ctx = c;
tf = Typeface.createFromAsset(ctx.getAssets(), "meiryo.ttc");
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.no_image)
.showImageForEmptyUri(R.drawable.no_image).cacheOnDisc()
.cacheInMemory().build();
config = new ImageLoaderConfiguration.Builder(c.getApplicationContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(2 * 1024 * 1024) // 2 Mb
.memoryCacheExtraOptions(100, 100)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging()
.build();
ImageLoader.getInstance().init(config);
}
SharedPreferences sharedPref;
boolean posters, fixFont;
float headerSize, timeSize, dateSize;
int imageWSize;
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
o = data.get(position);
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.double_list_item, null);
holder = new ViewHolder();
holder.textName = (TextView) convertView.findViewById(R.id.text);
if (fixFont) {
try {
holder.textName.setTypeface(tf);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
} else {
try {
holder.textName.setTypeface(Typeface.DEFAULT);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
holder.textEpisode = (TextView) convertView.findViewById(R.id.text2);
holder.img = (ImageView) convertView.findViewById(R.id.image);
String width = sharedPref.getString("image_width", "70");
imageWSize = Integer.parseInt(width); // ширина
final float scale = getContext().getResources().getDisplayMetrics().density;
int px = (int) (imageWSize*scale + 0.5f);
holder.img.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
holder.img.getLayoutParams().width = px;
if(imageWSize == 0) {
holder.img.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
}
holder.img.setPadding(5, 5, 5, 5);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
headerSize = Float.parseFloat(sharedPref.getString("headsize", "20"));
holder.textName.setTextSize(headerSize); // размер названия
timeSize = Float.parseFloat(sharedPref.getString("timesize", "15"));
holder.textEpisode.setTextSize(timeSize); // размер времени
if (posters) {
holder.img.setVisibility(View.VISIBLE);
try {
imageLoader.displayImage(o.getLink(), holder.img, options);
} catch (NullPointerException e) {
e.printStackTrace();
}
} else {
holder.img.setVisibility(View.GONE);
}
holder.img.setTag(o);
holder.textName.setText(o.getTextName());
holder.textEpisode.setText(o.getTextEpisode());
holder.textEpisode.setTextColor(Color.BLACK);
if (o.getTextEpisode().toString().contains(ctx.getString(R.string.final_ep))) {
String finaleColor = sharedPref.getString("finale_color", "1");
if (finaleColor.contains("default")) {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
if (finaleColor.contains("yelow")) {
holder.textEpisode.setTextColor(Color.YELLOW);
}
if (finaleColor.contains("red")) {
holder.textEpisode.setTextColor(Color.RED);
}
if (finaleColor.contains("green")) {
holder.textEpisode.setTextColor(Color.GREEN);
}
if (finaleColor.contains("white")) {
holder.textEpisode.setTextColor(Color.WHITE);
}
if (finaleColor.contains("gray")) {
holder.textEpisode.setTextColor(Color.GRAY);
}
} else {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
String chooseColor = sharedPref.getString("colorList", "");
if (chooseColor.contains("white")) {
int colorPos = position % colorWhite.length;
convertView.setBackgroundColor(colorWhite[colorPos]);
}
if (chooseColor.contains("black")) {
int colorPos = position % colorBlack.length;
convertView.setBackgroundColor(colorBlack[colorPos]);
holder.textName.setTextColor(Color.parseColor("#FFFFFF"));
}
if (chooseColor.contains("whitegray")) {
int colorPos = position % colors.length;
convertView.setBackgroundColor(colors[colorPos]);
}
if (chooseColor.contains("transparent")) {
int colorPos = position % colorTransparent.length;
convertView.setBackgroundColor(colorTransparent[colorPos]);
}
return convertView;
}
getView() method will be called every time when u do a scroll for loading next items.
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
This should slow the scroll since every time it need to read and parse the preference.
Have all those preferences been loaded once as some variables.
If that still does not solved the problem that try Method Profiling and check whats Incl% for the getView Method and see which methods is taking more cpu usage in getView.
EDITED
public class myAdapterDouble extends ArrayAdapter<Order> {
private int[] colorWhite = new int[] { -0x1 };
private int[] colors = new int[] { -0x1, -0x242425 };
private int[] colorBlack = new int[] { -0x1000000 };
private int[] colorTransparent = new int[] { android.R.color.transparent };
private LayoutInflater lInflater;
private ArrayList<Order> data;
private Order o;
private DisplayImageOptions options;
private ImageLoader imageLoader;
private ImageLoaderConfiguration config;
private Context ctx;
private Typeface tf;
boolean posters, fixFont;
float headerSize, timeSize, dateSize;
int imageWSize;
private String finaleColor;
private String chooseColor;
private String final_ep;
public myAdapterDouble(Context c, int listItem, ArrayList<Order> data) {
super(c, listItem, data);
lInflater = LayoutInflater.from(c);
this.data = data;
ctx = c;
tf = Typeface.createFromAsset(ctx.getAssets(), "meiryo.ttc");
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().showStubImage(R.drawable.no_image).showImageForEmptyUri(R.drawable.no_image).cacheOnDisc().cacheInMemory().build();
config = new ImageLoaderConfiguration.Builder(c.getApplicationContext()).threadPriority(Thread.NORM_PRIORITY - 2).memoryCacheSize(2 * 1024 * 1024)
// 2 Mb
.memoryCacheExtraOptions(100, 100).denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO)
.enableLogging().build();
ImageLoader.getInstance().init(config);
SharedPreferences sharedPref;
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
String width = sharedPref.getString("image_width", "70");
imageWSize = Integer.parseInt(width); // ширина
headerSize = Float.parseFloat(sharedPref.getString("headsize", "20"));
timeSize = Float.parseFloat(sharedPref.getString("timesize", "15"));
finaleColor = sharedPref.getString("finale_color", "1");
chooseColor = sharedPref.getString("colorList", "");
final_ep = ctx.getString(R.string.final_ep);
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
o = data.get(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.double_list_item, null);
holder = new ViewHolder();
holder.textName = (TextView) convertView.findViewById(R.id.text);
if (fixFont) {
try {
holder.textName.setTypeface(tf);
}
catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
else {
try {
holder.textName.setTypeface(Typeface.DEFAULT);
}
catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
holder.textEpisode = (TextView) convertView.findViewById(R.id.text2);
holder.img = (ImageView) convertView.findViewById(R.id.image);
final float scale = getContext().getResources().getDisplayMetrics().density;
int px = (int) (imageWSize * scale + 0.5f);
holder.img.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
holder.img.getLayoutParams().width = px;
if (imageWSize == 0) {
holder.img.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
}
holder.img.setPadding(5, 5, 5, 5);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.textName.setTextSize(headerSize); // размер названия
holder.textEpisode.setTextSize(timeSize); // размер времени
if (posters) {
holder.img.setVisibility(View.VISIBLE);
try {
imageLoader.displayImage(o.getLink(), holder.img, options);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
else {
holder.img.setVisibility(View.GONE);
}
holder.img.setTag(o);
holder.textName.setText(o.getTextName());
holder.textEpisode.setText(o.getTextEpisode());
holder.textEpisode.setTextColor(Color.BLACK);
if (o.getTextEpisode().toString().contains()) {
if (finaleColor.contains("default")) {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
if (finaleColor.contains("yelow")) {
holder.textEpisode.setTextColor(Color.YELLOW);
}
if (finaleColor.contains("red")) {
holder.textEpisode.setTextColor(Color.RED);
}
if (finaleColor.contains("green")) {
holder.textEpisode.setTextColor(Color.GREEN);
}
if (finaleColor.contains("white")) {
holder.textEpisode.setTextColor(Color.WHITE);
}
if (finaleColor.contains("gray")) {
holder.textEpisode.setTextColor(Color.GRAY);
}
}
else {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
if (chooseColor.contains("white")) {
int colorPos = position % colorWhite.length;
convertView.setBackgroundColor(colorWhite[colorPos]);
}
if (chooseColor.contains("black")) {
int colorPos = position % colorBlack.length;
convertView.setBackgroundColor(colorBlack[colorPos]);
holder.textName.setTextColor(Color.parseColor("#FFFFFF"));
}
if (chooseColor.contains("whitegray")) {
int colorPos = position % colors.length;
convertView.setBackgroundColor(colors[colorPos]);
}
if (chooseColor.contains("transparent")) {
int colorPos = position % colorTransparent.length;
convertView.setBackgroundColor(colorTransparent[colorPos]);
}
return convertView;
}
}
try like this instead of viewholder this works perfectly for me.
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.double_list_item, null);
}
TextView textName = (TextView) v.findViewById(R.id.text);
if (fixFont){
try {
textName.setTypeface(tf);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}else {
try {
textName.setTypeface(Typeface.DEFAULT);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
return super.getView(position, v, parent);
}
};
I hope this will help you.