我正在学习以编程方式添加视图。但是,我现在很困惑。我有数据,有idpatient,idheader。患者可以有多个 ID 标头。当我输入 idpatient 时,它将以编程方式添加 listview(带有自定义适配器)。listview 的数量与 ID header 的数量相同。
我想通过 ID 标题在每个列表视图中设置数据患者组。到目前为止,我在循环添加列表视图时添加了搜索视图,但是当我在 seacrh 视图中输入一个 ID 标题时,所有列表视图都会根据 ID 查看相同的数据搜索视图中的标题..
对于冗长的解释,我很抱歉。有人可以帮我解决这个问题吗?提前致谢
这是我的适配器:
/**
* Created by RKI on 11/9/2016.
*/
public class AdapterHistory extends BaseAdapter implements Filterable, View.OnClickListener {
private Activity activity;
LayoutInflater inflater;
HistoryHeaderActivity main;
public int count = 0;
Context context;
public ModelHistory product;
ArrayList<ModelHistory> mStringFilterList;
ModelHistory tempValues = null;
ValueFilter valueFilter;
public Cart cart;
public AdapterHistory(HistoryHeaderActivity main, ArrayList<ModelHistory> arraylist) {
this.main = main;
this.main.historyModel = arraylist;
mStringFilterList = arraylist;
}
@Override
public int getCount() {
return main.historyModel.size();
}
@Override
public Object getItem(int position) {
return main.historyModel.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
int pos = position;
final Cart carts = CartHelper.getCart();
View vi = convertView;
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_history, null);
holder.h_id = (TextView) vi.findViewById(R.id.id_header_);
holder.h_type = (TextView) vi.findViewById(R.id.servicetype_);
holder.h_qty = (TextView) vi.findViewById(R.id.qty_);
holder.h_ps_id = (TextView) vi.findViewById(R.id.patient_id);
holder.h_ps_name = (TextView) vi.findViewById(R.id.patient_);
holder.h_dokid = (TextView) vi.findViewById(R.id.doctor_id_);
holder.h_dokname = (TextView) vi.findViewById(R.id.doctor_);
holder.h_item = (TextView) vi.findViewById(R.id.item_);
holder.h_date = (TextView) vi.findViewById(R.id.date_);
holder.checkToCart = (CheckBox) vi.findViewById(R.id.checkBox);
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
tempValues.setSelected(isChecked);
}
});
vi.setTag(holder);
vi.setTag(R.id.checkBox, holder.checkToCart);
} else {
holder = (ViewHolderItem) vi.getTag();
}
if (main.historyModel.size() <= 0) {
holder.h_date.setText("No Data");
} else {
/*** Get each Model object from Arraylist ****/
tempValues = null;
tempValues = (ModelHistory) main.historyModel.get(position);
holder.h_id.setText(tempValues.getH_id());
holder.h_type.setText(tempValues.getH_service());
holder.h_qty.setText(tempValues.getH_qty());
holder.h_ps_name.setText(tempValues.getH_p_name());
holder.h_ps_id.setText(tempValues.getH_p_id());
holder.h_dokid.setText(tempValues.getH_d_id());
holder.h_dokname.setText(tempValues.getH_d_name());
holder.h_item.setText(tempValues.getH_item());
holder.h_date.setText(tempValues.getH_date());
holder.checkToCart.setTag(position);
holder.checkToCart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
main.historyModel.get(position).setSelected(buttonView.isChecked());
}
});
holder.checkToCart.setChecked(main.historyModel.get(position).isSelected());
for (pos = 1; pos <= 1; pos++) {
main.u_pname = tempValues.getH_p_name();
main.u_pid = tempValues.getH_p_id();
main.u_service = tempValues.getH_service();
main.up_iddetail = tempValues.getH_id();
}
}
return vi;
}
@Override
public void onClick(View v) {
}
public static class ViewHolderItem {
TextView h_id, h_type, h_ps_id, h_ps_name, h_dokid, h_dokname, h_item, h_qty, h_date;
CheckBox checkToCart;
}
private List<TransactionsItem> getCartItems(Cart cart) {
List<TransactionsItem> cartItems = new ArrayList<>();
Map<Saleable, Integer> itemMap = cart.getItemWithQuantity();
for (Map.Entry<Saleable, Integer> entry : itemMap.entrySet()) {
TransactionsItem cartItem = new TransactionsItem();
cartItem.setProduct((ModelInventory) entry.getKey());
cartItem.setQuantity(entry.getValue());
cartItems.add(cartItem);
}
return cartItems;
}
@Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<ModelHistory> filterList = new ArrayList<ModelHistory>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getH_id().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ModelHistory country = new ModelHistory(
mStringFilterList.get(i).getH_id(),
mStringFilterList.get(i).getH_p_id(),
mStringFilterList.get(i).getH_date(),
mStringFilterList.get(i).getH_p_name(),
mStringFilterList.get(i).getH_d_id(),
mStringFilterList.get(i).getH_d_name(),
mStringFilterList.get(i).getH_item(),
mStringFilterList.get(i).getH_qty(),
mStringFilterList.get(i).getH_service());
filterList.add(country);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
main.historyModel = (ArrayList<ModelHistory>) results.values;
notifyDataSetChanged();
}
}
}
这是我的活动:
import com.mobileproject.rki.mobile_his_receipt.view.adapter.AdapterHistory;
import org.w3c.dom.*;
import java.io.Serializable;
import java.util.*;
public class HistoryHeaderActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
static final String URL = "http://.../GetDataInv";
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_REG_ID = "Sales_Aptk_ID", KEY_DATE = "Sales_Aptk_Date",
KEY_PATIENT_ID = "Sales_Aptk_Patient_ID", KEY_SERVICE_ID = "Sales_Aptk_Type",
KEY_PATIENT_NAME = "Sales_Aptk_Patient_Name",
KEY_DOCTOR_ID = "Sales_Aptk_Doctor_ID", KEY_DOCTOR_NAME = "Sales_Aptk_Doctor_Name",
KEY_ITEM_ID = "Sales_Aptk_Detail_Item_ID", KEY_DETAIL_UNIT = "Sales_Aptk_Detail_Unit",
KEY_ITEM_QTY = "Sales_Aptk_Detail_Qty";
static final String KEY_ID_HEADER = "Sales_Aptk_ID";
static final String KEY_TABLE_INV = "Table"; // parent node
static final String KEY_ITEM_ID_INV = "Item_ID", KEY_ITEM_NAME = "Item_Name",
KEY_MAX_STOCK = "Item_Max_Stock";
public static final int DIALOG_DOWNLOAD_DATA_PROGRESS = 0, DIALOG_NO_DATA = 1,
DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 2;
Element e;
final Context context = this;
public List<ModelInventory> invModels;
private ProgressDialog mProgressDialog;
public static String id, up_iddetail, up_user, u_pid, u_pname, u_service, xml;
public ArrayList<ModelInventory> invModel = new ArrayList<ModelInventory>();
public ArrayList<ModelHistory> historyModel = new ArrayList<ModelHistory>();
public ArrayList<ModelIDHeader> headerModel = new ArrayList<ModelIDHeader>();
public Cart cart;
private Menu menu;
AdapterHistory hstAdpt, idhstAdpt;
private ProgressDialog progressDialog;
public ModelInventory productInv;
int mPosition, invPosition;
EditText p_id;
ListView listHistory;
XMLParser parser;
LinearLayout lm;
LinearLayout.LayoutParams params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_header);
lm = (LinearLayout) findViewById(R.id.linearMain);
params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
p_id = (EditText) findViewById(R.id.patientID);
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mPosition = position;
invPosition = position;
}
});
SharedPreferences login2 = getSharedPreferences("USERLOGIN", 0);
String doktername = login2.getString("userlogin", "0");
up_user = doktername;
p_id.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
onGetHistory();
}
});
}
/**
* Check Form Input
*
* @return
*/
private boolean isFormValid() {
String aTemp = p_id.getText().toString();
if (aTemp.isEmpty()) {
Toast.makeText(this, "Please Input Patient ID..", Toast.LENGTH_SHORT).show();
return false;
} else {
id = aTemp.toString();
}
return true;
}
protected void dismissDialogWait() {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
public void onGetHistory() {
listHistory.setAdapter(null);
if (isFormValid()) {
GetDataHistoryTask syncTask = new GetDataHistoryTask();
syncTask.execute(new IntroductingMethod());
GetDataHeaderTask syncTaskHeader = new GetDataHeaderTask();
syncTaskHeader.execute(new IntroductingMethod());
}
}
private class GetDataHistoryTask extends AsyncTask<IntroductingMethod, String, String> {
@Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryData(id);
}
@Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelHistory add = new ModelHistory();
add.setH_id(parser.getValue(e, KEY_REG_ID));
add.setH_p_name(parser.getValue(e, KEY_PATIENT_NAME));
add.setH_p_id(parser.getValue(e, KEY_PATIENT_ID));
add.setH_service(parser.getValue(e, KEY_SERVICE_ID));
add.setH_date(parser.getValue(e, KEY_DATE));
add.setH_detail_unit(parser.getValue(e, KEY_DETAIL_UNIT));
add.setH_d_id(parser.getValue(e, KEY_DOCTOR_ID));
add.setH_d_name(parser.getValue(e, KEY_DOCTOR_NAME));
add.setH_item(parser.getValue(e, KEY_ITEM_ID));
add.setH_qty(parser.getValue(e, KEY_ITEM_QTY));
historyModel.add(add);
}
ShowAllContentHistory();
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
private class GetDataHeaderTask extends AsyncTask<IntroductingMethod, String, String> {
@Override
protected String doInBackground(IntroductingMethod... params) {
IntroductingMethod REGService = params[0];
return REGService.getHistoryHeaderData(id);
}
@Override
protected void onPostExecute(String result) {
dismissDialogWait();
if (result != null) {
try {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
ModelIDHeader add = new ModelIDHeader();
add.setIdSalesHeader(parser.getValue(e, KEY_ID_HEADER));
headerModel.add(add);
}
if(result.contains("<Sales_Aptk_Patient_ID>"+id+"</Sales_Aptk_Patient_ID>")){
Log.d("NilaiID ", id);
AddNewList();
}
else{
Log.d("Kenapayahh", id);
}
} catch (Exception e) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Koneksi gagal. Silahkan coba kembali.", Toast.LENGTH_LONG).show();
}
}
}
public void AskUpdate(View v) {
if (hstAdpt.getCount() == 0) {
Toast.makeText(HistoryHeaderActivity.this.getApplicationContext(),
"Tidak ada rekaman pasien.", Toast.LENGTH_LONG).show();
} else {
SharedPreferences id_header = getSharedPreferences("IDSALESAPTK", 0);
SharedPreferences.Editor editorID = id_header.edit();
editorID.putString("idsalesaptk", up_iddetail);
editorID.commit();
SharedPreferences sendPref2 = getSharedPreferences("DATAPATIENTNAME", 0);
SharedPreferences.Editor editor2 = sendPref2.edit();
editor2.putString("datapatientname", u_pname);
editor2.commit();
editor2.clear();
SharedPreferences sendPref3 = getSharedPreferences("DATAPATIENTID", 0);
SharedPreferences.Editor editor3 = sendPref3.edit();
editor3.putString("datapatientid", u_pid);
editor3.commit();
editor3.clear();
SharedPreferences regID = getSharedPreferences("DATAREGID", 0);
String reg_ID = regID.getString("dataregid", "0");
SharedPreferences sendPref4 = getSharedPreferences("DATAREGID", 0);
SharedPreferences.Editor editor4 = sendPref4.edit();
editor4.putString("dataregid", reg_ID);
editor4.commit();
editor4.clear();
SharedPreferences sendPref1 = getSharedPreferences("DATASERVICE", 0);
SharedPreferences.Editor editor1 = sendPref1.edit();
editor1.putString("dataservice", u_service);
editor1.commit();
editor1.clear();
new LoadingDataAsync().execute();
}
}
public class LoadingDataAsync extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
updateDetail();
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_DATA_PROGRESS);
}
}
public void updateDetail() {
ArrayList<ModelHistory> candidateModelArrayList = new ArrayList<ModelHistory>();
for (ModelHistory model : historyModel) {
if (model.isSelected()) {
candidateModelArrayList.add(model);
}
}
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_TABLE_INV);
for (int i = 0; i < nl.getLength(); i++) {
e = (Element) nl.item(i);
ModelInventory add = new ModelInventory();
add.setItem_ID(parser.getValue(e, KEY_ITEM_ID_INV));
add.setItem_Name(parser.getValue(e, KEY_ITEM_NAME));
add.setItem_Max_Stock(parser.getValue(e, KEY_MAX_STOCK));
invModel.add(add);
}
invModels = new ArrayList<ModelInventory>();
invModels = invModel;
ArrayAdapter<ModelInventory> adptInv = new ArrayAdapter<ModelInventory>(context, android.R.layout.simple_spinner_dropdown_item, invModels);
ArrayAdapter<ModelHistory> adptChkItem = new ArrayAdapter<ModelHistory>(context, android.R.layout.simple_spinner_dropdown_item, candidateModelArrayList);
if (adptInv.isEmpty()) {
Toast.makeText(HistoryHeaderActivity.this, "Empty Patient", Toast.LENGTH_SHORT).show();
}
cart = CartHelper.getCart();
for (mPosition = 0; mPosition < adptChkItem.getCount(); mPosition++) {
ModelHistory historyItem = (ModelHistory) adptChkItem.getItem(mPosition);
for (int j = mPosition; j < adptInv.getCount(); j++) {
ModelInventory inventoryItem = (ModelInventory) adptInv.getItem(j);
if (candidateModelArrayList.get(mPosition).getH_item().equals(inventoryItem.getItem_ID())) {
if (cart.getProducts().toString().contains(inventoryItem.getItem_Name())) {
} else {
productInv = (ModelInventory) (Serializable) adptInv.getItem(j);
int qty = Integer.parseInt(historyItem.getH_qty());
cart.add(productInv, qty);
}
} else {
}
}
}
Intent i = new Intent(getBaseContext(), CartActivity.class);
i.putExtra("PersonID", "try");
startActivity(i);
}
@Override
protected Dialog onCreateDialog(int id) {
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
hstAdpt.getFilter().filter(newText);
idhstAdpt.getFilter().filter(newText);
return false;
}
public void AddNewList(){
ArrayAdapter<ModelIDHeader> adptIDHeader = new ArrayAdapter<ModelIDHeader>(context, android.R.layout.simple_spinner_dropdown_item, headerModel);
for(int count =0; count< adptIDHeader.getCount(); count++){
idhstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
ModelIDHeader idHeader = (ModelIDHeader) adptIDHeader.getItem(count);
Button btn = new Button(this);
btn.setId(count);
btn.setText(idHeader.getIdSalesHeader());
lm.addView(btn);
SearchView search = new SearchView(this);
search.setQuery(idHeader.getIdSalesHeader(), false);
search.setOnQueryTextListener(this);
lm.addView(search);
ListView tv = new ListView(this);
tv.setId(count);
tv.setLayoutParams(params);
tv.setDividerHeight(2);
tv.setAdapter(idhstAdpt);
lm.addView(tv);
}
}
public void ShowAllContentHistory() {
listHistory = (ListView) findViewById(R.id.listhistory);
hstAdpt = new AdapterHistory(HistoryHeaderActivity.this, historyModel);
listHistory.setAdapter(hstAdpt);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_history_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ClearPrefs();
logout();
Intent intent = new Intent(HistoryHeaderActivity.this, LoginActivity.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
}
if (id == R.id.action_home) {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
Intent intent = new Intent(HistoryHeaderActivity.this, MainActivity.class);
startActivity(intent);
}
public void ClearPrefs() {
}
public void logout() {
SharedPreferences preferences5 = getSharedPreferences("IDLOGIN", Context.MODE_PRIVATE);
SharedPreferences.Editor editor5 = preferences5.edit();
editor5.clear();
editor5.commit();
}
}