EditText added dynamically does not set invisble in Android - java

I am adding some EditTexts dynamically, when a button is clicked, the information is entered and displayed on a text View, I need to make invisible all the EditText Views, the problem that I am facing is that only the last EditText added goes invisible. I tried to set a tag to set the EditText invisible but it is not working Am I missing something?
Any assistance with this would be appreciated.
import java.util.ArrayList;
import java.util.List;
import com.juancho.workingout.R;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class TEST extends Fragment {
// Add EditText Dynamically
RelativeLayout containerLayout;
static int exercisesViews = 0; // initial value
public int totalExercisesViews = 15;
Context context;
private int counterExeNumber = 1;
private int margingTopEditTextInitial = 120; // default position
private int margingTopNumberAdd = 130;
private List<EditText> editTextListName = new ArrayList<>();
EditText EditTextName;
String nameResultCardio, nameResult1, nameResult2, nameResult3;
int myTagValueCardio;
int myTagValueYesCardioExe2, myTagValueYesCardioExe3;
boolean cardioViewEnable = false;
boolean exe2IfCardioViewEnable = false;
boolean exe3IfCardioViewEnable = false;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View ViewCalendarEditNotesInfo = inflater.inflate(R.layout.logs_add_notes, null);
exercisesViews = 0; // Reset
containerLayout = (RelativeLayout) ViewCalendarEditNotesInfo.findViewById(R.id.layout1);
LogsAddNotes.isExercise1Enable = true;
LogsAddNotes.isExercise2Enable = true;
LogsAddNotes.isExercise3Enable = true;
final Button btnSave = (Button) ViewCalendarEditNotesInfo.findViewById(R.id.btnSave);
btnSave.setVisibility(View.VISIBLE);
if (LogsAddNotes.isExercise1Enable == true) {
// Set Views
editTextName(exercisesViews);
myTagValueCardio = (int) EditTextName.getTag();
cardioViewEnable = true;
}
// --------------------------------------------------------------------------------------------------------------------------------------------
if (LogsAddNotes.isExercise2Enable == true) {
exercisesViews++;
counterExeNumber++;
margingTopEditTextInitial = margingTopEditTextInitial + margingTopNumberAdd;
// Set Views
editTextName(exercisesViews);
// Get information entered
nameResult2 = EditTextName.getText().toString();
myTagValueYesCardioExe2 = (int) EditTextName.getTag();
exe2IfCardioViewEnable = true;
}
// --------------------------------------------------------------------------------------------------------------------------------------------
if (LogsAddNotes.isExercise3Enable == true) {
exercisesViews++;
counterExeNumber++;
margingTopEditTextInitial = margingTopEditTextInitial + margingTopNumberAdd;
// Set Views
editTextName(exercisesViews);
// Get information entered
nameResult3 = EditTextName.getText().toString();
myTagValueYesCardioExe3 = (int) EditTextName.getTag();
exe3IfCardioViewEnable = true;
}
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index = 0;
while (index < editTextListName.size()) {
// --------------------------------------------------------------------------------------------------
if (cardioViewEnable == true && index == 0) {
nameResultCardio = editTextListName.get(index).getText().toString();
if (myTagValueCardio == index) {
// tToast("B1");
EditTextName.setVisibility(View.INVISIBLE);
}
}
// --------------------------------------------------------------------------------------------------
if (exe2IfCardioViewEnable == true && index == 1) {
nameResult2 = editTextListName.get(index).getText().toString();
if (myTagValueYesCardioExe2 == index) {
// tToast("B2");
EditTextName.setVisibility(View.INVISIBLE);
}
}
// --------------------------------------------------------------------------------------------------
if (exe3IfCardioViewEnable == true && index == 2) {
nameResult3 = editTextListName.get(index).getText().toString();
if (myTagValueYesCardioExe3 == index) {
// tToast(" B3");
EditTextName.setVisibility(View.INVISIBLE);
}
}
// more exercises HERE
index++;
} // end while loop
}// end Click
});
return ViewCalendarEditNotesInfo;
}// end Main
// -----------------------------------------------------------------------------------------
private EditText editTextName(int _intID) {
EditTextName = new EditText(getActivity());
EditTextName.setId(_intID);
EditTextName.setHint("Name");
// CharSequence hint = "\u200F" + editText.getHint();
// editText.setHint(hint);
// Maximum input chars allow
int maxLength = 10;
// Allow only Letters
EditTextName.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength), new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end, Spanned dst, int dstart, int dend) {
if (src.equals("")) { // for backspace
return src;
}
if (src.toString().matches("[a-zA-Z ]+")) {
return src;
}
return "";
}
} });
editTextListName.add(EditTextName);
containerLayout.addView(EditTextName);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) EditTextName.getLayoutParams();
layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
layoutParams.setMargins(300, margingTopEditTextInitial, 750, 0);
// RelativeLayout.LayoutParams()
EditTextName.setLayoutParams(layoutParams);
// if you want to identify the created editTexts, set a tag, like below
// EditTextName[i].setTag("EditText" + editText.getId());
EditTextName.setTag(_intID);
// tToast("THE TAG= " + _intID);
return EditTextName;
}
}

Related

recyclerView layout grid items not aligning properly

