how to prevent to creating the duplicate item while scrolling my recyclerview - android-adapter

Here is My AdapterClass AvailablePateientAdapter.java
plaese let me know the how to resolve this issue while scrolling my recyclerview each time increasing the duplicate items
Thanks in advance.
public class AvailablePatientsAdapter extends RecyclerView.Adapter<AvailablePatientsAdapter.AvailablePatientListViewHolder> {
static ReportData patData = null;
private static String niramaiID= null;
static ProgressBar progBar ;
private static ProgressDialog progressDialog;
private static LayoutInflater mInflater = null;
private static ViewPendingList viewPendingList;
private static List<PatientData> patients;
private static Context mContext;
static boolean isPending = false;
int postion;
private static boolean clicked = true;
static String repStatus ;
static Handler viewPatHandler= new Handler(){
#Override
public void handleMessage(Message msg){
patData.setStatusReport(repStatus);
// progressDialog.show();
if(niramaiID != null) {
if (msg.what == 1) {
getexaminationtable(niramaiID);
} else if (msg.what == 2) {
getsegmentationtable(niramaiID);
} else if (msg.what == 3) {
getthanalysistable(niramaiID);
} else if (msg.what == 4) {
Log.d(Config.LOG_TAG, "Response:1 status report " + patData.getStatusReport());
String viewPat = patData.toJson();
Intent addPatFromEdit = new Intent();
addPatFromEdit.setClass(mContext, DisplayReport.class);
addPatFromEdit.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
addPatFromEdit.putExtra("display_report", viewPat);
// addPatFromEdit.putExtra("is_pending",isPending);
if(progressDialog.isShowing()) {
progressDialog.hide();
}
mContext.startActivity(addPatFromEdit);
progBar.setVisibility(View.GONE);
}
}else
{
if(progressDialog.isShowing()) {
progressDialog.hide();
}
Toast.makeText(mContext,"Niramai id is null ",Toast.LENGTH_SHORT).show();
}
}
};
static class AvailablePatientListViewHolder extends RecyclerView.ViewHolder{
private static SimpleDateFormat oudSdf = new SimpleDateFormat("dd-MMM-yyyy");
private static SimpleDateFormat inSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
AvailablePatientsAdapter mPatientBinding;
ViewPendingList viewPendingList;
AvailablePatientListViewHolder(View itemView) {
super(itemView);
}
// public AvailablePatientListViewHolder(ViewPendingList viewPendingList,View item){
// super(item);
// this.viewPendingList = viewPendingList;
// }
void bind(final PatientData data) {
RelativeLayout b = itemView.findViewById(R.id.rel_available);
niramaiID = data.getNiramaiId();
// progBar.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.postDelayed(new Runnable(){
#Override
public void run() {
Log.d(Config.LOG_TAG," data.getStatus() :: "+data.getStatus());
int muID;
if(NiramaiMythriApplication.getDefaultInt(UNINVERSAL_MUID,mContext) != 0)
{
muID = NiramaiMythriApplication.getDefaultInt(UNINVERSAL_MUID,mContext);
}else
{
muID = LoggedInUser.Users.getDetails().getMu().get(0).getId();
}
getPatientDetails(itemView.getContext(), data.getStatus(),muID ,data.getNiramaiId(),data.getPatientId(), itemView);
progBar.setVisibility(View.GONE);
}
},500);
}
});
TextView patientID = (TextView) itemView.findViewById(R.id.patientID);
TextView scandate = (TextView) itemView.findViewById(R.id.scanDate);
try {
scandate.setText(oudSdf.format(inSdf.parse(data.getScanDate())));
} catch (ParseException e) {
e.printStackTrace();
}
patientID.setText(data.getPatientId());
}
AvailablePatientsAdapter getPatientBinding(){
return this.mPatientBinding;
}
}
public AvailablePatientsAdapter(Context c, #Nullable List<PatientData> p){
mContext=c;
patients = p;
setHasStableIds(true);
progressDialog = new ProgressDialog(mContext);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
}
#Override
public AvailablePatientListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.available_patient_list, parent, false);
mContext = parent.getContext();
progBar = new ProgressBar(parent.getContext());
return new AvailablePatientListViewHolder(itemView);
}
#Override
public void onBindViewHolder(AvailablePatientListViewHolder holder, int position) {
// Log.e("ADAPTER","pos:"+position );
final PatientData p = patients.get(position);
holder.bind(p);
holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return patients.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void setPatientList(List<PatientData> p, Boolean isPendingActivity){
isPending = isPendingActivity;
patients = p;
notifyDataSetChanged();
}
// Dharam
public void clickOnRecyclerViewItem(boolean click){
clicked = click;
}
private static void getPatientDetails(final Context context, final String status, int muID, String niramaiID, String pID, final View itemView){
if(!progressDialog.isShowing()) {
progressDialog.show();
}
ApiInterface mApiService = RetrofitFactory.getInterfaceService();
Log.d(Config.LOG_TAG,"Call Start muID in Av Report :: "+muID+" niramaiID :: "+niramaiID+" pID :: "+pID);
repStatus = status;
mApiService.getPatientReportData(muID,niramaiID,pID).enqueue(new Callback<ReportData>() {
#Override
public void onResponse(Call<ReportData> call, Response<ReportData> response) {
patData = response.body();
Log.d(Config.LOG_TAG,"patData status color "+ patData);
// progBar.setVisibility(View.VISIBLE);
viewPatHandler.sendEmptyMessage(1);
}
#Override
public void onFailure(Call<ReportData> call, Throwable t) {
// itemView.setClickable(true);
Log.e(Config.LOG_TAG,"An getPatientDetails Error Occured: "+t.getMessage());
}
});
}
private static void getexaminationtable(String niramaiId) {
ApiInterface mApiService = RetrofitFactory.getInterfaceService();
Log.d(Config.LOG_TAG,"getexaminationtable Start");
if(!progressDialog.isShowing()) {
progressDialog.show();
}
mApiService.getExaminationTable(niramaiId).enqueue(new Callback<List<CBEData>>() {
#Override
public void onResponse(Call<List<CBEData>> call, Response<List<CBEData>> response) {
Log.d(Config.LOG_TAG, "Response Body :: "+response.body());
if(response.body() != null && response.body().size()>=1) {
viewPatHandler.sendEmptyMessage(2);
}
}
#Override
public void onFailure(Call<List<CBEData>> call, Throwable t) {
Log.e(Config.LOG_TAG,"An getexaminationtable Error Occured: "+t.getMessage());
}
});
}
private static void getsegmentationtable(String niramaiId) {
ApiInterface mApiService = RetrofitFactory.getInterfaceService();
Log.d(Config.LOG_TAG,"getsegmentationtable Start");
if(!progressDialog.isShowing()) {
progressDialog.show();
}
mApiService.getSegmentationTable(niramaiId).enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
response.body();
viewPatHandler.sendEmptyMessage(3);
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
Log.e(Config.LOG_TAG,"An getsegmentationtable Error Occured: "+t.getMessage());
}
});
}
private static void getthanalysistable(String niramaiId) {
ApiInterface mApiService = RetrofitFactory.getInterfaceService();
Log.d(Config.LOG_TAG,"getthanalysistable Start");
if(!progressDialog.isShowing()) {
progressDialog.show();
}
mApiService.getthanAlysisTable(niramaiId).enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
response.body();
viewPatHandler.sendEmptyMessage(4);
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
Log.e(Config.LOG_TAG,"An getthanalysistable Error Occured: "+t.getMessage());
}
});
}
}
Here is my Activity AvailablePateint.class
can you please let me know also why is it occurring each time while scrolling each time.
public class AvailablePatients extends Activity {
#BindView(R.id.patientsSwipeView) SwipeRefreshLayout swipeContainer;
#BindView(R.id.patientList) RecyclerView patientListView;
#BindView(R.id.searchBox) EditText searchBox;
private Context context;
private boolean clicked;
static String MY_PREFS_NAME = "NIRAMAI_PREFERENCE";
String LOG_TAG = "Niramai";
ApiInterface mApiService;
List<PatientData> allPatientData;
List<PatientData> displayPatientData;
List<PatientData> filteredPatientData;
List<PatientData> availablePatData;
Patients patient;
// List<patient_> patient_ = null;
private AvailablePatientsAdapter mPA;
private user mLoginObject;
// List<IndividualPatient> eachpatient = null;
#BindView(R.id.drawerView) PlaceHolderView mDrawerView;
#BindView(R.id.drawerLayout) DrawerLayout mDrawer;
#BindView(R.id.toolbar_all) Toolbar mToolbar;
int muid = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_report);
availablePatData = new ArrayList<>();
context = this;
ButterKnife.bind(this);
mLoginObject = LoggedInUser.Users.getDetails();
if(mLoginObject == null)
{
Toast.makeText(this,"Please Login Again !!",Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(this, LoginActivity.class);
//dharam
myIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK );
ComponentName cn = myIntent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
finish();
}
SharedPreferences pref = getSharedPreferences("NiramaiPrefrence", Context.MODE_PRIVATE);
if(mLoginObject != null) {
muid = mLoginObject.getMu().get(0).getId();
}
mPA = new AvailablePatientsAdapter(this,new ArrayList<PatientData>());
patientListView.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL,
false));
RecyclerSectionItemDecoration sectionItemDecoration =
new RecyclerSectionItemDecoration(false,getResources().getDimensionPixelSize(R.dimen.recycler_section_header_height),
true,
getSectionCallback());
patientListView.addItemDecoration(sectionItemDecoration);
patientListView.setAdapter(mPA);
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
displayPatientData = new ArrayList<>();
if(availablePatData==null) return;
for(PatientData pd : availablePatData){
if (pd.getPatientId().contains(charSequence)){
displayPatientData.add(pd);
}
}
Collections.sort(displayPatientData, new Comparator<PatientData>() {
#Override
public int compare(PatientData p1, PatientData p2) {
return p1.getPatientId().compareTo(p2.getPatientId());
}
});
mPA.setPatientList(displayPatientData,false);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeContainer.setRefreshing(true);
if(NiramaiMythriApplication.getDefaultInt(UNINVERSAL_MUID,AvailablePatients.this) != 0) {
getAllPatientDataWithRetrofit((NiramaiMythriApplication.getDefaultInt(UNINVERSAL_MUID,AvailablePatients.this)));
}else
{
getAllPatientDataWithRetrofit(muid);
}
}
});
swipeContainer.setRefreshing(true);
if(NiramaiMythriApplication.getDefaultInt(UNINVERSAL_MUID,AvailablePatients.this) != 0) {
getAllPatientDataWithRetrofit((NiramaiMythriApplication.getDefaultInt(UNINVERSAL_MUID,AvailablePatients.this)));
}else
{
getAllPatientDataWithRetrofit(muid);
}
setupDrawer();
}
private RecyclerSectionItemDecoration.SectionCallback getSectionCallback() {
return new RecyclerSectionItemDecoration.SectionCallback() {
#Override
public boolean isSection(int position) {
return false;
}
#Override
public CharSequence getSectionHeader(int position) {
return "Patient ";
}
};
}
private void availablePatData(List<PatientData> patData) {
int j = 0;
Log.d(Config.LOG_TAG, "size" + patData.size());
for (int i = 0; i < patData.size(); i++) {
// Log.d(Config.LOG_TAG, "Patient id" + patData.get(i).getPatientId());
if (patData.get(i).getStatus().equalsIgnoreCase(getResources().getString(R.string.report_status_available)) ||
patData.get(i).getStatus().equalsIgnoreCase(getResources().getString(R.string.report_status_screening_done))) {
availablePatData.add(j,patData.get(i));
j++;
}
}
}
private void getAllPatientDataWithRetrofit(int muID) {
mApiService = RetrofitFactory.getInterfaceService();
Call mService = mApiService.getAllPatients(muID);
mService.enqueue(new Callback<List<Patients>>() {
#Override
public void onResponse(Call<List<Patients>> call, Response<List<Patients>> response) {
if(response.isSuccessful()) {
patient= response.body().get(0);
allPatientData = patient.getPatientData();
try {
filteredPatientData = filterPatients(allPatientData);
} catch (ParseException e) {
e.printStackTrace();
}
availablePatData(filteredPatientData);
displayPatientData = availablePatData;
mPA.setPatientList(displayPatientData,false);
mPA.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
Log.d(LOG_TAG,"Response string is ::: "+ patient.toString());
}
}
#Override
public void onFailure(Call<List<Patients>> call, Throwable t) {
call.cancel();
swipeContainer.setRefreshing(false);
Log.e(LOG_TAG,"getAllPatientDataWithRetrofit process failed in response: "+t.getMessage());
}
});
if(mService.isExecuted())
{
}
}
// Filters All patient to keep only single latest record of each patient id
private List<PatientData> filterPatients(List<PatientData> allPatientData) throws ParseException {
HashMap<String ,Pair<PatientData,Date>> filtered = new HashMap<>();
SimpleDateFormat inSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
for(PatientData p : allPatientData){
if(filtered.containsKey(p.getPatientId())){
Pair<PatientData,Date> _p = filtered.get(p.getPatientId());
Date d1 = _p.second;
Date d2 = inSdf.parse(p.getScanDate());
if(d2.after(d1)){
filtered.put(p.getPatientId(), new Pair<>(p, d2));
}
}else{
if(p.getScanDate() != null)
filtered.put(p.getPatientId(), new Pair<>(p, inSdf.parse(p.getScanDate())));
}
}
List<Pair<PatientData,Date>> filteredPairs = new ArrayList<>(filtered.values());
Collections.sort(filteredPairs,new Comparator<Pair<PatientData, Date>>() {
#Override
public int compare(Pair<PatientData, Date> t1, Pair<PatientData, Date> t2) {
if(t1.second.after(t2.second)){
return -1;
}else if (t1.second.before(t2.second)){
return 1;
}
else
return t1.first.getPatientId().compareTo(t2.first.getPatientId());
}
});
List<PatientData> filteredList = new ArrayList<>(filteredPairs.size());
for(Pair<PatientData,Date> p : filteredPairs){
filteredList.add(p.first);
}
return filteredList;
}
#Override
protected void onResume() {
super.onResume();
mPA.clickOnRecyclerViewItem(true);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
private void setupDrawer(){
mDrawerView
.addView(new DrawerHeader())
.addView(new DrawerMenuItem(this.getApplicationContext(),1))
.addView(new DrawerMenuItem(this.getApplicationContext(),2))
.addView(new DrawerMenuItem(this.getApplicationContext(),3))
.addView(new DrawerMenuItem(this.getApplicationContext(),4));
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawer.addDrawerListener(drawerToggle);
drawerToggle.syncState();
}
}

