C++/CX CreateTask pass value - c++

I pass value to property of class in CreateTask, use the property value outside the AsyncTask class, the property value is not change, but the property value change in button click event.
the CreateTask in the AsyncTask class, AsyncTask class have a N property
namespace CreateTask
{
public ref class AsyncTask sealed : INotifyPropertyChanged
{
public:
AsyncTask();
void InitTask();
void ShowN();
IAsyncOperation<float64>^ GetPrimesAsync(float64 x, float64 y);
private:
float64 _n;
bool _isPropertyChangedObserved;
event PropertyChangedEventHandler^ _privatePropertyChanged;
protected:
void OnPropertyChanged(Platform::String^ propertyName)
{
if (_isPropertyChangedObserved)
{
PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
}
}
public:
property float64 N
{
float64 get()
{
return _n;
}
void set(float64 value)
{
_n = value;
OnPropertyChanged("N");
}
}
virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged
{
virtual Windows::Foundation::EventRegistrationToken add(Windows::UI::Xaml::Data::PropertyChangedEventHandler^ e)
{
_isPropertyChangedObserved = true;
return _privatePropertyChanged += e;
}
virtual void remove(Windows::Foundation::EventRegistrationToken t)
{
_privatePropertyChanged -= t;
}
protected:
virtual void raise(Object^ sender, Windows::UI::Xaml::Data::PropertyChangedEventArgs^ e)
{
if (_isPropertyChangedObserved)
{
_privatePropertyChanged(sender, e);
}
}
}
};
}
this code is AsyncTask.Cpp
AsyncTask::AsyncTask()
{
InitTask();
}
void AsyncTask::InitTask()
{
create_task(GetPrimesAsync(111.1, 222.2)).then(
[this](float64 z)
{
N = z;
});
}
IAsyncOperation<float64>^ AsyncTask::GetPrimesAsync(float64 x, float64 y)
{
return create_async([this, x, y]() -> float64
{
// Ensure that the input values are in range.
float64 z;
z = x + y;
return z;
});
}
void AsyncTask::ShowN()
{
MessageDialog^ msg = ref new MessageDialog(N.ToString());
msg->ShowAsync();
}
this MainPage.xaml.h code
namespace CreateTask
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public ref class MainPage sealed
{
public:
MainPage();
private:
AsyncTask^ asyncTask;
private:
void Click_Button(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
};
}
this MainPage.xaml.cpp code
MainPage::MainPage()
{
InitializeComponent();
asyncTask = ref new AsyncTask();
MessageDialog^ msg = ref new MessageDialog(asyncTask->N.ToString());
msg->ShowAsync();
}
void CreateTask::MainPage::Click_Button(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
MessageDialog^ msg = ref new MessageDialog(asyncTask->N.ToString());
msg->ShowAsync();
}

Related

How can I use a QMap to store and look at my data?