i don't know much about java, just started, so i will have difficulties understanding the answers. emli5.
screenshot:
expected output:
in the recyclerview (right), these items are not aligning up like i want them to.
I want that each cell has a fixed size, and maximum number of columns possible in the grid.
spacing b/w each cell (both vertical and horizontal) is equal to (left space) divided by (number of columns minus one). [with no extra space left at start, top, bottom or end]
here is the code:
package com.MyStickersWA.DogeStickers;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
#SuppressWarnings("ALL")
public class StickerPackDetailsActivity extends AddStickerPackActivity {
/**
* Do not change below values of below 3 lines as this is also used by WhatsApp
*/
public static final String EXTRA_STICKER_PACK_ID = "sticker_pack_id";
public static final String EXTRA_STICKER_PACK_AUTHORITY = "sticker_pack_authority";
public static final String EXTRA_STICKER_PACK_NAME = "sticker_pack_name";
public static final String EXTRA_STICKER_PACK_WEBSITE = "sticker_pack_website";
public static final String EXTRA_STICKER_PACK_EMAIL = "sticker_pack_email";
public static final String EXTRA_STICKER_PACK_PRIVACY_POLICY = "sticker_pack_privacy_policy";
public static final String EXTRA_STICKER_PACK_LICENSE_AGREEMENT = "sticker_pack_license_agreement";
public static final String EXTRA_STICKER_PACK_TRAY_ICON = "sticker_pack_tray_icon";
public static final String EXTRA_SHOW_UP_BUTTON = "show_up_button";
public static final String EXTRA_STICKER_PACK_DATA = "sticker_pack";
private RecyclerView recyclerView;
private GridLayoutManager layoutManager;
private StickerPreviewAdapter stickerPreviewAdapter;
private int numColumns;
private View addButton;
private View infoButton;
private View backButton;
private View alreadyAdded;
private StickerPack stickerPack;
private WhiteListCheckAsyncTask whiteListCheckAsyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sticker_pack_details);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
MobileAds.initialize(this, initializationStatus -> { });
mAdView.loadAd(adRequest);
boolean showUpButton = getIntent().getBooleanExtra(EXTRA_SHOW_UP_BUTTON, false);
stickerPack = getIntent().getParcelableExtra(EXTRA_STICKER_PACK_DATA);
TextView packNameTextView = findViewById(R.id.pack_name);
TextView packPublisherTextView = findViewById(R.id.author);
ImageView packTrayIcon = findViewById(R.id.tray_image);
TextView packSizeTextView = findViewById(R.id.pack_size);
TextView stickersQtyTextView = findViewById(R.id.stickers_qty);
TextView stickersAnimatedView = findViewById(R.id.stickers_animated);
ImageView stickersAnimatedImage = findViewById(R.id.sticker_pack_animation_indicator);
SimpleDraweeView expandedStickerView = findViewById(R.id.sticker_details_expanded_sticker);
addButton = findViewById(R.id.add_to_whatsapp_button);
infoButton = findViewById(R.id.action_info);
backButton = findViewById(R.id.action_back);
alreadyAdded = findViewById(R.id.already_added_button);
layoutManager = new GridLayoutManager(this, 1);
recyclerView = findViewById(R.id.sticker_list);
recyclerView.setLayoutManager(layoutManager);
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(pageLayoutListener);
if (stickerPreviewAdapter == null) {
stickerPreviewAdapter = new StickerPreviewAdapter(getLayoutInflater(), R.drawable.sticker_error, getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_size), getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_padding), stickerPack, expandedStickerView);
recyclerView.setAdapter(stickerPreviewAdapter);
}
packNameTextView.setText(stickerPack.name);
packPublisherTextView.setText(stickerPack.publisher);
packTrayIcon.setImageURI(StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.trayImageFile));
packSizeTextView.setText(Formatter.formatShortFileSize(this, stickerPack.getTotalSize()));
stickersQtyTextView.setText(stickerPack.getTotalQty() + "");
addButton.setOnClickListener(v -> addStickerPackToWhatsApp(stickerPack.identifier, stickerPack.name));
infoButton.setOnClickListener(v -> onOptionsItemSelected());
backButton.setOnClickListener(v -> finish());
if (stickerPack.animatedStickerPack) {
Uri animatedIcon = Uri.parse("android.resource://" + getPackageName() + "/"+R.drawable.animated_indicator_vector);
stickersAnimatedImage.setImageURI(animatedIcon);
stickersAnimatedView.setText("Animated");
} else {
Uri animatedIcon = Uri.parse("android.resource://" + getPackageName() + "/"+R.drawable.static_indicator_vector);
stickersAnimatedImage.setImageURI(animatedIcon);
stickersAnimatedView.setText("Static");
}
}
private void launchInfoActivity(String publisherWebsite, String publisherEmail, String privacyPolicyWebsite, String licenseAgreementWebsite, String trayIconUriString) {
Intent intent = new Intent(StickerPackDetailsActivity.this, StickerPackInfoActivity.class);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_ID, stickerPack.identifier);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_WEBSITE, publisherWebsite);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_EMAIL, publisherEmail);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_PRIVACY_POLICY, privacyPolicyWebsite);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_LICENSE_AGREEMENT, licenseAgreementWebsite);
intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_TRAY_ICON, trayIconUriString);
startActivity(intent);
}
public boolean onOptionsItemSelected() {
if (stickerPack != null) {
Uri trayIconUri = StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.trayImageFile);
launchInfoActivity(stickerPack.publisherWebsite, stickerPack.publisherEmail, stickerPack.privacyPolicyWebsite, stickerPack.licenseAgreementWebsite, trayIconUri.toString());
return true;
}
return false;
}
private final ViewTreeObserver.OnGlobalLayoutListener pageLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int imgSize = recyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.sticker_pack_details_image_size);
int recyclerViewWidth = recyclerView.getWidth();
int numColumns = recyclerViewWidth / imgSize;
int colSpacing = (recyclerViewWidth - (numColumns * imgSize)) / (numColumns - 1);
// int colSpacing = recyclerView.getWidth() - imgSize * numColumns;
setNumColumns(numColumns, colSpacing);
}
};
#SuppressLint("NotifyDataSetChanged")
private void setNumColumns(int numColumns, int colSpacing) {
if (this.numColumns != numColumns) {
// recyclerView.addItemDecoration(new GridSpacingItemDecoration(4, 2, 2));
layoutManager.setSpanCount(numColumns);
recyclerView.setLayoutManager(layoutManager);
this.numColumns = numColumns;
if (stickerPreviewAdapter != null) {
stickerPreviewAdapter.notifyDataSetChanged();
}
}
}
#Override
protected void onResume() {
super.onResume();
whiteListCheckAsyncTask = new WhiteListCheckAsyncTask(this);
whiteListCheckAsyncTask.execute(stickerPack);
}
#Override
protected void onPause() {
super.onPause();
if (whiteListCheckAsyncTask != null && !whiteListCheckAsyncTask.isCancelled()) {
whiteListCheckAsyncTask.cancel(true);
}
}
private void updateAddUI(Boolean isWhitelisted) {
if (isWhitelisted) {
addButton.setVisibility(View.GONE);
alreadyAdded.setVisibility(View.VISIBLE);
} else {
addButton.setVisibility(View.VISIBLE);
alreadyAdded.setVisibility(View.GONE);
}
}
static class WhiteListCheckAsyncTask extends AsyncTask<StickerPack, Void, Boolean> {
private final WeakReference<StickerPackDetailsActivity> stickerPackDetailsActivityWeakReference;
WhiteListCheckAsyncTask(StickerPackDetailsActivity stickerPackListActivity) {
this.stickerPackDetailsActivityWeakReference = new WeakReference<>(stickerPackListActivity);
}
#Override
protected final Boolean doInBackground(StickerPack... stickerPacks) {
StickerPack stickerPack = stickerPacks[0];
final StickerPackDetailsActivity stickerPackDetailsActivity = stickerPackDetailsActivityWeakReference.get();
if (stickerPackDetailsActivity == null) {
return false;
}
return WhitelistCheck.isWhitelisted(stickerPackDetailsActivity, stickerPack.identifier);
}
#Override
protected void onPostExecute(Boolean isWhitelisted) {
final StickerPackDetailsActivity stickerPackDetailsActivity = stickerPackDetailsActivityWeakReference.get();
if (stickerPackDetailsActivity != null) {
stickerPackDetailsActivity.updateAddUI(isWhitelisted);
}
}
}
}
/*
* Copyright (c) WhatsApp Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.MyStickersWA.DogeStickers;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
public class StickerPreviewAdapter extends RecyclerView.Adapter<StickerPreviewViewHolder> {
private static final float COLLAPSED_STICKER_PREVIEW_BACKGROUND_ALPHA = 1f;
private static final float EXPANDED_STICKER_PREVIEW_BACKGROUND_ALPHA = 0.2f;
#NonNull
private final StickerPack stickerPack;
private final int cellSize;
private final int cellLimit;
private final int cellPadding;
private final int errorResource;
private final SimpleDraweeView expandedStickerPreview;
private final LayoutInflater layoutInflater;
private RecyclerView recyclerView;
private View clickedStickerPreview;
float expandedViewLeftX;
float expandedViewTopY;
StickerPreviewAdapter(
#NonNull final LayoutInflater layoutInflater,
final int errorResource,
final int cellSize,
final int cellPadding,
#NonNull final StickerPack stickerPack,
final SimpleDraweeView expandedStickerView) {
this.cellSize = cellSize;
this.cellPadding = cellPadding;
this.cellLimit = 0;
this.layoutInflater = layoutInflater;
this.errorResource = errorResource;
this.stickerPack = stickerPack;
this.expandedStickerPreview = expandedStickerView;
}
#NonNull
#Override
public StickerPreviewViewHolder onCreateViewHolder(#NonNull final ViewGroup viewGroup, final int i) {
View itemView = layoutInflater.inflate(R.layout.sticker_image_item, viewGroup, false);
StickerPreviewViewHolder vh = new StickerPreviewViewHolder(itemView);
ViewGroup.LayoutParams layoutParams = vh.stickerPreviewView.getLayoutParams();
layoutParams.height = cellSize;
layoutParams.width = cellSize;
vh.stickerPreviewView.setLayoutParams(layoutParams);
vh.stickerPreviewView.setPadding(cellPadding, cellPadding, cellPadding, cellPadding);
return vh;
}
#Override
public void onBindViewHolder(#NonNull final StickerPreviewViewHolder stickerPreviewViewHolder, final int i) {
stickerPreviewViewHolder.stickerPreviewView.setImageResource(errorResource);
stickerPreviewViewHolder.stickerPreviewView.setImageURI(StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.getStickers().get(i).imageFileName));
stickerPreviewViewHolder.stickerPreviewView.setOnClickListener(v -> expandPreview(i, stickerPreviewViewHolder.stickerPreviewView));
}
#Override
public void onAttachedToRecyclerView(#NonNull RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
this.recyclerView = recyclerView;
recyclerView.addOnScrollListener(hideExpandedViewScrollListener);
}
#Override
public void onDetachedFromRecyclerView(#NonNull RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
recyclerView.removeOnScrollListener(hideExpandedViewScrollListener);
this.recyclerView = null;
}
private final RecyclerView.OnScrollListener hideExpandedViewScrollListener =
new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dx != 0 || dy != 0) {
hideExpandedStickerPreview();
}
}
};
private void positionExpandedStickerPreview(int selectedPosition) {
if (expandedStickerPreview != null) {
// Calculate the view's center (x, y), then use expandedStickerPreview's height and
// width to
// figure out what where to position it.
final ViewGroup.MarginLayoutParams recyclerViewLayoutParams =
((ViewGroup.MarginLayoutParams) recyclerView.getLayoutParams());
final int recyclerViewLeftMargin = recyclerViewLayoutParams.leftMargin;
final int recyclerViewRightMargin = recyclerViewLayoutParams.rightMargin;
final int recyclerViewWidth = recyclerView.getWidth();
final int recyclerViewHeight = recyclerView.getHeight();
final StickerPreviewViewHolder clickedViewHolder =
(StickerPreviewViewHolder)
recyclerView.findViewHolderForAdapterPosition(selectedPosition);
if (clickedViewHolder == null) {
hideExpandedStickerPreview();
return;
}
clickedStickerPreview = clickedViewHolder.itemView;
final float clickedViewCenterX =
clickedStickerPreview.getX()
+ recyclerViewLeftMargin
+ clickedStickerPreview.getWidth() / 2f;
final float clickedViewCenterY =
clickedStickerPreview.getY() + clickedStickerPreview.getHeight() / 2f;
expandedViewLeftX = clickedViewCenterX - expandedStickerPreview.getWidth() / 2f;
expandedViewTopY = clickedViewCenterY - expandedStickerPreview.getHeight() / 2f;
// If the new x or y positions are negative, anchor them to 0 to avoid clipping
// the left side of the device and the top of the recycler view.
expandedViewLeftX = Math.max(expandedViewLeftX, 0);
expandedViewTopY = Math.max(expandedViewTopY, 0);
// If the bottom or right sides are clipped, we need to move the top left positions
// so that those sides are no longer clipped.
final float adjustmentX =
Math.max(
expandedViewLeftX
+ expandedStickerPreview.getWidth()
- recyclerViewWidth
- recyclerViewRightMargin,
0);
final float adjustmentY =
Math.max(expandedViewTopY + expandedStickerPreview.getHeight() - recyclerViewHeight, 0);
expandedViewLeftX -= adjustmentX;
expandedViewTopY -= adjustmentY;
expandedStickerPreview.setX(expandedViewLeftX);
expandedStickerPreview.setY(expandedViewTopY);
}
}
private void expandPreview(int position, View clickedStickerPreview) {
if (isStickerPreviewExpanded()) {
hideExpandedStickerPreview();
return;
}
this.clickedStickerPreview = clickedStickerPreview;
if (expandedStickerPreview != null) {
positionExpandedStickerPreview(position);
final Uri stickerAssetUri = StickerPackLoader.getStickerAssetUri(stickerPack.identifier, stickerPack.getStickers().get(position).imageFileName);
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(stickerAssetUri)
.setAutoPlayAnimations(true)
.build();
expandedStickerPreview.setImageResource(errorResource);
expandedStickerPreview.setController(controller);
expandedStickerPreview.setVisibility(View.VISIBLE);
recyclerView.setAlpha(EXPANDED_STICKER_PREVIEW_BACKGROUND_ALPHA);
expandedStickerPreview.setOnClickListener(v -> hideExpandedStickerPreview());
}
}
public void hideExpandedStickerPreview() {
if (isStickerPreviewExpanded() && expandedStickerPreview != null) {
clickedStickerPreview.setVisibility(View.VISIBLE);
expandedStickerPreview.setVisibility(View.INVISIBLE);
recyclerView.setAlpha(COLLAPSED_STICKER_PREVIEW_BACKGROUND_ALPHA);
}
}
private boolean isStickerPreviewExpanded() {
return expandedStickerPreview != null && expandedStickerPreview.getVisibility() == View.VISIBLE;
}
#Override
public int getItemCount() {
int numberOfPreviewImagesInPack;
numberOfPreviewImagesInPack = stickerPack.getStickers().size();
if (cellLimit > 0) {
return Math.min(numberOfPreviewImagesInPack, cellLimit);
}
return numberOfPreviewImagesInPack;
}
}
thanks in advance
You need to create a custom item decoration by extending RecyclerView.ItemDecoration. You can do something like this:
import android.graphics.Rect;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private final int numberOfColumns;
private final int spacing;
private final boolean addSpacingToPerimeter;
public GridSpacingItemDecoration(int numberOfColumns, int spacing, boolean addSpacingToPerimeter) {
this.numberOfColumns = numberOfColumns;
this.spacing = spacing;
this.addSpacingToPerimeter = addSpacingToPerimeter;
}
#Override
public void getItemOffsets(#NonNull Rect outRect, #NonNull View view, RecyclerView parent, #NonNull RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % numberOfColumns; // item column
if (addSpacingToPerimeter) {
outRect.left = spacing - column * spacing / numberOfColumns;
outRect.right = (column + 1) * spacing / numberOfColumns;
if (position < numberOfColumns) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / numberOfColumns;
outRect.right = spacing - (column + 1) * spacing / numberOfColumns;
if (position >= numberOfColumns) {
outRect.top = spacing; // item top
}
}
}
}
and then use it like this
int numberOfColumns = 3; // 3 columns
int spacing = 50; // 50px
boolean addSpacingToPerimeter = false;
recyclerView.addItemDecoration(new GridSpacingItemDecoration(numberOfColumns, spacing, addSpacingToPerimeter))
The GridSpacingItemDecoration class takes as a parameter the number of columns, the spacing in pixel and a boolean value that specifies whether you want spacing to be added to the list's perimeter as well. This boolean if set to true will add the given spacing as a margin not only between the grid adapter's items, but also between the items and the whole recyclerView.
Keep in mind that spacing is in pixels. So if you want to use dp instead, you can convert dp to px using
Math.round(dpValue * getResources().getDisplayMetrics().density))
It seems like every item has right padding.
You should use addItemDecoration on your RecyclerView instead.
Or use this: https://github.com/grzegorzojdana/SpacingItemDecoration

My app won't enter the for loop even though all conditions are satisfied [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am working on an app, for which I want a for loop to run. The for loop is inside a listview adapter, and it basically runs to get the some data from each entry of the list (hence the for loop). But, on debugging, I find that the app never enters the for loop, and just moves on to the 'if statement' given just below it. The condition that i == size of list isn't satisfied, so it should be running. Why?
This is the code :
package com.example.taskmasterv3;
import android.content.Context;
import android.icu.text.UFormat;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
public class SubtaskDetailAdapter extends ArrayAdapter<SubtaskPartTwo> {
private final Context context;
private ArrayList<SubtaskPartTwo> values;
public boolean deleted;
DBHelper dbHelper;
int ph = 10;
int pm = 9;
int pl = 8;
int th = 3;
int tm = 2;
int tl = 1;
private int totalTime;
private int x;
int a;
int b;
int c;
int d;
int e;
int f;
int totaltimeints;
int ans;
public SubtaskDetailAdapter(Context context, ArrayList<SubtaskPartTwo> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.task_summary_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvlolitaskname);
ImageView ivPri = convertView.findViewById(R.id.ivloliPri);
ImageView ivTime = convertView.findViewById(R.id.ivloliTime);
TextView tvEstTaskTime = convertView.findViewById(R.id.tvEstTaskTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
// Algorithm
int totaltime = values.get(position).getEstTaskTime();
while (values.listIterator().hasNext()){
totaltimeints += values.listIterator().next().getTime();
}
ans = totaltime / totaltimeints;
if (values.get(position).getPriHigh() == 1)
{
ivPri.setImageResource(R.drawable.priority_high);
values.get(position).setPri(ph);
}
if (values.get(position).getPriMed() == 1)
{
ivPri.setImageResource(R.drawable.priority_med);
values.get(position).setPri(pm);
}
if (values.get(position).getPriLow() == 1)
{
ivPri.setImageResource(R.drawable.priority_low);
values.get(position).setPri(pl);
}
if (values.get(position).getTimeMore() == 1)
{
ivTime.setImageResource(R.drawable.time_symbol_more);
values.get(position).setTime(th);
int b = ans * th;
tvEstTaskTime.setText(b + "");
}
if (values.get(position).getTimeMed() == 1)
{
ivTime.setImageResource(R.drawable.time_symbol_med);
values.get(position).setTime(tm);
int b = ans * tm;
tvEstTaskTime.setText(b + "");
}
if (values.get(position).getTimeLess() == 1)
{
ivTime.setImageResource(R.drawable.time_symbol_less);
values.get(position).setTime(tl);
int b = ans * tl;
tvEstTaskTime.setText(b + "");
}
// THIS IS WHERE I USE SORT
Collections.sort(values, new TaskComparator());
//return the view you inflated
return convertView;
}
public void addANewSubTask(SubtaskPartTwo newSubTask) {
add(newSubTask);
notifyDataSetChanged();
}
// this doesnt work yet, fix this bug ! (same on the other adapter)
#Override
public int getCount() {
if (this.values.size()>11)
{
return 10;
}
else
{
return super.getCount();
}
}
}
Code for activity where the list is shown:
package com.example.taskmasterv3;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class TaskSummary extends AppCompatActivity {
ListView lvTaskList;
TextView tvBreak, tvBreakAfterEvery, txt1, txt2, text1, hmm;
TextView break_duration_mins;
ArrayList<SubtaskPartTwo> subtaskList = new ArrayList<>();
String subtname;
String pri;
String time;
int working_hours;
int working_minutes;
int totalTime;
DBHelper dbHelper;
int timeInts;
int timeConstant;
int answer;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.tasksummary, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
dbHelper.deleteAll();
if (item.getItemId() == R.id.restore) {
Intent inti = new Intent(this, TaskInfo.class);
startActivity(inti);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_summary);
lvTaskList = findViewById(R.id.lvTaskList);
tvBreak = findViewById(R.id.tvBreak);
tvBreakAfterEvery = findViewById(R.id.tvBreakAfterEvery);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
break_duration_mins = findViewById(R.id.break_duration_mins);
text1 = findViewById(R.id.text1);
hmm = findViewById(R.id.hmm);
dbHelper = new DBHelper(this);
working_hours = getIntent().getIntExtra("working_hours", 1);
working_minutes = getIntent().getIntExtra("working_minutes", 0);
int alol = working_hours * 60;
int blol = working_minutes;
totalTime = alol + blol;
double without_break_hours = getIntent().getIntExtra("without_break_hours", 1);
double without_break_minutes = getIntent().getIntExtra("without_break_minutes", 0);
double break_duration = getIntent().getIntExtra("break_duration", 20);
String a = working_hours + " h";
txt1.setText(a);
String b = working_minutes + " m";
break_duration_mins.setText(b);
String c = break_duration + " m";
txt2.setText(c);
//Mathematics
double g = working_hours * 100;
double h = g + working_minutes;
double i = h + break_duration;
double j = i / 60;
double p = (int) j;
double q = j - p;
double r = q * 60;
without_break_hours = p;
without_break_minutes = r;
String d = without_break_hours + " h";
String e = without_break_minutes + " m";
text1.setText(d);
hmm.setText(e);
Cursor res = dbHelper.getdata();
SubtaskDetailAdapter adapter = new SubtaskDetailAdapter(this, subtaskList);
lvTaskList.setAdapter(adapter);
while (res.moveToNext() && res != null){
for (int i1 = 0; i1 < adapter.getCount(); i1++ ){
timeInts += adapter.getItem(i1).getTime();
}
timeConstant = totalTime/timeInts;
for (int i2 = 0; i2 < adapter.getCount(); i2++){
answer = timeConstant * adapter.getItem(i2).getTime();
}
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(res.getString(0), res.getInt(1), res.getInt(2), res.getInt(3), res.getInt(4), res.getInt(5), res.getInt(6), 0, 0, answer);
//subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
}
}
}
Before each iteration of the for loop, program checks if the condition (i == values.size()) is satisfied . As i is equal to 0, it is not equal to values.size(), so the block will not be executed.
Do you want the more common i < values.size() or possibly i <= values.size()?
The adapter's GetView method will be called multiple times, so it is not the correct place to put the for/while loop for totaling as you will have unexpected results. if you want to total anything put that inside the fragment or activity class where you are using the adapter to populate the recycler view. Ya, you can also set inside the constructor of the adapter too, if the ArrayList which you are passing at the time of initialization is not going to be changed.

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

Dialog Fragment does not working?

Iam getting runtime error at Dialog fragment. At the Runtime of program works smoothly but when it comes to dialog appearence imes the program crashes........... Somebody show me where did the mistake I can't resolve my problem.
I am posting a LogCat Image because of body limit is crossed
MainActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
public static final String GUESSES = "settings_numberOfGuesses";
public static final String ANIMALS_TYPE = "settings_animalType";
public static final String QUIZ_BACKGROUND_COLOR = "settings_quiz_background_color";
public static final String QUIZ_FONT = "settings_quiz_font";
private boolean isSettingsChanged = false;
static Typeface azkiaDemo;
static Typeface chunkFive;
static Typeface fontleroyBrown;
static Typeface hauntedEyes;
static Typeface knightBrushDemo;
static Typeface wonderbarDemo;
MainActivityFragment myAnimalQuizFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
azkiaDemo = Typeface.createFromAsset(getAssets(),"fonts/Azkia demo.otf");
chunkFive = Typeface.createFromAsset(getAssets(),"fonts/Chunkfive.otf");
fontleroyBrown = Typeface.createFromAsset(getAssets(),"fonts/FontleroyBrown.ttf");
hauntedEyes = Typeface.createFromAsset(getAssets(),"fonts/Haunted Eyes.otf");
knightBrushDemo = Typeface.createFromAsset(getAssets(),"fonts/Knight Brush Demo.otf");
wonderbarDemo = Typeface.createFromAsset(getAssets(),"fonts/Wonderbar Demo.otf");
PreferenceManager.setDefaultValues(this, R.xml.quiz_preferences, false);
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(settingsChangedListener);
myAnimalQuizFragment = (MainActivityFragment) getSupportFragmentManager().findFragmentById(R.id.animalQuizFragment);
myAnimalQuizFragment.modifyAnimalGuessRows(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyTypeofAnimals(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyQuizFont(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyBackgroundColor(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.resetAnimalQuiz();
isSettingsChanged = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent preferencesIntent = new Intent(this,SettingsActivity.class);
startActivity(preferencesIntent);
return super.onOptionsItemSelected(item);
}
private SharedPreferences.OnSharedPreferenceChangeListener settingsChangedListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
isSettingsChanged = true;
if (key.equals(GUESSES)){
myAnimalQuizFragment.modifyAnimalGuessRows(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(ANIMALS_TYPE)){
Set<String> animalTypes = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
if (animalTypes != null && animalTypes.size() > 0){
myAnimalQuizFragment.modifyTypeofAnimals(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else {
SharedPreferences.Editor editor = sharedPreferences.edit();
animalTypes.add(getString(R.string.default_animal_type));
editor.putStringSet(ANIMALS_TYPE, animalTypes); // here we provided default value also.......
editor.apply();
Toast.makeText(MainActivity.this, R.string.default_animalType_message, Toast.LENGTH_SHORT).show();
}
}else if (key.equals(QUIZ_FONT)){
myAnimalQuizFragment.modifyQuizFont(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(QUIZ_BACKGROUND_COLOR)){
myAnimalQuizFragment.modifyBackgroundColor(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}
Toast.makeText(MainActivity.this, R.string.toast_message , Toast.LENGTH_SHORT).show();
}
};
public void showDialog(){
ExampleDialog exampleDialog = new ExampleDialog();
exampleDialog.setCancelable(false);
exampleDialog.show(getFragmentManager(),"Animal_Quiz_Result");
}
}
Here is the MainActivityFragment.java class
import android.animation.Animator;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class MainActivityFragment extends Fragment {
public static final int NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ = 10;
private List<String> allAnimalsNameList;
private List<String> animalNamesQuizList;
private Set<String> animalTypesInQuiz;
private String correctAnimalsAnswer;
public static int numberOfAllGuesses;
private int numberOfAnimalGuessRows;
private int numberOfRightAnswers;
private SecureRandom secureRandomNumber;
private Handler handler;
private Animation wrongAnswerAnimation;
private LinearLayout animalQuizLinearLayout;
private TextView txtQuestionNumber;
private ImageView imgAnimal;
private LinearLayout[] rowsOfGuessButtonsInAnimalQuiz;
private TextView txtAnswer;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
allAnimalsNameList = new ArrayList<>();
animalNamesQuizList = new ArrayList<>();
secureRandomNumber = new SecureRandom();
handler = new Handler();
wrongAnswerAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.wrong_animation);
wrongAnswerAnimation.setRepeatCount(1);
animalQuizLinearLayout = view.findViewById(R.id.animalQuizLinearLayout);
txtQuestionNumber = view.findViewById(R.id.txtQuestionNumber);
imgAnimal = view.findViewById(R.id.imgAnimal);
rowsOfGuessButtonsInAnimalQuiz = new LinearLayout[3];
rowsOfGuessButtonsInAnimalQuiz[0] = view.findViewById(R.id.firstRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[1] = view.findViewById(R.id.secondRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[2] = view.findViewById(R.id.thirdRowLinearLayout);
txtAnswer = view.findViewById(R.id.txtAnswer);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz) {
for (int column = 0; column < row.getChildCount(); column++) {
Button btnGuess = (Button) row.getChildAt(column);
btnGuess.setOnClickListener(btnGuessListener);
btnGuess.setTextSize(24);
}
}
txtQuestionNumber.setText(getString(R.string.question_text, 1, NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
// getString is extends fragment...........
return view;
}
private View.OnClickListener btnGuessListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Button btnGuess = ((Button) view);
String guessValue = btnGuess.getText().toString();
String answerValue = getTheExactAnimalName(correctAnimalsAnswer);
++numberOfAllGuesses;
if (guessValue.equals(answerValue)) {
++numberOfRightAnswers;
txtAnswer.setText(answerValue + " ! " + " RIGHT");
disableQuizGuessButton();
if (numberOfRightAnswers == NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
} else {
handler.postDelayed(new Runnable() {
#Override
public void run() {
animateAnimalQuiz(true);
}
}, 1000); //1000 milliseconds for 1 second delay.......
}
} else {
imgAnimal.startAnimation(wrongAnswerAnimation);
txtAnswer.setText(R.string.wrong_answer_message);
btnGuess.setEnabled(false);
}
}
};
public static String getTheExactAnimalName(String animalName) {
return animalName.substring(animalName.indexOf('-') + 1).replace('_', ' ');
}// this method changes the actual name of image for example removes or starts after tame_animal- through index of method
// and after that removes _ between the names of animals...........
private void disableQuizGuessButton() {
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
LinearLayout guessRowLinearLayout = rowsOfGuessButtonsInAnimalQuiz[row];
for (int buttonIndex = 0; buttonIndex < guessRowLinearLayout.getChildCount(); buttonIndex++) {
guessRowLinearLayout.getChildAt(buttonIndex).setEnabled(false);
}
}
}
public void resetAnimalQuiz() {
AssetManager assets = getActivity().getAssets();
allAnimalsNameList.clear();
try {
for (String animalType : animalTypesInQuiz) {
String[] animalImagePathsInQuiz = assets.list(animalType);
for (String animalImagePathInQuiz : animalImagePathsInQuiz) {
allAnimalsNameList.add(animalImagePathInQuiz.replace(".png", ""));
}
}
} catch (IOException e) {
Log.e("AnimalQuiz", "Error", e);
}
numberOfRightAnswers = 0; // this variable holds the right guesses must be 0 because we reset the game.
numberOfAllGuesses = 0; // this variable holds no. of all guesses whether it is right or wrong have to be 0.
animalNamesQuizList.clear(); // this variable holds randomly generated quiz paths must be 0 to generate new paths......
int counter = 1;
int numberOfAvailableAnimal = allAnimalsNameList.size();// this variable holds number of available animals or the size or length of paths
while (counter <= NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
int randomIndex = secureRandomNumber.nextInt(numberOfAvailableAnimal);
String animalImageName = allAnimalsNameList.get(randomIndex);
if (!animalNamesQuizList.contains(animalImageName)) {
animalNamesQuizList.add(animalImageName);
++counter;
}
}
showNextAnimal();
}
private void animateAnimalQuiz(boolean animateOutAnimalImage) {
if (numberOfRightAnswers == 0) {
return;
}
int xTopLeft = 0;
int yTopLeft = 0;
int xBottomRight = animalQuizLinearLayout.getLeft() + animalQuizLinearLayout.getRight();
int yBottomRight = animalQuizLinearLayout.getTop() + animalQuizLinearLayout.getBottom();
//Here is max value for radius
int radius = Math.max(animalQuizLinearLayout.getWidth(), animalQuizLinearLayout.getHeight());
Animator animator;
if (animateOutAnimalImage) {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xBottomRight, yBottomRight, radius, 0);
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
showNextAnimal();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
} else {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xTopLeft, yTopLeft, 0, radius);
}
animator.setDuration(700);
animator.start();
}
private void showNextAnimal() {
String nextAnimalImageName = animalNamesQuizList.remove(0);
correctAnimalsAnswer = nextAnimalImageName;
txtAnswer.setText("");
txtQuestionNumber.setText(getString(R.string.question_text, (numberOfRightAnswers + 1), NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
String animalType = nextAnimalImageName.substring(0, nextAnimalImageName.indexOf("-")); // it holds the animal type whether it is
// Tame animal or Wild Animal
AssetManager assets = getActivity().getAssets();
try (InputStream stream = assets.open(animalType + "/" + nextAnimalImageName + ".png")) {
Drawable animalImage = Drawable.createFromStream(stream, nextAnimalImageName);
imgAnimal.setImageDrawable(animalImage);
animateAnimalQuiz(false);
} catch (IOException e) {
Log.e("AnimalQuiz", "There is an Error Getting" + nextAnimalImageName, e);
}
Collections.shuffle(allAnimalsNameList); // this method is a predefined method in java which helps to shuffle the list of data
int correctAnimalNameIndex = allAnimalsNameList.indexOf(correctAnimalsAnswer);
String correctAnimalName = allAnimalsNameList.remove(correctAnimalNameIndex);
allAnimalsNameList.add(correctAnimalName);
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
for (int column = 0; column < rowsOfGuessButtonsInAnimalQuiz[row].getChildCount(); column++) {
Button btnGuess = (Button) rowsOfGuessButtonsInAnimalQuiz[row].getChildAt(column);
btnGuess.setEnabled(true);
String animalImageName = allAnimalsNameList.get((row * 2) + column);
btnGuess.setText(getTheExactAnimalName(animalImageName));
}
}
int row = secureRandomNumber.nextInt(numberOfAnimalGuessRows);
int column = secureRandomNumber.nextInt(2);
LinearLayout randomRow = rowsOfGuessButtonsInAnimalQuiz[row];
String correctAnimalImageName = getTheExactAnimalName(correctAnimalsAnswer);
((Button) randomRow.getChildAt(column)).setText(correctAnimalImageName);
}
public void modifyAnimalGuessRows(SharedPreferences sharedPreferences){
final String NUMBER_OF_GUESS_OPTION = sharedPreferences.getString(GUESSES,null);
numberOfAnimalGuessRows = Integer.parseInt(NUMBER_OF_GUESS_OPTION)/2;
for (LinearLayout horizontalLinearLayout : rowsOfGuessButtonsInAnimalQuiz){
horizontalLinearLayout.setVisibility(View.GONE);
}
for (int row = 0; row < numberOfAnimalGuessRows; row++){
rowsOfGuessButtonsInAnimalQuiz[row].setVisibility(View.VISIBLE);
}
}
public void modifyTypeofAnimals(SharedPreferences sharedPreferences){
animalTypesInQuiz = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
}
public void modifyQuizFont(SharedPreferences sharedPreferences){
String fontStringValue = sharedPreferences.getString(QUIZ_FONT,null);
switch (fontStringValue){
case "Chunkfive.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(chunkFive);
}
}
break;
case "Azkia demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(azkiaDemo);
}
}
break;
case "FontleroyBrown.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(fontleroyBrown);
}
}
break;
case "Haunted Eyes.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(hauntedEyes);
}
}
break;
case "Knight Brush Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(knightBrushDemo);
}
}
break;
case "Wonderbar Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(wonderbarDemo);
}
}
break;
}
}
public void modifyBackgroundColor(SharedPreferences sharedPreferences){
String backgroundColor = sharedPreferences.getString(QUIZ_BACKGROUND_COLOR,null);
switch (backgroundColor){
case "White":
animalQuizLinearLayout.setBackgroundColor(Color.WHITE);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.rgb(34,167,240));
break;
case "Black":
animalQuizLinearLayout.setBackgroundColor(Color.BLACK);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(247,202,24));
button.setTextColor(Color.BLACK);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Green":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(38,166,91));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.rgb(247,202,24));
txtAnswer.setTextColor(Color.WHITE);
break;
case "Yellow":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(247,202,24));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.BLACK);
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.BLACK);
break;
case "Red":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(240,52,52));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Blue":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(34,167,240));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(240,52,52));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
}
}
}
Here is the ExampleDialog.java class
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import static com.example.narayanmaity.app61animal_quiz.MainActivityFragment.numberOfAllGuesses;
/**
* Created by Narayan Maity on 12/14/2017.
*/
public class ExampleDialog extends DialogFragment {
MainActivityFragment myAnimalQuizFragment;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.results_string_value, numberOfAllGuesses,
(1000 / (double) numberOfAllGuesses)));
builder.setPositiveButton(R.string.result_animal_quiz, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myAnimalQuizFragment.resetAnimalQuiz();
}
});
return builder.create();
}
}
The problem is in this line.Remove the line below from your code
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
You never ever create an Activity's instance with new operator. Its android Component class it initializes automatically with Intent . All Activities in android must go through a lifecycle so that they have a valid context attached to them. Read Activity.
The solution for this problem.
if(getActivity()!=null){
((MainActivity)getActivity()).showDialog()
}
For your new problem which you mentioned in comments.
You never assign myAnimalQuizFragment so it will give you NullPointerException anyway . Access it from your MainActivity.
((MainActivity)getActivity()).myAnimalQuizFragment.resetAnimalQuiz();
Make myAnimalQuizFragment as public in MainActivity.