Basically when we are adding new item in the list it needs refresh it but while refreshing it you will see the duplicates of the existing items because of previous list was not empty the list had some items. So clear the list first before adding the items in the list.
add the following changes in ActivityPatient.java
private void availablePatData(List<PatientData> patData) {
int j = 0;
if(availablePatData.size()>=0){
availablePatData.clear();
}
Log.d(Config.LOG_TAG, "size" + patData.size());
for (int i = 0; i < patData.size(); i++) {
// Log.d(Config.LOG_TAG, "Patient id" + patData.get(i).getPatientId());
if (patData.get(i).getStatus().equalsIgnoreCase(getResources().getString(R.string.report_status_available)) ||
patData.get(i).getStatus().equalsIgnoreCase(getResources().getString(R.string.report_status_screening_done))) {
availablePatData.add(j,patData.get(i));
j++;
}
}
}

Related

DynamoDB: Enum as partition key giving error "Missing the key id in the item" when putItem

I am using the enum as the partition key and my model looks like below
#DynamoDbBean
public class Item {
public enum Key {
KEY_A(false),
KEY_B(2),
private final Object defaultValue;
private Key(Object defaultValue) {
this.defaultValue = defaultValue;
}
public Object getDefaultValue() {
return this.defaultValue;
}
}
private Key key;
private Object value;
public Item() {
}
public Item(Key key) {
this.key = key;
this.value = key.getDefaultValue();
}
#DynamoDbConvertedBy(KeyEnumConverter.class)
#DynamoDbPartitionKey
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
#DynamoDbConvertedBy(ValueConverter.class)
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
My Converter classes to convert between java object and DDB data type is as below:
public class KeyEnumConverter implements AttributeConverter<Item.Key> {
#Override
public AttributeValue transformFrom(Item.Key key) {
return EnhancedAttributeValue.fromString(key.toString()).toAttributeValue();
}
#Override
public Item.Key transformTo(AttributeValue attributeValue) {
return Item.Key.valueOf(attributeValue.s());
}
#Override
public EnhancedType<Item.Key> type() {
return EnhancedType.of(Item.Key.class);
}
#Override
public AttributeValueType attributeValueType() {
return AttributeValueType.S;
}
public class ValueConverter implements AttributeConverter<Object> {
#Override
public AttributeValue transformFrom(Object Value) {
return getEnhancedAttributeValue(Value).toAttributeValue();
}
#Override
public Object transformTo(AttributeValue attributeValue) {
return JsonConvertor.getObjectFromJsonString(attributeValue.s(), Object.class);
}
#Override
public EnhancedType<Object> type() {
return EnhancedType.of(Object.class);
}
#Override
public AttributeValueType attributeValueType() {
return AttributeValueType.S;
}
private EnhancedAttributeValue getEnhancedAttributeValue (Object value) {
if (Value instanceof Boolean) {
return EnhancedAttributeValue.fromBoolean((Boolean)Value);
} else if(value instanceof Number) {
return EnhancedAttributeValue.fromNumber(String.valueOf(value));
} else {
throw new IllegalArgumentException("Please add support for type " + value.getClass().getSimpleName());
}
}
}
When I am putting an item into the table:
public void saveItem (String itemKey) {
Table.putItem(new Item(Item.Key.valueOf(itemKey)));
}
I got the error:
One or more parameter values were invalid: Missing the key id in the item
The partitionKey is defined in the model, why the key id still missing

Android if statement doesnt work on setOnClickListener

I have create a walkthrough android studio screen of 3 slides and I need that when I push the button mNextBtn, at the third slide, it change to another Java class. As you can see in the code below I've used an if statement but it doesn't work because when I run and I push the mButtonBtn button the app stop, how can I fix it?
public class Portada extends AppCompatActivity {
private ViewPager mSlideViewPager;
private LinearLayout mDotLayout;
private TextView[] mDots;
private SliderAdapter sliderAdapter;
private Button mNextBtn;
private Button mBackBtn;
private int mCurrentpage;
int mLogin;
public void onLogin (){
if (mDots.length == 3){
Intent intent= new Intent(Portada.this, Login.class);
startActivity(intent);
}else
{
mSlideViewPager.setCurrentItem(mCurrentpage + 1);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_portada);
mSlideViewPager = (ViewPager) findViewById(R.id.slideViewPager);
mDotLayout = (LinearLayout) findViewById(R.id.dotsLayout);
mNextBtn = (Button) findViewById(R.id.nextBtn);
mBackBtn = (Button) findViewById(R.id.prevBtn);
sliderAdapter = new SliderAdapter(this);
mSlideViewPager.setAdapter(sliderAdapter);
addDotsIndicator(0);
mSlideViewPager.addOnPageChangeListener(viewListerer);
mNextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mDots.length == 3){
Intent intent= new Intent(getApplicationContext(), Login.class);
startActivity(intent);
}else
{
mSlideViewPager.setCurrentItem(mCurrentpage + 1);
}
}
});
mBackBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSlideViewPager.setCurrentItem(mCurrentpage - 1);
}
});
}
public void addDotsIndicator(int position) {
mDots = new TextView[3];
mDotLayout.removeAllViews();
for(int i = 0; i < mDots.length; i++ ){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(50);
mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));
mDotLayout.addView(mDots[i]);
}
if (mDots.length > 0){
mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
}
}
ViewPager.OnPageChangeListener viewListerer = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
addDotsIndicator(i);
mCurrentpage = i;
if (i == 0){
mNextBtn.setEnabled(true);
mBackBtn.setEnabled(false);
mBackBtn.setVisibility(View.INVISIBLE);
mNextBtn.setText("NEXT");
mBackBtn.setText("");
}else if(i == mDots.length - 1) {
mNextBtn.setEnabled(true);
mBackBtn.setEnabled(true);
mBackBtn.setVisibility(View.VISIBLE);
mNextBtn.setText("FINISH");
mBackBtn.setText("BACK");
}else {
mNextBtn.setEnabled(true);
mBackBtn.setEnabled(true);
mBackBtn.setVisibility(View.VISIBLE);
mNextBtn.setText("NEXT");
mBackBtn.setText("BACK");
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
};
}
`

How to get all property of child class in 'List' element in C#?

I want to get all property in child class and all from base class when i add it into List<>.
My Child class "SellNumber.cs":
class SellNumber : Entity
{
public SellNumber()
{
TableName = "tbl_sell_number";
Record_status = (int)EStatusRecord.NEW;
Buyer_number = new SecurityHelper().getCurrentIndexOfBuyer();
}
private long id_number;
public long Id_number
{
get { return id_number; }
set { id_number = value; }
}
private int lottery_buy;
public int Lottery_buy
{
get { return lottery_buy; }
set { lottery_buy = value; }
}
private long price_buy_number;
public long Price_buy_number
{
get { return price_buy_number; }
set { price_buy_number = value; }
}
private long buyer_number;
public long Buyer_number
{
get { return buyer_number; }
set { buyer_number = value; }
}
private int channel_id;
public int Channel_id
{
get { return channel_id; }
set { channel_id = value; }
}
private int shift_id;
public int Shift_id
{
get { return shift_id; }
set { shift_id = value; }
}
}
Base class
class Entity : BaseEntity
{
public Entity()
{
User_create = new SecurityHelper().getCurrentUser();
User_update = new SecurityHelper().getCurrentUser();
Date_create = DateHelper.DATE_TO_DAY_DAYTIME;
Date_update = DateHelper.DATE_TO_DAY_DAYTIME;
}
private long user_create;
public long User_create
{
get { return user_create; }
set { user_create =value; }
}
private long user_update;
public long User_update
{
get { return user_update; }
set { user_update = value; }
}
private String date_create;
public String Date_create
{
get { return date_create; }
set { date_create = value; }
}
private String date_update;
public String Date_update
{
get { return date_update; }
set { date_update = value; }
}
private int record_status;
public int Record_status
{
get { return record_status; }
set { record_status = value; }
}
}
Edited:
I want to get all property in child class and all from base class when i add it into List<>. I have class 'SellNumber.cs' which extends from class 'Entity.cs', so I want to use all properties of parent class to use with collection 'List'.

EclipseLink JPA #OneToMany List is not same in differernt request of same session in Jesery REST

I have two entities as People and Story. Now I post my story and check my stories, but returns different Story List occasionally. I mean, usr.stories.hashCode() is not same in differernt request from the exactly same user. The database table is always correct, so I am very confused. I checked out Hibernate reference for better details, but it didn't help at all.
Model class:
#MappedSuperclass
public class People{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer id;
#OrderBy(value = "id DESC")
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "people")
public List<Story> stories = new LinkedList<Story>();
public People(){
}
}
#MappedSuperclass
public class Story{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "people_id")
public People people;
#Column(name = "story", nullable = false)
public String story;
public Story(String story){
this.story = story;
}
}
REST class:
#Path("/story")
public class StoryRS {
#POST
public StreamingOutput create(final #Context HttpServletRequest req, final String story) throws IOException{
return new StreamingOutput() {
#Override
public void write(OutputStream os) {
HttpSession hs = req.getSession(false);
if (hs != null && story != null && story.trim().length() > 0) {
Integer uid = (Integer) hs.getAttribute("uid");
People usr = uid != null ? PeopleDAO.findById(uid) : null;
if (usr != null) {
Story obj = new Story(story);
EntityManagerHelper.beginTransaction();
StoryDAO.save(obj);
EntityManagerHelper.commit();
os.write(obj.id);
}
}
os.close();
}
};
}
#GET
public StreamingOutput create(final #Context HttpServletRequest req) throws IOException{
return new StreamingOutput() {
#Override
public void write(OutputStream os) {
HttpSession hs = req.getSession(false);
if (hs != null && story != null && story.trim().length() > 0) {
Integer uid = (Integer) hs.getAttribute("uid");
People usr = uid != null ? PeopleDAO.findById(uid) : null;
if (usr != null && usr.stories != null && usr.stories.size()>0) {
os.write(usr.stories...);
}
}
os.close();
}
};
}
}
PeopleDAO:
public class PeopleDAO{
#Override
public void save(People entity) {
try {
getEntityManager().persist(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("save failed", Level.SEVERE, re);
throw re;
}
}
#Override
public void delete(People entity) {
try {
entity = getEntityManager().getReference(People.class, entity.getId());
getEntityManager().remove(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("delete failed", Level.SEVERE, re);
throw re;
}
}
#Override
public People update(People entity) {
try {
People result = getEntityManager().merge(entity);
return result;
} catch (RuntimeException re) {
EntityManagerHelper.log("update failed", Level.SEVERE, re);
throw re;
}
}
#Override
public People findById(Integer id) {
try {
People instance = getEntityManager().find(People.class, id);
return instance;
} catch (RuntimeException re) {
EntityManagerHelper.log("find failed", Level.SEVERE, re);
throw re;
}
}
StoryDAO:
public class StoryDAO{
#Override
public void save(Story entity) {
try {
getEntityManager().persist(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("save failed", Level.SEVERE, re);
throw re;
}
entity.People.stories.add(0, entity);
}
#Override
public void delete(Story entity) {
try {
entity = getEntityManager().getReference(Story.class, entity.getId());
getEntityManager().remove(entity);
} catch (RuntimeException re) {
EntityManagerHelper.log("delete failed", Level.SEVERE, re);
throw re;
}
entity.People.stories.remove(entity);
}
#Override
public Story update(Story entity) {
try {
Story result = getEntityManager().merge(entity);
return result;
} catch (RuntimeException re) {
EntityManagerHelper.log("update failed", Level.SEVERE, re);
throw re;
}
}
#Override
public Story findById(Integer id) {
try {
Story instance = getEntityManager().find(Story.class, id);
return instance;
} catch (RuntimeException re) {
EntityManagerHelper.log("find failed", Level.SEVERE, re);
throw re;
}
}
EntityManagerHelper:
public class EntityManagerHelper {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
private static final Logger logger;
static {
emf = Persistence.createEntityManagerFactory("db");
threadLocal = new ThreadLocal<EntityManager>();
logger = Logger.getLogger("db");
logger.setLevel(Level.ALL);
}
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
threadLocal.set(null);
if (em != null)
em.close();
}
public static void beginTransaction() {
getEntityManager().getTransaction().begin();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static Query createQuery(String query) {
return getEntityManager().createQuery(query);
}
Thanks a lot for any response
Here's your problem
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
EntityManager's are supposed to be short-lived objects. They're cheap to make and cheap to destroy. It also explains why you are getting inconsistent results. EntityManagers have an internal cache which is surprisingly aggressive.
The rule for working with EM's is "One EntityManager per transaction."
Change your code to get a new EM every time and your problems will go away.

How to add different layouts for children in expandable list view in android?

I'm trying to implement expendable list view with two different layouts for children in different groups. After quite a bit of searching I came up with the following code for my adapter. When I run application and try to expand last group (of 4 groups) it crashes with
ArrayIndexOutOfBoundsException: length=2; index=2
no matter for which group I check the condition in getChildType:
public int getChildType (int groupPosition, int childPosition) {
Log.i(TAG, "getChildType("+groupPosition+","+childPosition+") called");
if (groupPosition == 3)
return 1;
else return 0;
}
Thanks for any help!
Code for adapter:
public class ExpListAdapter extends BaseExpandableListAdapter {
private String TAG = "ExpListAdapter";
private String arrGroupelements[];
private String arrChildelements[][][];
private Context myContext;
public ExpListAdapter(Context context, String[] groupElements, String[][][] childElements) {
myContext = context;
arrGroupelements = groupElements;
arrChildelements = childElements;
}
public Object getChild(int groupPosition, int childPosition) {
return arrChildelements[groupPosition][childPosition];
}
public int getChildType (int groupPosition, int childPosition) {
Log.i(TAG, "getChildType("+groupPosition+","+childPosition+") called");
if (groupPosition == 3)
return 1;
else return 0;
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView( int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int gp = groupPosition;
int cp = childPosition;
Log.d(TAG, "groupPosition: "+gp);
Log.d(TAG, "childPosition: "+cp);
Log.d(TAG, "isLastChild: "+isLastChild);
if (convertView == null) {
if (getChildType(groupPosition,childPosition)==0)
convertView = inflater.inflate(R.layout.child_row, null);
else
convertView = inflater.inflate(R.layout.child_row_slide_btn, null);
}
if (getChildType(groupPosition,childPosition)==0) {
TextView fieldInfo = (TextView) convertView.findViewById(R.id.fieldInfo);
fieldInfo.setText(arrChildelements[gp][cp][0]);
EditText editField = (EditText) convertView.findViewById(R.id.editField);
editField.setText(arrChildelements[gp][cp][1], null);
editField.addTextChangedListener( new TextWatcher() {
public void afterTextChanged(Editable s) {
// Log.i(TAG,"afterTextChanged called");
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
} else {
CheckBox cb = (CheckBox)convertView.findViewById(R.id.onOff);
cb.setText("konj");
}
return convertView;
}
public int getChildTypeCount (int groupPosition) {
if (groupPosition==3)
return 2;
else
return 1;
}
public int getChildrenCount(int groupPosition) {
return arrChildelements[groupPosition].length;
}
public Object getGroup(int groupPosition) {
return arrGroupelements[groupPosition];
}
public int getGroupCount() {
return arrGroupelements.length;
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_row, null);
}
TextView groupTitle = (TextView) convertView.findViewById(R.id.groupTitle);
groupTitle.setText(arrGroupelements[groupPosition]);
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Seems the logic for getChildTypeCount(int groupPosition) and getChildType(int groupPosition, int childPosition) is not matching.
When group position is not 3 the type is 1 but count is 1 (which means there are more than 1 type)