I am new to QT started to try out some things with QMap as it seems like a useful tool. I already read some other forum threads but I wasnt able to answer my question. The user is supposed to add and edit different shapes via the GUI. For the shapes I first wrote an abstract base class:
#ifndef BASE_H
#define BASE_H
#include <QListWidget>
#include <QMap>
class Base
{
protected:
QVariantMap m_properties;
QString m_key;
void setKey(const QString& key){
this->m_key=key;
}
public:
Base(){}
virtual ~Base(){}
QString key(){
return m_key;
}
void setProperty(QString key, QVariant variant){
m_properties[key]=variant;
}
virtual void toRTC()=0;
};
#endif // BASE_H
one example of a subclass is an ellipse with the following cpp file:
#include "ellipse.h"
Ellipse::Ellipse(int Start_x, int Start_y, int Rad_x, int Rad_y): rad_x(Rad_x), rad_y(Rad_y), start_x(Start_x), start_y(Start_y)
{
this->setKey("ellipse");
this->setProperty("radX", rad_x);
this->setProperty("radY", rad_y);
this->setProperty("startX", start_x);
this->setProperty("startY", start_y);
}
void Ellipse::set_rad_x(int rad_x)
{
Base::setProperty("radX", rad_x);
}
void Ellipse::set_rad_y(int rad_y)
{
Base::setProperty("radY", rad_y);
}
void Ellipse::set_start_x(int start_x)
{
Base::setProperty("startX", start_x);
}
void Ellipse::set_start_y(int start_y)
{
Base::setProperty("startY", start_y);
}
int Ellipse::get_rad_x()
{
return m_properties["radX"].toInt();
}
int Ellipse::get_rad_y()
{
return m_properties["radY"].toInt();
}
int Ellipse::get_start_x()
{
return m_properties["startX"].toInt();
}
int Ellipse::get_start_y()
{
return m_properties["startY"].toInt();
}
First off, is this a correct approach for the cpp file? I feel my approach is vary laborious.
In my main window file I thought about storing my data in a simple Vector QVector<Base *> data_storage;
Ellipse *e_values = new Ellipse(ui->Ellipse_Value_start_x->value(),ui->Ellipse_Value_start_y->value(), ui->Ellipse_Value_rad_x->value(),ui->Ellipse_Value_rad_y->value());
data_storage.append(e_values);
To load the data, I thought it would be a good idea to use the key to check which object of data_storage I want to load, but I don't really know how I can access the data which is connected to my key.
if(data_storage[t]->key()=="ellipse"){
ui->Ellipse_Value_rad_x->setValue(data_storage[t]->) //how can I access the correct data?
}
I feel like I messed up the entire approach, like how to properly use keys, so how would I do that?
You need to declare all the behaviours you need in the base class. I don't see the need to have Base hold the data.
E.g. if you need to be able to read and write the UI, there should be methods to do that.
class Base
{
public:
virtual ~Base() = default;
virtual void toRTC() = 0;
virtual QVariantMap properties() const = 0;
virtual void writeUI(form_t * ui) const = 0;
virtual void readUI(const form_t * ui) = 0;
};
class Ellipse : public Base
{
int start_x;
int start_y;
int rad_x;
int rad_y;
public:
void toRTC() final { /* ??? */ }
QVariantMap properties() const final {
return { { "radX", rad_x }, { "radY", rad_y },
{ "startX", start_x }, { "startY", start_y } };
}
void writeUI(form_t * ui) const final {
ui->Ellipse_Value_rad_x->setValue(rad_x);
ui->Ellipse_Value_rad_y->setValue(rad_y);
ui->Ellipse_Value_start_x->setValue(start_x);
ui->Ellipse_Value_start_y->setValue(start_y);
}
void readUI(const form_t * ui) final {
rad_x = ui->Ellipse_Value_rad_x->value().toInt();
rad_y = ui->Ellipse_Value_rad_y->value().toInt();
start_x = ui->Ellipse_Value_start_x->value().toInt();
start_y = ui->Ellipse_Value_start_y->value().toInt();
}
};
If you don't want to tie your shapes to the UI, you could define a visitor interface, with a visit method for each shape type.
class ShapeVisitor
{
virtual void accept(Ellipse * ellipse) = 0;
/* virtual void accept(Rectangle * rectangle) = 0; // etc.. */
};
class Base
{
public:
virtual ~Base() = default;
virtual void toRTC() = 0;
virtual QVariantMap properties() const = 0;
virtual void visit(ShapeVisitor & visitor) = 0;
};
class Ellipse : public Base
{
public:
int start_x;
int start_y;
int rad_x;
int rad_y;
void toRTC() final { /* ??? */ }
QVariantMap properties() const final {
return { { "radX", rad_x }, { "radY", rad_y },
{ "startX", start_x }, { "startY", start_y } };
}
void visit(ShapeVisitor & visitor) final {
visitor.accept(this); // calls visitor::accept(Ellipse *)
}
};
class UIReadVisitor : public ShapeVisitor
{
form_t * ui
void accept(Ellipse * ellipse) final {
ellipse->rad_x = ui->Ellipse_Value_rad_x->value().toInt();
ellipse->rad_y = ui->Ellipse_Value_rad_y->value().toInt();
ellipse->start_x = ui->Ellipse_Value_start_x->value().toInt();
ellipse->start_y = ui->Ellipse_Value_start_y->value().toInt();
}
}
class UIWriteVisitor : public ShapeVisitor
{
form_t * ui;
void accept(Ellipse * ellipse) final {
ui->Ellipse_Value_rad_x->setValue(ellipse->rad_x);
ui->Ellipse_Value_rad_y->setValue(ellipse->rad_y);
ui->Ellipse_Value_start_x->setValue(ellipse->start_x);
ui->Ellipse_Value_start_y->setValue(ellipse->start_y);
}
}

how to prevent to creating the duplicate item while scrolling my recyclerview

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++;
}
}
}

Builder design pattern does not work for me