Issue with checkbox checked

i am use this for setting checkbox in listview i have follow all step as per given tutorial, but there are some critical issue with output, is that when i am select first checkbox and scroll down it will change selected item and automatically appear 3rd.
so i think there are something wrong with getview. so please help me out this ....
here is my code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
public class Favorites extends ListActivity {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
ArrayList alAppName;
float[] rate;
boolean[] bSelected;
ArrayList<Comment> alPackagenm;
Drawable[] alIcon;
ViewHolder holder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
for (int i = 0; i < strAr.length; i++) {
System.out.println("strAr[" + i + "] " + strAr[i]);
}
for (String s : strAr) {
list.add(new RowModel(s));
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
}
});
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.ratingBar1.setOnRatingBarChangeListener(l);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
return (row);
}
}
}
I really don't understand your code exactly what you are trying to do. I haven't seen before this you are checking holder == null where as it should be convertView == null. If you have a scrolling issue you can check my blog post
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
...
}
else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
Use Below Code to your MainActivity.java file.
public class ListViewActivity extends Activity {
ListView mLstView1;
Button mBtn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLstView1 = (ListView) findViewById(R.id.mLstView1);
String[] lv_items = { "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil", "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil" };
;
mLstView1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
mLstView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Using a List to hold the IDs, but could use an array.
List<Integer> checkedIDs = new ArrayList<Integer>();
// Get all of the items that have been clicked - either on or
// off
final SparseBooleanArray checkedItems = mLstView1
.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
// And this tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if (isChecked) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// Put the value of the id in our list
checkedIDs.add(position);
System.out.println("Position is:- " + position);
}
}
}
});
}
}

Categories