In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.
Related
I am getting the data from server using JSON and when i try to search in the listview it just refreshes the whole list and does not narrate it, but when i debug i can see the result on getfilter is right right and it drugsFiltered = (ArrayList<drugs_json_data>) results.values; does have the filtered data inside it. just the listview.setadaptor is being done inside onPostExecute of the asynctask.
here is my adapter code:
public class drugs_adaptor_listView extends ArrayAdapter<drugs_json_data> implements Filterable {
ArrayList<drugs_json_data> drugs;
ArrayList<drugs_json_data> drugsFiltered;
Context context;
int resource;
public drugs_adaptor_listView(Context context, int resource, ArrayList<drugs_json_data> drugs) {
super(context, resource, drugs);
this.drugs = drugs;
this.drugsFiltered = drugs;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View r = convertView;
ViewHolder viewHolder;
if (r == null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
r = layoutInflater.inflate(R.layout.row_layout_drugs, null, true);
viewHolder = new ViewHolder(r);
r.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) r.getTag();
}
drugs_json_data drugs_json_data = getItem(position);
viewHolder.txtDrugId.setText(drugs_json_data.getDrugId());
viewHolder.txtDrugName.setText(drugs_json_data.getDrugName());
viewHolder.txtDrugCategory.setText(drugs_json_data.getDrugCategory());
Picasso builder = new Picasso.Builder(context).build();
builder.load(drugs_json_data.getDrugImage()).memoryPolicy(MemoryPolicy.NO_STORE).placeholder(R.drawable.ic_launcher_foreground).into(viewHolder.imageView);
return r;
}
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
drugsFiltered = (ArrayList<drugs_json_data>) results.values; // has the filtered values
if (results.count>0) {
notifyDataSetChanged(); // notifies the data with new filtered values
}else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<drugs_json_data> FilteredArrList = new ArrayList<>();
if (drugs == null) {
drugs = new ArrayList<>(drugsFiltered); // saves the original data in mOriginalValues
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = drugs.size();
results.values = drugs;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < drugs.size(); i++) {
String data = drugs.get(i).getDrugName();
if (data.startsWith(constraint.toString())) {
FilteredArrList.add(new drugs_json_data(drugs.get(i).getDrugId(), drugs.get(i).getDrugName(), drugs.get(i).getDrugCategory(), drugs.get(i).getDrugImage()));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
class ViewHolder {
TextView txtDrugId, txtDrugName, txtDrugCategory;
ImageView imageView;
ViewHolder(View v) {
txtDrugId = v.findViewById(R.id.txtDrugId);
txtDrugName = v.findViewById(R.id.txtDrugName);
txtDrugCategory = v.findViewById(R.id.txtDrugCat);
imageView = v.findViewById(R.id.ImageViewDrug);
}
}
}
here is the data model:
public class drugs_json_data {
private String drugImage;
private String drugName;
private String drugCategory;
private String drugId;
public drugs_json_data(String drugImage, String drugName, String drugCategory, String drugId) {
this.drugImage = drugImage;
this.drugName = drugName;
this.drugCategory = drugCategory;
this.drugId = drugId;
}
public String getDrugImage() {
return this.drugImage;
}
public void setDrugImage(String drugImage) {
this.drugImage = drugImage;
}
public String getDrugName() {
return this.drugName;
}
public void setDrugName(String drugName) {
this.drugName = drugName;
}
public String getDrugCategory() {
return this.drugCategory;
}
public void setDrugCategory(String drugCategory) {
this.drugCategory = drugCategory;
}
public String getDrugId() {
return this.drugId;
}
public void setDrugId(String drugId) {
this.drugId = drugId;
}
}
and here is the main activity code:
public class clerk_drugs extends AppCompatActivity {
ListView listView;
Button createDrug;
String drug_id, json_drug;
TextView noMed;
EditText searchTxt;
JSONObject jsonObject;
JSONArray jsonArray;
ArrayList<drugs_json_data> arrayList;
drugs_adaptor_listView adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clerk_drugs);
createDrug = findViewById(R.id.create_drug);
arrayList = new ArrayList<>();
listView = findViewById(R.id.list_drugs);
noMed = findViewById(R.id.no_med);
searchTxt = findViewById(R.id.listSearch);
searchTxt.setSingleLine(true);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
new ReadJSON().execute("http://(mylink)").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
try {
jsonObject = new JSONObject(json_drug);
jsonArray = jsonObject.getJSONArray("server_response");
} catch (JSONException e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
drug_id = ((TextView) view.findViewById(R.id.txtDrugId)).getText().toString();
for (int i = 0; i<jsonArray.length(); i++){
try {
JSONObject jobj = jsonArray.getJSONObject(i);
String drugid = jobj.getString("drug_id");
if(drugid.equals(drug_id)) {
String drugname = jobj.getString("drug_name");
String drugcategory = jobj.getString("drug_category");
String drugdescription = jobj.getString("drug_description");
String drugphoto = jobj.getString("drug_photo");
drug_update_dialog drug_update_dialog = new drug_update_dialog();
Bundle args = new Bundle();
args.putString("drug-id", drug_id);
args.putString("drug-name", drugname);
args.putString("drug-category", drugcategory);
args.putString("drug-description", drugdescription);
args.putString("drug_photo",drugphoto);
drug_update_dialog.setArguments(args);
drug_update_dialog.show(getSupportFragmentManager(),"ویرایش اطلاعات دارو");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
searchTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
searchTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
hideKeyboard(v);
}
}
});
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
class ReadJSON extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
for(int i=0; i<jsonArray.length();i++){
JSONObject drugObj = jsonArray.getJSONObject(i);
arrayList.add(new drugs_json_data(
drugObj.getString("drug_photo"),
drugObj.getString("drug_name"),
drugObj.getString("drug_category"),
drugObj.getString("drug_id")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new drugs_adaptor_listView(
getApplicationContext(), R.layout.row_layout_drugs, arrayList
);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
if (adapter.getCount()==0){
noMed.setVisibility(View.VISIBLE);
}
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try{
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line=bufferedReader.readLine())!=null){
content.append(line).append("\n");
}
bufferedReader.close();
}catch (Exception e){
e.printStackTrace();
}
json_drug = content.toString();
return content.toString();
}
#Override
public void onBackPressed() {
finish();
Intent intent = new Intent(this,patient_mainPage.class);
startActivity(intent);
}
public void createDrugDialog(View view){
openDrugDialog();
}
private void openDrugDialog() {
drug_add_dialog drug_add_dialog = new drug_add_dialog();
drug_add_dialog.show(getSupportFragmentManager(),"ثبت داروی جدید");
}
}
I would be grateful if someone could help.
UPDATED
In getView method in Adapter
Replace
drugs_json_data drugs_json_data = getItem(position);
With
drugs_json_data drugs_json_data = drugsFiltered.get(position);
I have a listview in which in each row I have a checkbox along with details o persons. Now on clicking checkboxes, I want to store the id of those persons in arrayList which I am able to store but the arrayList id in adapter. I want to access the arrayList in activity because I want to take a button in activity on clicking which I want to send ids of all the selected persons to another activity. How do I do that.
My code is below:
SendWorkList.java
public class SendWorkList extends AppCompatActivity {
List<SendWorkRow> send_work_array_list;
ListView send_work_list;
JSONArray send_work_jsonArray1,send_work_result_jsonArray2;
JSONObject send_work_jsonObject1,send_work_result_jsonArray2_i;
String[] send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
String send_work_status,send_work_result;
ViewGroup send_work_headerView;
Set<Integer> send_work_count;
Intent intent;
Set<String> indexes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_work);
send_work_list=findViewById( R.id.send_work_list);
send_work_array_list=new ArrayList<SendWorkRow>();
send_work_count= new HashSet<>();
}
#Override
protected void onResume() {
super.onResume();
cardDetailsList();
/* send_work_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SendWorkList.this, "assasa", Toast.LENGTH_SHORT).show();
}
});*/
}
private void cardDetailsList()
{
RequestQueue rq = Volley.newRequestQueue(SendWorkList.this);
StringRequest stringRequest = new StringRequest( Request.Method.GET,
"http://grepthorsoftware.in/tst/bank_account/showingdata.php",
new Response.Listener<String>() {
public void onResponse(String response) {
try {
send_work_jsonArray1=new JSONArray(response);
send_work_jsonObject1 = send_work_jsonArray1.getJSONObject(0);
send_work_status= send_work_jsonObject1.getString("status");
if(send_work_status.equals("1")) {
send_work_result = send_work_jsonObject1.getString("result");
send_work_result_jsonArray2 = new JSONArray(send_work_result);
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
if ( send_work_name.length > 0 || send_work_id.length > 0 || send_work_bankaccount.length > 0 || send_work_ifsc.length > 0 || send_work_contacts.length > 0)
{
send_work_id = null;
send_work_name = null;
send_work_bankaccount = null;
send_work_ifsc = null;
send_work_contacts = null;
send_work_department= null;
send_work_cardnumber= null;
send_work_cardexpiry= null;
send_work_cardcvv= null;
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
}
for(int i=0;i<send_work_result_jsonArray2.length();i++)
{
send_work_result_jsonArray2_i=send_work_result_jsonArray2.getJSONObject(i);
send_work_id[i] = send_work_result_jsonArray2_i.getString("id");
send_work_name[i] = send_work_result_jsonArray2_i.getString("Name");
send_work_bankaccount[i] = send_work_result_jsonArray2_i.getString("Bankaccount");
send_work_ifsc[i] = send_work_result_jsonArray2_i.getString("IFSC");
send_work_contacts[i] = send_work_result_jsonArray2_i.getString("Contact");
send_work_department[i] = send_work_result_jsonArray2_i.getString("Department");
send_work_cardnumber[i] = send_work_result_jsonArray2_i.getString("Cardnumber");
send_work_cardexpiry[i] = send_work_result_jsonArray2_i.getString("Cardexpiry");
send_work_cardcvv[i] = send_work_result_jsonArray2_i.getString("Cardcvv");
}
if ( send_work_array_list.size() > 0) {
send_work_array_list.clear();
}
for (int i = 0; i < send_work_id.length && i< send_work_name.length && i < send_work_bankaccount.length && i < send_work_ifsc.length && i < send_work_contacts.length && i < send_work_department.length && i< send_work_cardnumber.length && i< send_work_cardexpiry.length && i< send_work_cardcvv.length; i++) {
send_work_array_list.add(new SendWorkRow( send_work_id[i], send_work_name[i], send_work_bankaccount[i], send_work_ifsc[i], send_work_contacts[i], send_work_department[i], send_work_cardnumber[i], send_work_cardexpiry[i],send_work_cardcvv[i]));
}
if ( send_work_headerView != null) {
send_work_list.removeHeaderView( send_work_headerView);
}
send_work_headerView = (ViewGroup) getLayoutInflater().inflate(R.layout.send_work_list_view_header, send_work_list, false);
send_work_list.addHeaderView( send_work_headerView);
send_work_list.setAdapter(new SendWorkAdapter(SendWorkList.this, send_work_array_list));
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
rq.add(stringRequest);
}
}
SendWorkAdapter.java
public class SendWorkAdapter extends BaseAdapter {
Context context;
List<SendWorkRow> send_work_array_list;
Set<String> indexes;
public SendWorkAdapter(Context context, List<SendWorkRow> send_work_array_list)
{
this.context=context;
this.send_work_array_list=send_work_array_list;
indexes = new HashSet<String>();
}
#Override
public int getCount() {
return send_work_array_list.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater= (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view=inflater.inflate( R.layout.send_work_list_view_row,viewGroup,false);
CheckBox textView1=view.findViewById( R.id.send_work_checkbox_row);
TextView textView2=view.findViewById( R.id.send_work_name_row );
TextView textView3=view.findViewById( R.id.send_work_bank_account_row );
TextView textView4=view.findViewById( R.id.send_work_ifsc_row );
TextView textView5=view.findViewById( R.id.send_work_contact_number_row );
TextView textView6=view.findViewById( R.id.send_work_department_row );
TextView textView7=view.findViewById( R.id.send_work_card_number_row );
TextView textView8=view.findViewById( R.id.send_work_expiry_date_row );
TextView textView9=view.findViewById( R.id.send_work_cvv_row );
final SendWorkRow account_details_row=send_work_array_list.get( position );
textView2.setText( account_details_row.getSendWorkCardDetailsName() );
textView3.setText( account_details_row.getSendWorkCardDetailsBankAccount() );
textView4.setText( account_details_row.getSendWorkCardDetailsIfsc());
textView5.setText( account_details_row.getSendWorkCardDetailsContacts() );
textView6.setText( account_details_row.getSendWorkCardDetailsDepartment() );
textView7.setText( account_details_row.getSendWorkCardDetailsCardNumber() );
textView8.setText( account_details_row.getSendWorkCardDetailsCardExpiry() );
textView9.setText( account_details_row.getSendWorkCardDetailsCardCvv() );
textView1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()){
Toast.makeText(context, account_details_row.getSendWorkCardDetailsId(), Toast.LENGTH_SHORT).show();
indexes.add(account_details_row.getSendWorkCardDetailsId());
}
}
});
return view;
}
}
SendWorkRow.java
public class SendWorkRow {
private String send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
public SendWorkRow(String send_work_id, String send_work_name, String send_work_bankaccount, String send_work_ifsc, String send_work_contacts,String send_work_department,String send_work_cardnumber,String send_work_cardexpiry,String send_work_cardcvv) {
this.send_work_id = send_work_id;
this.send_work_name = send_work_name;
this.send_work_bankaccount = send_work_bankaccount;
this.send_work_ifsc = send_work_ifsc;
this.send_work_contacts = send_work_contacts;
this.send_work_department = send_work_department;
this.send_work_cardnumber = send_work_cardnumber;
this.send_work_cardexpiry = send_work_cardexpiry;
this.send_work_cardcvv = send_work_cardcvv;
}
//Getters
public String getSendWorkCardDetailsId() {
return send_work_id;
}
public String getSendWorkCardDetailsName() {
return send_work_name;
}
public String getSendWorkCardDetailsBankAccount() {
return send_work_bankaccount;
}
public String getSendWorkCardDetailsIfsc() {
return send_work_ifsc;
}
public String getSendWorkCardDetailsContacts() {
return send_work_contacts;
}
public String getSendWorkCardDetailsDepartment() {
return send_work_department;
}
public String getSendWorkCardDetailsCardNumber() {
return send_work_cardnumber;
}
public String getSendWorkCardDetailsCardExpiry() {
return send_work_cardexpiry;
}
public String getSendWorkCardDetailsCardCvv() {
return send_work_cardcvv;
}
}
Create one method in adapter like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllWorkRows() {
return send_work_array_list;
}
}
and access this method using adapter instance in activity.
Another way is you can write a method in Adapter where you will find all selected ids in a List and return. So whenever you will require list of selected ids, call this method from Activity and do your task. like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllSelectedWorkRows() {
// write your logic to find selected rows
return result;
}
}
I am creating an application with a list that list cards based on the value from the server.
I created a StudentCardArrayAdapter to achieve this and everything works fine. All the data has been populated in card list. also I able to get the values on button click in each card separately.
What I need is on clicking the button it will call a method requestion server for data asynchronously and get a value from the server and according to that value, i need to change the button text in that particular card.
My StudentCardArrayAdapter code:
public class StudentCardArrayAdapter extends ArrayAdapter<StudentCard> {
private static final String TAG = "CardArrayAdapter";
private List<StudentCard> cardList = new ArrayList<StudentCard>();
private Context mContext;
String selected = "0";
PreferenceHelper prefs;
CardViewHolder viewHolder;
View row;
ProgressDialog pd;
static class CardViewHolder {
TextView studentname;
TextView stop;
Button selectbutton;
CircleImageView imageId;
}
public StudentCardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.mContext = context;
prefs = new PreferenceHelper(this.mContext);
pd = new ProgressDialog(this.mContext);
}
#Override
public void add(StudentCard object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public StudentCard getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.student_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.studentname = (TextView) row.findViewById(R.id.studentname);
viewHolder.stop = (TextView) row.findViewById(R.id.stop);
viewHolder.selectbutton = (Button) row.findViewById(R.id.selectbutton);
viewHolder.imageId = (CircleImageView) row.findViewById(R.id.imageId);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
StudentCard card = getItem(position);
viewHolder.studentname.setText(card.getStudName());
viewHolder.studentname.setTextColor(Color.parseColor("#000000"));
viewHolder.stop.setText(card.getStudStop());
viewHolder.stop.setTextColor(Color.parseColor("#000000"));
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
else{
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.select));
viewHolder.selectbutton.setEnabled(true);
}
final String studid = card.getStudId();
final String busname = prefs.getString("busname", "0");
final String schoolid = prefs.getString("schoolid", "");
viewHolder.selectbutton.setOnClickListener(new View.OnClickListener()
{
String updatedvalue = "0";
#Override
public void onClick(View v)
{
Log.e("studid",studid);
Log.e("busname",busname);
Log.e("schoolid",schoolid);
selectstudent(v, studid, busname, schoolid,mContext);
//Toast.makeText(v.getContext(), amountinfo, Toast.LENGTH_SHORT).show();
/*SnackbarManager.show(Snackbar.with(this) // context
.text(amountinfo));*/
}
});
Picasso.with(mContext).load(card.getImageUrl()).fit().error(R.mipmap.ic_launcher).into(viewHolder.imageId);
return row;
}
public void selectstudent(final View v, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
}
I used the below code but nothing works.. No error also.. and not change in button text.I get value of selected as 1 from server.
if(selected.equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
I am new to android.. and is stuck here. Please help me out.
FINALLY IT WORKED
As changes mention by Krish, I updated the code suggested by him.
And added this changes in onClick it worked
if(card.getSelected().equals("1")){
viewHolder.selectbutton.setText(mContext.getResources().getString(R.string.selected));
viewHolder.selectbutton.setEnabled(false);
}
Change the code like this,
public void selectstudent(StudentCard card, String studid, String busname, String schoolid, final Context mContext) {
String returnedselected = "0";
Log.e("BASE_URL_STUDENT_UPDATE", Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid);
RestClientHelper.getInstance().get(Constants.BASE_URL_STUDENT_UPDATE + "?studid=" + studid+"&busname="+busname+"&schoolid="+schoolid, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
Log.e("RESULT", response);
try {
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("status");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String status = post.optString("status");
if (status.equals("true")) {
selected = post.optString("selected");
} else {
selected = post.optString("selected");
String error = post.optString("error");
SnackbarManager.show(Snackbar.with(getContext()) // context
.text(error));
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
if(selected.equals("1")){
card.setSelected("1");
notifyDataSetChanged();
}
}
}
#Override
public void onError(String error) {
Log.e("error", error);
selected = "0";
}
});
}
and change this line like this ,
final StudentCard card = getItem(position);
and call method inside onclick.
selectstudent(card, studid, busname, schoolid,mContext);
I've this adapter class :
public class NoteFeedListAdapter extends RecyclerView.Adapter<feedItemsHolder>{
private Activity activity;
private LayoutInflater inflater;
private List<NoteFeedItem> feedItems;
private List<CommentModel> commentItems;
private NoteCommentListAdapter adapter;
private RecyclerView mRecyclerView;
ImageLoader imageLoader = NoteAppController.getInstance().getImageLoader();
private static final String URL_LIST_VIEW_COMMENT = "http://url.com";
private int level = 0;
private Context mContext;
public NoteFeedListAdapter(Context context, List<NoteFeedItem> feedItems) {
this.feedItems = feedItems;
this.mContext = context;
}
public feedItemsHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.feed_item, null);
feedItemsHolder mh = new feedItemsHolder(v);
return mh;
}
public void onBindViewHolder(final feedItemsHolder fItemsHolder, final int i) {
final NoteFeedItem item = feedItems.get(i);
fItemsHolder.setLevel(item.getLevel());
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
and Inside onBindViewHolder :
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this code is what I used to call asyntask but result from asynctask cannot be shown in this adapter
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView = new RecyclerView(mContext);
getListViewComments(item.getUserid(), item.getId(),fItemsHolder,i, commentItems, adapter, mRecyclerView);
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView.setAdapter(adapter);
}
});
}
...
} else {
fItemsHolder.mHiddenComment.setVisibility(View.GONE);
fItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
}
if(item.getLevel() == Level.LEVEL_ONE){
level = Level.LEVEL_TWO;
}else if(item.getLevel() == Level.LEVEL_TWO){
level = Level.LEVEL_THREE;
}
}
public int getItemCount() {
return (null != feedItems ? feedItems.size() : 0);
}
private void getListViewComments(final String userid, String id_note,final feedItemsHolder feedItemsHolder, int i, final List<CommentModel> commentItems, final NoteCommentListAdapter adapter, final RecyclerView mRecyclerView) {
class ambilComment extends AsyncTask<String, Void, String> {
ProgressDialog loading;
com.android.personal.asynctask.profileSaveDescription profileSaveDescription = new profileSaveDescription();
String result = "";
InputStream inputStream = null;
#Override
protected void onPreExecute() {
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLoading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("userid", params[0]);
data.put("id_note", params[1]);
String result = profileSaveDescription.sendPostRequest(URL_LIST_VIEW_COMMENT,data);
return result;
}
protected void onPostExecute(String s) {
JSONArray dataJsonArr = null;
if(s.equals(null)){
Toast.makeText(mContext, "Internet Problem.", Toast.LENGTH_SHORT).show();
}else{
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
Toast.makeText(mContext, id_note, Toast.LENGTH_SHORT).show();
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String id_comment = c.getString("id_comment");
String uid = c.getString("userid");
String profile_name = c.getString("profile_name");
String profile_photo = c.getString("profile_photo");
String amount_of_like = c.getString("amount_of_like");
String amount_of_dislike = c.getString("amount_of_dislike");
String amount_of_comment = c.getString("amount_of_comment");
String content_comment = c.getString("content_comment");
String tgl_comment = c.getString("tgl_comment");
String parent_id = c.getString("parent_id");
CommentModel citem = new CommentModel();
citem.setId_note(id_note);
citem.setId_comment(id_comment);
citem.setUserid(uid);
citem.setProfileName(profile_name);
String pPhoto = c.isNull("profile_photo") ? null : c.getString("profile_photo");
citem.setProfile_photo(pPhoto);
citem.setJumlahLove(amount_of_like);
citem.setJumlahNix(amount_of_dislike);
citem.setJumlahComment(amount_of_comment);
citem.setContent_comment(content_comment);
citem.setTimeStamp(tgl_comment);
String prntID = c.isNull("parent_id") ? null : c.getString("parent_id");
citem.setParent_id(prntID);
citem.setLevel(level);
commentItems.add(citem);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
The problem is that I wanna add data from Asynctask and shown on another adapter. But how can i do that? please help. view from another adapter couldn't show with this code.
This is simple Android project that I did. I get no warnings or errors while running. But the ListView doesn't get populated. I don't understand what's going wrong.
Since I dont' understand where is the exact problem and copy-pasting all the code won't help, here is my project code repository: https://bitbucket.org/geejo/msk-v2
Any kind of help will be appreciated
MSKFragment.java
public class MSKFragment extends android.support.v4.app.Fragment implements android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>
{
private ServiceAdapter mServiceAdapter;
public static final int SERVICE_LOADER = 0;
private static final String[] SERVICE_COLUMNS =
{
ServiceContract.ServiceEntry.TABLE_NAME,
ServiceContract.ServiceEntry._ID,
ServiceContract.ServiceEntry.COLUMN_NAME,
ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME,
ServiceContract.ServiceEntry.COLUMN_PRICE
};
public static final int COL_ID = 0;
public static final int COL_NAME = 1;
public static final int COL_ORG_NAME = 2;
public static final int COL_PRICE = 3;
public MSKFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getLoaderManager().initLoader(SERVICE_LOADER, null, this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.menu_fragment_msk, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_refresh)
{
//Moving functions to a helper class, so that when Activity starts the data can be displayed
updateServices();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mServiceAdapter = new ServiceAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_msk, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listViewMainService);
listView.setAdapter(mServiceAdapter);
return rootView;
}
#Override
public void onStart()
{
super.onStart();
//Refresh called and service updated when activity starts
updateServices();
}
//Calling FetchServiceTask and executing it.
private void updateServices()
{
FetchServicesTask serviceTask = new FetchServicesTask(getActivity());
serviceTask.execute();
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int i, Bundle args)
{
Uri serviceUri = ServiceContract.ServiceEntry.buildServiceUri(i);
return new android.support.v4.content.CursorLoader(getActivity(), serviceUri, null, null, null, null);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data)
{
mServiceAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader)
{
mServiceAdapter.swapCursor(null);
}
}
FetchServices.java (AsyncTasks)
public class FetchServicesTask extends AsyncTask<String, Void, Void>
{
private final String LOG_TAG = FetchServicesTask.class.getSimpleName();
private final Context mContext;
private boolean DEBUG = true;
public FetchServicesTask(Context context )
{
mContext = context;
}
private String[] getServicesDatafromJson(String serviceJsonStr) throws JSONException
{
final String MSK_NAME = "name";
final String MSK_PRICE = "price";
final String MSK_ORG_NAME = "organizationName";
final String MSK_POSTED_USER = "postedUser";
final String MSK_PROFILE = "profile";
int totalResults = 25;
String resultStrs[] = new String[totalResults];
try
{
JSONArray serviceArray = new JSONArray(serviceJsonStr);
Vector<ContentValues> cVVector = new Vector<ContentValues>(serviceArray.length());
for(int i=0;i<serviceArray.length();i++)
{
String name, organizationName;
int price;
JSONObject serviceObject = serviceArray.getJSONObject(i);
name = serviceObject.getString(MSK_NAME);
price = serviceObject.getInt(MSK_PRICE);
JSONObject postedUserObject = serviceObject.getJSONObject(MSK_POSTED_USER);
JSONObject profileObject = postedUserObject.getJSONObject(MSK_PROFILE);
organizationName = profileObject.getString(MSK_ORG_NAME);
ContentValues serviceValues = new ContentValues();
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_NAME, name);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME, organizationName);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_PRICE, price);
cVVector.add(serviceValues);
}
int inserted = 0;
if(cVVector.size()>0)
{
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = mContext.getContentResolver().bulkInsert(ServiceContract.ServiceEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "FetchServicesTask Complete. " + inserted + " Inserted");
}
catch(JSONException e)
{
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/////////////////////////////// NETWORKING BOILER PLATE ///////////////////////////
#Override
protected Void doInBackground(String... params)
{
if (params.length == 0)
{
return null;
}
HttpURLConnection urlConnection = null; //Streaming data using HTTP
String serviceJsonStr = null; //raw JSON response
BufferedReader reader = null; //read text from character i/p stream
int pageNo = 1;
int numResults = 5;
try
{
//-------------------------CONNECTION--------------------//
final String SERVICE_BASE_URL = "http://myservicekart.com/public/";
final String SEARCH_BASE_URL = "http://myservicekart.com/public/search?";
final String SEARCH_PARAM = "search";
final String PAGE_PARAM = "pageno";
/*Using a helper class UriBuilder for building and manipulating URI references*/
Uri builtServiceUri = Uri.parse(SERVICE_BASE_URL);
Uri builtSearchUri = Uri.parse(SEARCH_BASE_URL).buildUpon().
appendQueryParameter(SEARCH_PARAM, "").
appendQueryParameter(PAGE_PARAM, Integer.toString(pageNo)).
build();
URL searchUrl = new URL(builtSearchUri.toString());
Log.v(LOG_TAG, "Built SearchUri" +builtSearchUri.toString());
urlConnection = (HttpURLConnection) searchUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//------------------------BUFFERING---------------------//
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream==null)
{
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if(buffer.length()==0)
{
return null;
}
serviceJsonStr = buffer.toString();
getServicesDatafromJson(serviceJsonStr);
Log.v(LOG_TAG, "Services JSON String: " +serviceJsonStr);
}
catch(IOException e)
{
Log.e(LOG_TAG, "Error cannot connect to URL", e);
return null;
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{
if(urlConnection!=null)
{
urlConnection.disconnect();
}
if(reader!=null)
{
try
{
reader.close();
}
catch (final IOException e)
{
Log.e(LOG_TAG,"Error closing stream",e);
}
}
}
return null;
}
}
ServiceAdapter.java
public class ServiceAdapter extends CursorAdapter
{
public ServiceAdapter(Context context, Cursor c, int flags)
{
super(context, c, flags);
}
private String convertCursorRowToUXFormat(Cursor cursor)
{
return cursor.getString(MSKFragment.COL_NAME) + "-" + cursor.getString(MSKFragment.COL_ORG_NAME) +
" - " + cursor.getInt(MSKFragment.COL_PRICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
View view = LayoutInflater.from(context).inflate(R.layout.list_item_main, parent, false);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView tv = (TextView)view;
tv.setText(convertCursorRowToUXFormat(cursor));
}
}
change the method newView() in ServiceAdapter.java to :
public View newView(Context context, Cursor cursor, ViewGroup parent){
View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
return view;}