I have a problem with a c++ code I just written. The code is a sample of the Builder design pattern. I created an abstract builder class, and two classes inherited from this class: MonsterBuilder and RuffianBuilder. I created a Builder class, this class receives a Monster or a RuffianBuilder, and constructs a new instance of these classes. The problem comes here: if the MonsterBuilder class is used to build a new instance the program terminates with an error (a.exe has stopped working). If the Builder receives a RuffianBuilder, it constructs a new instance without an error. Here is the sample code:
#include <iostream>
class Character
{
private:
// Attributes
int dex;
int str;
int end;
// skills
int lockpick;
int guns;
int sneak;
/***************************************** Setters ********************************************************/
// Attribute setters
public:
void setStrength(const int &s)
{
this->str = s;
}
void setDexterity(const int &d)
{
this->dex = d;
}
void setEndurance(const int &e)
{
this->str = e;
}
// Skill setters
void setLockpick(const int &s)
{
this->lockpick = s;
}
void setSneak(const int &s)
{
this->sneak = s;
}
void setGuns(const int &s)
{
this->guns = s;
}
int getGuns()
{
return this->guns;
}
int getStrength()
{
return this->str;
}
};
/* Abstract builder */
class CharacterBuilder
{
protected:
Character * int_character;
public:
Character * getCharacter()
{
return int_character;
}
void buildCharacter()
{
int_character = new Character;
}
virtual void buildSkills() = 0;
virtual void buildAttributes() = 0;
};
class MonsterBuilder : public CharacterBuilder
{
public:
virtual void buildSkills()
{
int_character->setLockpick(10);
int_character->setSneak(12);
int_character->setGuns(50);
}
virtual void buildAttributes()
{
int_character->setStrength(5);
int_character->setDexterity(5);
int_character->setEndurance(5);
}
};
class RuffianBuilder : public CharacterBuilder
{
public:
virtual void buildSkills()
{
int_character->setLockpick(10);
int_character->setSneak(12);
int_character->setGuns(50);
}
virtual void buildAttributes()
{
int_character->setStrength(5);
int_character->setDexterity(5);
int_character->setEndurance(5);
}
};
class Builder
{
public:
void setBuilder(CharacterBuilder * builder)
{
this->builder = builder;
}
Character * getCharacter()
{
return builder->getCharacter();
}
void buildCharacter()
{
//std::cout << builder->buildSkills;
builder->buildSkills();
builder->buildAttributes();
}
private:
CharacterBuilder * builder;
};
int main()
{
Builder B;
RuffianBuilder R;
MonsterBuilder Mo;
B.setBuilder(&R);
B.buildCharacter();
std::cout << B.getCharacter()->getGuns();
std::cout << B.getCharacter()->getStrength();
B.setBuilder(&Mo);
B.buildCharacter();
//std::cout << B.getCharacter()->getStrength();
return 0;
}
What causes this problem? Could somebody explain it?
Reading uninitlalized variable will cause undefined behavior.
I added builder->buildCharacter(); to Builder::buildCharacter() and then this code seems working well.
class Builder
{
public:
void setBuilder(CharacterBuilder * builder)
{
this->builder = builder;
}
Character * getCharacter()
{
return builder->getCharacter();
}
void buildCharacter()
{
//std::cout << builder->buildSkills;
builder->buildCharacter(); // add this line
builder->buildSkills();
builder->buildAttributes();
}
private:
CharacterBuilder * builder;
};

List row clicking is not working in the popup screen

I am trying to put a listfield in the pop up screen. The list is coming properly. But when i am clicking a particular row of the list, it is not firing any event. itried with showing a dialog. but it is also not working. Here is my code:
public class AttachmentListPopup extends PopupScreen implements FieldChangeListener{
private ListField _listField;
private Vector _listElements;
public AttachmentListPopup()
{
super(new VerticalFieldManager());
_listElements = new Vector();
_listField = new ListField();
ListCallback _callback = new ListCallback()
{
public boolean navigationClick(int status, int time)
{
int index = _listField.getSelectedIndex();
if(index == 0)
{
Dialog.alert("Grocery Clicked");
}
else if(index == 1)
{
Dialog.alert("To Do's Clicked");
}
return true;
}
};
_listField.setCallback(_callback);
initializeList();
add(_listField);
}
private void initializeList()
{
String itemOne = "Grocery";
String itemTwo = "To Do's";
_listElements.addElement(itemOne);
_listElements.addElement(itemTwo);
_listField.setSize(_listElements.size());
_listField.setRowHeight(Display.getHeight()/6);
}
private class ListCallback implements ListFieldCallback
{
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
y = y +20;
String text = (String)_listElements.elementAt(index);
g.drawText(text, (Display.getWidth() - getFont().getAdvance(text))/2, y, 0 , w);
}
public Object get(ListField list, int index)
{
return _listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return _listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
}
}
It will be great help if you find out the issue..
Thanks.
Have a look at this, this is a good example of ListField implementation, since I am on Mac, I can't run your code. Hope it might help you.
Finally i am able to fix the issue. I am writing the navigation click for the list view. And now it is working properly..
Here is my updated code:
public class AttachmentListPopup extends PopupScreen implements FieldChangeListener{
private ListField _listField;
private Vector _listElements;
public AttachmentListPopup()
{
super(new VerticalFieldManager());
_listElements = new Vector();
_listField = new ListField();
ListCallback _callback = new ListCallback();
_listField.setCallback(_callback);
initializeList();
add(_listField);
}
protected boolean navigationClick(int arg0, int arg1) {
// TODO Auto-generated method stub
int index = _listField.getSelectedIndex();
if(index == 0)
{
UiApplication.getUiApplication().popScreen(this);
Logger.out("AttachmnentList", "first row clicked");
Dialog.alert("Grocery Clicked");
}
else if(index == 1)
{
Dialog.alert("To Do's Clicked");
}
return super.navigationClick(arg0, arg1);
}
private void initializeList()
{
String itemOne = "Grocery";
String itemTwo = "To Do's";
_listElements.addElement(itemOne);
_listElements.addElement(itemTwo);
_listField.setSize(_listElements.size());
_listField.setRowHeight(Display.getHeight()/6);
}
private class ListCallback implements ListFieldCallback
{
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
y = y +20;
String text = (String)_listElements.elementAt(index);
g.drawText(text, (Display.getWidth() - getFont().getAdvance(text))/2, y, 0 , w);
}
public Object get(ListField list, int index)
{
return _listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return _listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
}
}

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)