I'm facing an odd situation here, when I search for an item it returns me what I'm searching for, but it is doing something else too, it is adding 2 empty rows to the listview by each character pressed on the search, if I search for example: "fire" it will add 8 empty rows at the end of my listview, why is this happening?
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class FragmentClientes extends Fragment implements OnQueryTextListener{
private boolean searchCheck;
private List<ClienteModel> clientes = new ArrayList<ClienteModel>();
private ListView lv;
private View rootView;
ProgressBar progressBar;
private LinearLayout footerLinearLayout;
public FragmentActivity activity;
private SearchView searchView;
private String currentQuery = null;
private ClientViewAdapter ad;
private ClientSearchViewAdapter ads;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout._fragment_clientes, container, false);
rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ));
return rootView;
}
public void gerarToast(CharSequence message) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast
.makeText(getActivity(), message, duration);
toast.show();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(Menus.PROCURAR));
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextSubmit(String submit) {
// showResults(submit, 1);
return false;
}
public boolean onQueryTextChange(String change) {
//TODO Auto-generated method stub
if (searchCheck) {
showResults();
try {
clientes = new ArrayList<ClienteModel>();
Repositorio mRepositorio = new Repositorio(getActivity());
List Clientes = mRepositorio.getClientes(change, 15, 1);
clientes = Clientes;
ads = new ClientSearchViewAdapter(getActivity(), this, clientes);
lv.addFooterView(footerLinearLayout);
lv.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
new LoadMoreClientTask(progressBar, FragmentClientes.this, ad, getActivity()).execute(1);
System.out.println("PAGE " + page);
}
});
new LoadMoreClientTask(progressBar, this, ad, getActivity()).execute(1);
lv.setAdapter(ads);
System.out.println("Pesquisa: " + clientes);
}catch (Exception e){
e.printStackTrace();
}
}
return false;
}
});
}
searchView.setQueryHint(this.getString(R.string.search));
((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text))
.setHintTextColor(getResources().getColor(R.color.white));
menu.findItem(Menus.PROCURAR).setVisible(true);
searchCheck = true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case Menus.PROCURAR:
searchCheck = true;
break;
}
return true;
}
private void showResults() {
try {
progressBar = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyle);
LinearLayout.LayoutParams progressBarParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
progressBar.setLayoutParams(progressBarParams);
progressBar.setPadding(6, 6, 6, 6);
footerLinearLayout = new LinearLayout(getActivity());
AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
footerLinearLayout.setGravity(Gravity.CENTER);
footerLinearLayout.setLayoutParams(layoutParams);
footerLinearLayout.addView(progressBar);
lv = (ListView) rootView.findViewById(R.id.listaClientes);
clientes = new ArrayList<ClienteModel>();
ad = new ClientViewAdapter(getActivity(), this, clientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setAdapter(ad);
} catch (Exception e) {
e.printStackTrace();
}
}
LoadMoreTask:
public class LoadMoreClientTask extends AsyncTask<Integer, Void, Boolean> {
private SearchView.OnQueryTextListener activity;
private ClientViewAdapter adapter;
private List<ClienteModel> cliente = new ArrayList<ClienteModel>();
private ProgressBar progressBar;
private Context context;
public LoadMoreClientTask(ProgressBar progressBar, SearchView.OnQueryTextListener activity, ClientViewAdapter adapter, Context context){
this.progressBar = progressBar;
this.activity = activity;
this.adapter = adapter;
this.context = context;
}
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Integer... parameters) {
int npagina = parameters[0];
cliente= new ArrayList<ClienteModel>();
try {
Repositorio mRepositorio = new Repositorio(context);
List listaDeClientes = mRepositorio.getClientes("", 5, npagina);
cliente = listaDeClientes;
System.out.println("pagina " + npagina);
}catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
adapter.setData(cliente);
}
progressBar.setVisibility(View.INVISIBLE);
}
}
getClientes:
public List<ClienteModel> getClientes( String consulta, Integer limit, Integer pagina) throws SQLException {
int offset = pagina * limit - limit;
System.out.println("OFFSET: "+ offset);
List<ClienteModel> listaDeRegistros = new ArrayList<ClienteModel>();
System.out.println("Consulta: "+ consulta);
if(consulta.isEmpty()) {
query = "SELECT * FROM " + tabelaCLIENTES + " WHERE credencial_id = " + mSessao.getString("id_credencial") + " LIMIT " + offset + ", " + limit;
}else {
query = "SELECT * FROM " + tabelaCLIENTES + " WHERE (credencial_id = " + mSessao.getString("id_credencial") + ") AND (nome LIKE '%"+consulta+"%') LIMIT " + offset + ", " + limit;
}
System.out.println(query);
try {
Cursor mCursor = bd.rawQuery(query, null);
if (mCursor.getCount() > 0) {
if (mCursor.moveToFirst()) {
do {
ClienteModel mClienteModel = new ClienteModel();
mClienteModel.setClientes_id(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.CLIENTES_ID)));
mClienteModel.setId_rm(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.ID_RM)));
mClienteModel.setCredencial_id(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.CREDENCIAL_ID)));
mClienteModel.setNome(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.NOME)));
mClienteModel.setTipo(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.TIPO)));
mClienteModel.setInformacao_adicional(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.INFORMACAO_ADICIONAL)));
mClienteModel.set_criado(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._CRIADO)));
mClienteModel.set_modificado(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._MODIFICADO)));
mClienteModel.set_status(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._STATUS)));
listaDeRegistros.add(mClienteModel);
} while (mCursor.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return listaDeRegistros;
}
It's doing this because you keep adding the footerView for the query changes.
lv.addFooterView(footerLinearLayout);
You should add the footerView one time and keep a reference to it in the Activity and then update the view as needed.
Related
I want to fill an ExpandableListView with a custom Adapter. What I found online is having only one child(one TextView) as a child. In my case, I want to make it have multiple child and data filled after a Background task.
Please help me find what I've done wrong or what should I do as the error as I keep on getting
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.HashMap.put(java.lang.Object, java.lang.Object)' on a null object reference
at com.infy.texpetrol.Activity.CreditReportActivity$GetData.onPostExecute
CreditReportActivity
public class CreditReportActivity extends AppCompatActivity {
private static final String TAG = "CreditBillActivity";
private ConnectionClass connectionClass;
private ProgressDialog progressDialog;
private List<String> cListPetrol, cListDIESEL, cListSPEED, cListOIL;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_credit_report);
String empCode = getIntent().getStringExtra("empCode");
String shift = getIntent().getStringExtra("shift");
String date = getIntent().getStringExtra("date");
connectionClass = new ConnectionClass();
expListView = findViewById(R.id.lvExpandable);
GetData getData = new GetData();
getData.execute(empCode);
}
#SuppressLint("StaticFieldLeak")
private class GetData extends AsyncTask {
boolean bPetrolRS = false;
boolean bDesiRS = false;
boolean bSpedRS = false;
boolean bOilRS = false;
#Override
protected Object doInBackground(Object[] objects) {
String empCode = objects[0].toString();
try {
Connection con = connectionClass.CONN();
String queryPetrol, queryDIESEL, queryOIL, querySPEED;
queryDIESEL = "Some SQL QUERY";
queryPetrol = "Some SQL QUERY";
queryOIL = "Some SQL QUERY";
querySPEED = "Some SQL QUERY";
if (con != null) {
Statement statement1 = con.createStatement();
Statement statement2 = con.createStatement();
Statement statement3 = con.createStatement();
Statement statement4 = con.createStatement();
ResultSet rsPetrol = statement1.executeQuery(queryPetrol);
ResultSet rsDIESEL = statement2.executeQuery(queryDIESEL);
ResultSet rsOIL = statement3.executeQuery(queryOIL);
ResultSet rsSPEED = statement4.executeQuery(querySPEED);
listDataHeader = new ArrayList<>();
cListPetrol = new ArrayList<>();
cListDIESEL = new ArrayList<>();
cListSPEED = new ArrayList<>();
cListOIL = new ArrayList<>();
Log.d(TAG, "doInBackground: rsPetrol " + rsPetrol.next());
if (rsPetrol.next()) {
while (rsPetrol.next()) {
bPetrolRS = true;
cListPetrol.add(rsPetrol.getString("PartyName")
+ "#.#" + rsPetrol.getString("QTY")
+ "#.#" + rsPetrol.getString("Amount"));
}
} else {
bPetrolRS = false;
cListPetrol.add("NONE");
}
Log.d(TAG, "doInBackground: rsDIESEL " + rsDIESEL.next());
if (rsDIESEL.next()) {
while (rsDIESEL.next()) {
bDesiRS = true;
cListDIESEL.add(rsDIESEL.getString("PartyName")
+ "#.#" + rsDIESEL.getString("QTY")
+ "#.#" + rsDIESEL.getString("Amount"));
}
} else {
bDesiRS = false;
cListDIESEL.add("NONE");
}
Log.d(TAG, "doInBackground: rsSPEED " + rsSPEED.next());
if (rsSPEED.next()) {
while (rsSPEED.next()) {
bSpedRS = true;
cListSPEED.add(rsSPEED.getString("PartyName")
+ "#.#" + rsSPEED.getString("QTY")
+ "#.#" + rsSPEED.getString("Amount"));
}
} else {
bSpedRS = false;
cListSPEED.add("NONE");
}
Log.d(TAG, "doInBackground: rsOIL " + rsOIL.next());
if (rsOIL.next()) {
while (rsOIL.next()) {
bOilRS = true;
cListOIL.add(rsOIL.getString("PartyName")
+ "#.#" + rsOIL.getString("QTY")
+ "#.#" + rsOIL.getString("Amount"));
}
} else {
bSpedRS = false;
cListOIL.add("NONE");
}
} else {
Log.d(TAG, "doInBackground: Error in Connection");
}
} catch (Exception e) {
bPetrolRS = false;
Log.d(TAG, "doInBackground: CATCH " + e.getMessage());
}
return empCode;
}
#Override
protected void onPostExecute(Object o) {
progressDialog.hide();
if (!o.toString().isEmpty()) {
listDataHeader.add("DIESEL");
listDataHeader.add("PETROL");
listDataHeader.add("SPEED");
listDataHeader.add("OIL");
if (bDesiRS) {
Log.d(TAG, "onPostExecute: cListDIESEL " + cListDIESEL.size() + " listDataHeader.get(0) " + listDataHeader.get(0));
listDataChild.put(listDataHeader.get(0), cListDIESEL);
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN DIESEL", Toast.LENGTH_SHORT).show();
}
if (bPetrolRS) {
Log.d(TAG, "onPostExecute: cListPetrol " + cListPetrol.size() + " listDataHeader.get(1) " + listDataHeader.get(1));
listDataChild.put(listDataHeader.get(1), cListPetrol); //error gets me here
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN PETROL", Toast.LENGTH_SHORT).show();
}
if (bOilRS) {
listDataChild.put(listDataHeader.get(2), cListSPEED);
Log.d(TAG, "onPostExecute: cListSPEED " + cListSPEED.size());
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN SPEED", Toast.LENGTH_SHORT).show();
}
if (bSpedRS) {
listDataChild.put(listDataHeader.get(3), cListOIL);
Log.d(TAG, "onPostExecute: cListOIL " + cListOIL.size());
} else {
Toast.makeText(CreditReportActivity.this, "NO DATA IN OIL", Toast.LENGTH_SHORT).show();
}
listAdapter = new ExpandableListAdapter(CreditReportActivity.this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
} else {
Toast.makeText(CreditReportActivity.this, "No Data", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(CreditReportActivity.this);
progressDialog.setMessage("Getting your Report");
progressDialog.show();
}
}
}
ExpandableListAdapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private String[] split;
public ExpandableListAdapter(Context _context, List<String> _listDataHeader, HashMap<String, List<String>> _listDataChild) {
this._context = _context;
this._listDataHeader = _listDataHeader;
this._listDataChild = _listDataChild;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return Objects.requireNonNull(this._listDataChild.get(this._listDataHeader.get(groupPosition))).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#SuppressLint("InflateParams")
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
stringSplit(childText);
if (convertView == null) {
LayoutInflater Inflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = Inflater.inflate(R.layout.child, null);
}
TextView txtPartyName = convertView.findViewById(R.id.txt_C_partyName);
txtPartyName.setText(split[0]);
TextView product = convertView.findViewById(R.id.txt_C_COUNT);
product.setText(String.valueOf(childPosition));
TextView qty = convertView.findViewById(R.id.txt_C_qty);
qty.setText(split[1]);
TextView amt = convertView.findViewById(R.id.txt_C_amt);
amt.setText(split[2]);
return convertView;
}
private void stringSplit(String childText) {
split = childText.split("#.#");
}
#Override
public int getChildrenCount(int groupPosition) {
return Objects.requireNonNull(this._listDataChild.get(this._listDataHeader.get(groupPosition)))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#SuppressLint("InflateParams")
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.header, null);
}
TextView lblListHeader = convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
You forgot to initialize listDataChild
HashMap<String, List<String>> listDataChild = new HashMap<>();
I implemented the displaying contacts with checkboxes. When I selected the multiple contacts and click the button it shows this error "
Attempt to invoke virtual method 'boolean
java.lang.Boolean.booleanValue()' on a null object reference"
. at mCustomAdapter.mCheckedStates.get(i). So i wrote like this in adapter class is "
mCheckedStates = new LongSparseArray<>(ContactList.size())
And again it shows the same error after assigning some value. When I print the size of the mCustomAdapter.mCheckedStates.size it show the correct value of how many contacts I selected but when getting the value it shows the error. How to solve that?
This is My adapter class :
public class Splitadapter extends BaseAdapter implements Filterable,CompoundButton.OnCheckedChangeListener
{
// public SparseBooleanArray mCheckStates;
LongSparseArray<Boolean> mCheckedStates = new LongSparseArray<>();
private ArrayList<COntactsModel> ContactList;
private Context mContext;
private LayoutInflater inflater;
private ValueFilter valueFilter;
ArrayList<COntactsModel> ContactListCopy ;
public Splitadapter(Context context, ArrayList<COntactsModel> ContactList) {
super();
mContext = context;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.ContactList = ContactList;
this.ContactListCopy = this.ContactList;
mCheckedStates = new LongSparseArray<>(ContactList.size());
System.out.println("asdfghjk" + mCheckedStates);
getFilter();
}//End of CustomAdapter constructor
#Override
public int getCount() {
return ContactListCopy.size();
}
#Override
public Object getItem(int position) {
return ContactListCopy.get(position).getName();
}
#Override
public long getItemId(int position) {
return ContactListCopy.get(position).getId();
}
public class ViewHolder {
TextView textviewName;
TextView textviewNumber;
CheckBox checkbox;
Button b;
int id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
//
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.list, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.name);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.mobile);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
holder.b = convertView.findViewById(R.id.round_icon);
convertView.setTag(holder);
}//End of if condition
else {
holder = (ViewHolder) convertView.getTag();
}//End of else
COntactsModel c = ContactListCopy.get(position);
holder.textviewName.setText(c.getName());
holder.textviewNumber.setText(c.getPhonenum());
holder.checkbox.setTag(c.getId());
holder.checkbox.setChecked(mCheckedStates.get(c.getId(), false));
holder.checkbox.setOnCheckedChangeListener(this);
holder.b.setText(c.getName().substring(0,1));
//holder.id = position;
return convertView;
// }//End of getView method
}
boolean isChecked(long id) {// it returns the checked contacts
return mCheckedStates.get(id, false);
}
void setChecked(long id, boolean isChecked) { //set checkbox postions if it sis checked
mCheckedStates.put(id, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
void toggle(long id) {
setChecked(id, !isChecked(id));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mCheckedStates.put((Long) buttonView.getTag(), true);
} else {
mCheckedStates.delete((Long) buttonView.getTag());
}
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<COntactsModel> filterList = new ArrayList<COntactsModel>();
for (int i = 0; i < ContactList.size(); i++) {
COntactsModel ca = ContactList.get(i);
if ((ca.getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
//COntactsModel contacts = new COntactsModel();
filterList.add(ca);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = ContactList.size();
results.values = ContactList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
ContactListCopy = (ArrayList<COntactsModel>) results.values;
notifyDataSetChanged();
}
}
}
This my Main Activity :
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
public static String TAG = "amount";
ListView mainListView;
ProgressDialog pd;
public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
final static List<String> name1 = new ArrayList<>();
List<String> phno1 = new ArrayList<>();
List<Long> bal = new ArrayList<>();
List<Bitmap> img = new ArrayList<>();
private Splitadapter mCustomAdapter;
private ArrayList<COntactsModel> _Contacts = new ArrayList<COntactsModel>();
HashSet<String> names = new HashSet<>();
Set<String>phonenumbers = new HashSet<>();
Button select;
int amount=100;
float result;
String ph;
String phoneNumber;
EditText search;
String contactID;
String name;
// private FirebaseAuth mAuth;
// FirebaseUser firebaseUser;
//
// FirebaseFirestore db = FirebaseFirestore.getInstance();
#SuppressLint("StaticFieldLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Split");
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = findViewById(R.id.search_bar);
final List<String> phonenumber = new ArrayList<>();
System.out.print(phonenumber);
mainListView = findViewById(R.id.listview);
showContacts();
select = findViewById(R.id.button1);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user chan ged the Text
mCustomAdapter.getFilter().filter(cs.toString());
//
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
//ma.filter(text);
}
});
select.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
ArrayList checkedcontacts1 = new ArrayList();
ArrayList names = new ArrayList();
System.out.println(".............." + (mCustomAdapter.mCheckedStates.size()));
System.out.println("name size is" + name1.size());
int a = mCustomAdapter.mCheckedStates.size();
result = ((float) amount / a);
System.out.println("final1 amount is " + result);
long result1 = (long) result;
System.out.println("final amount is " + result1);
for (int k = 0; k < a; k++) {
bal.add(result1);
}
System.out.println("balance" + bal);
System.out.println("selected contacts split amount" + result);
System.out.println("names" + name1.size());
// int as = name1.size();
// mCustomAdapter.mCheckedStates = new LongSparseArray<>(as);
System.out.println("cjgygytygh" + mCustomAdapter.mCheckedStates);
for (int i = 0; i < name1.size(); i++) // it displays selected contacts with amount
{
System.out.println("checked contcts" + mCustomAdapter.mCheckedStates.get(i));
if (mCustomAdapter.mCheckedStates.get(i)) {
checkedcontacts.append(phno1.get(i)).append("\t").append("\t").append("\t").append(result1);
checkedcontacts1.add((phno1.get(i)));
names.add((name1.get(i)));
checkedcontacts.append("\n");
System.out.println("checked contacts:" + "\t" + phno1.get(i) + "\t" + "amount" + "\t" + result1);
}
}
System.out.println("checked names" + names);
System.out.println(
"checkec contcts foggfgfgfgfgf" + checkedcontacts1
);
List<Object> list = new ArrayList<>();
for (Object i : checkedcontacts1) {
list.add(i);
}
System.out.println("checked contacts size is" + checkedcontacts1.size());
HashMap<String, HashMap<String, Object>> Invites = new HashMap<>();
for (int i = 0; i < checkedcontacts1.size(); i++) {
HashMap<String, Object> entry = new HashMap<>();
entry.put("PhoneNumber", list.get(i));
entry.put("Name", names.get(i));
System.out.println("entry is" + entry);
for (int j = i; j <= i; j++) {
System.out.println("phonenumber" + i + ":" + list.get(i));
System.out.println("amount" + j + ":" + bal.get(j));
//dataToSave.put("phonenumber" +i, list.get(i));
entry.put("Amount", bal.get(j));
}
Invites.put("Invite" + i, entry);
}
Intent intent = new Intent(MainActivity.this, Display.class);
intent.putExtra("selected", checkedcontacts1.toString().split(","));
startActivity(intent);
}
});
}
private void showContacts() // it is for to check the build versions of android . if build version is >23 or above it is set the permissions at the run time . if the build version is less than 23 the we give the permissions at manifest file .
{if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
}
else {
mCustomAdapter = new Splitadapter(MainActivity.this,_Contacts);
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
mainListView.setAdapter(mCustomAdapter);
mainListView.setOnItemClickListener(this);
mainListView.setItemsCanFocus(false);
mainListView.setTextFilterEnabled(true);
getAllContacts();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, // it is display the request access permission dilogue box to access the contacts of user.
#NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
}
}
}
private void getAllContacts() {
// it displays the contact phonenumber and name rom the phone book. and add to the list.
ContentResolver cr = getContentResolver();
String[] PROJECTION = new String[] {
ContactsContract.RawContacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_URI,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String filter = ""+ ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and " + ContactsContract.CommonDataKinds.Phone.TYPE +"=" + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
String order = ContactsContract.Contacts.DISPLAY_NAME + " ASC";
Cursor phones = cr.query(uri, PROJECTION, filter, null, order);
while (phones.moveToNext()) {
long id = phones.getLong(phones.getColumnIndex(ContactsContract.Data._ID));
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
_Contacts.add(new COntactsModel(id,name,phoneNumber));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
mCustomAdapter.toggle(arg3);
}
This my Model Class :
public class COntactsModel
{
String phonenum;
long id;
String cname;
boolean selected = false;
public COntactsModel(long id, String name,String phonenumber) {
this.id = id;
this.cname = name;
this.phonenum = phonenumber;
}
public long getId() {
return this.id;
}
public String getName() {
return this.cname;
}
public String getPhonenum() {
return this.phonenum;
}
}
How to solve that error?
I'm new to Java and Android and am trying to figure out how to write a ListView and load the ListView from where it is saved.
I have ListView and each item on the ListView has a string and bool that changes if a checkbox for the item is checked or unchecked. I have a working method to add items to the ListView and am now trying to figure out how to write the ListView to a textfile.
I got some code for saving the ListView by clicking a menu item and them I'm trying to load it when I re-run the program in my OnCreate, but nothing is loading. I'm not sure if its the write or load that is not working or both.
Here is a class I made that works with my ListView.
Item.java
public class Item {
String name;
boolean isChecked = false;
public Item(String name) {this.name = name;}
public Item(String name, boolean checked){
this.name = name;
this.isChecked = checked;
}
#Override
public String toString(){
return name;
}
}
Here is my MainActivity.java that includes my saveList() and readFile()
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
ArrayList<Item> items = new ArrayList<>();
private ListView lv;
private static final String sFile = "Saved.txt";
protected ListView getListView() {
if (lv == null) {
lv = (ListView) findViewById(android.R.id.list);
}
return lv;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
private void deleteList()
{
if (!items.isEmpty())
{
items.clear();
}
lv.invalidateViews();
}
private void deleteCheckedItems()
{
SparseBooleanArray checked = lv.getCheckedItemPositions();
for(int i = 0; i < lv.getCount(); i++)
{
if (checked.get(i)==true)
{
items.remove(i);
}
lv.invalidateViews();
}
lv.clearChoices();
}
private void saveList(ArrayList<Item> itemlist) {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(sFile, 0));
int iCnt = 0;
String allstring = "";
for (Item s : items)
{
if (s.isChecked)
{
iCnt++;
if (iCnt < items.size()) {
String thisstring;
thisstring = s.name + "\r\n";
out.write(thisstring);
allstring += thisstring;
} else {
String thisstring;
thisstring = s.name;
out.write(thisstring);
allstring += thisstring;
}
}
}
out.close();
//Toast.makeText(activity, allstring + " Written", duration).show();
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activity, "Write Exception : " + ex.getMessage(), duration).show();
}
}
public String readFile(ArrayList<Item> itemsList)
{
String sRet = "Nothing";
try
{
InputStream is = openFileInput(sFile);
if (is != null)
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String sLine;
StringBuffer sb = new StringBuffer();
while ((sLine = br.readLine()) != null)
sb.append(sLine + "\r\n");
is.close();
sRet = sb.toString();
// Toast.makeText(Toast.LENGTH_LONG).show();
}
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activi"Read Exception" + ex.getMessage(), Toast.LENGTH_LONG).show();
}
return sRet;
}
private void addItemDialog()
{
LayoutInflater inflater = LayoutInflater.from(this);
final View addView = inflater.inflate(R.layout.add, null);
new AlertDialog.Builder(this)
.setTitle("Add Item")
.setView(addView)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText txtAdd = (EditText) addView.findViewById(R.id.etInput);
String sItem = (txtAdd).getText().toString();
items.add(new Item(sItem));
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_multiple_choice, items));
lv = this.getListView();
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
readFile(items);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.add_item:
addItemDialog();
return true;
case R.id.clear_all:
deleteList();
return true;
case R.id.clear_checked:
deleteCheckedItems();
return true;
case R.id.write:
saveList(items);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
put your oncreate method above after declaration that means after this line
private static final String sFile = "Saved.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.......
.......
//your code
}
//other method
Read Android activity lifecyle for better understanding
i have some problem with my JSON code.
I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please master help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for HomeFragment.java (where i doing the JSON).
public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {
private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;
public HomeFragment() {
}
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
try {
mCallbacks = (CategorySelectionCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
if (UtilMethods.isConnectedToInternet(getActivity())) {
initCategoryList();
} else {
internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener,
getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), CATEGORY_ACTION);
}
}
public class getCategList extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
/**
* json is populating from text file. To make api call use ApiHandler class
*
* <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
* <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done. Do the parsing as the following.
*/
URL hp = null;
try {
hp = new URL(
getString(R.string.liveurl) + "foodcategory.php");
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("UR1L", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
categoryList = new ArrayList<Category>();
for (int i = 0; i < j.length(); i++) {
Category category = new Category();// buat variabel category
JSONObject Obj;
Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
category.setId(Obj.getString(JF_ID));
category.setTitle(Obj.getString(JF_TITLE));
category.setIconUrl(Obj.getString(JF_ICON));
if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
}
Log.d("URL1",""+Obj.getString(JF_TITLE));
categoryList.add(category);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
}
});
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
Error = e.getMessage();
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
Error = e.getMessage();
}
return null;
}
}
//! function for populate category list
private void initCategoryList() {
new getCategList().execute();
}
#Override
public void onConnectionEstablished(int code) {
if (code == CATEGORY_ACTION) {
initCategoryList();
}
}
#Override
public void onUserCanceled(int code) {
if (code == CATEGORY_ACTION) {
getActivity().finish();
}
}
//! catch json response from here
#Override
public void onSuccessResponse(String tag, String jsonString) {
//! do same parsing as done in initCategoryList()
}
//! detect response error here
#Override
public void onFailureResponse(String tag) {
}
//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
void onCategorySelected(String catID, String title);
}
}
This code for categoryAdapter.java (where i put the result of JSON to the list)
public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {
private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;
public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
super(activity, R.layout.layout_category_list);
this.activity = activity;
this.inflater = LayoutInflater.from(activity.getApplicationContext());
this.categoryList = categoryList;
this.mCallbacks = mCallbacks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder row;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_category_list, null);
row = new ViewHolder();
row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);
} else {
row = (ViewHolder) convertView.getTag();
}
Category category = categoryList.get(position);
Picasso.with(activity).load(UtilMethods
.getDrawableFromFileName(activity,category.getIconUrl()))
.tag(category.getIconUrl())
.into(row.categoryImage);
row.categoryName.setText(category.getTitle());
Picasso.with(activity)
.load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
.placeholder(R.drawable.img_banner_placeholder)
.tag(category.getIconUrl())
.fit()
.into(row.bannerImage);
row.bannerImage.setOnClickListener(this);
row.categoryImage.setTag(position);
row.categoryName.setTag(position);
row.bannerImage.setTag(position);
return convertView;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public void onClick(View v) {
int position = Integer.parseInt(v.getTag().toString());
mCallbacks.onCategorySelected(categoryList.get(position).getId(),
categoryList.get(position).getTitle());
}
private static class ViewHolder {
public ImageView bannerImage;
public TextView categoryName;
public ImageView categoryImage;
}
}
Try this.
Picasso.with(activity).load(category.getIconUrl())
.into(row.categoryImage);
If it worked !. You Check the UtilMethods.getDrawableFromFileName() !!!
i am adding data to list view it shows multiple Times .
I have two Activities.first activity i have add button and listview . when i click add button i goes to second activity.in second activity,adding data to ArrayList.here i am passing arraylist object to first Activity using parcelable .
in first activity,here i am storing the getting ArrayList object values in one Arraylist<>.and then passing object to listview. in listview data showing in multipule times .please go though this link https://www.codota.com/codebox/#/9lqy1ardnfyctyb9/shared
please, sorry i am not good in english.
public class MainActivity extends ActionBarActivity {
ImageView addView, searchView;
DetailsEmp detailsEmp = new DetailsEmp();
ListView listView;
ArrayList<Employee> listDetails=new ArrayList<Employee>();
DetailsAdapter detailsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Employee emp = (Employee) getIntent().getParcelableExtra(detailsEmp.PAR_KEY);
listView = (ListView) findViewById(R.id.listView);
addView = (ImageView) findViewById(R.id.addImage);
addView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), DetailsEmp.class);
startActivity(i);
}
});
if (emp != null) {
Employee emplyoee=new Employee();
{
emplyoee.setName(emp.getName());
listDetails.add(emplyoee);
emplyoee.setCmpny(emp.getCmpny());
listDetails.add(emplyoee);
emplyoee.setDisig(emp.getDisig());
listDetails.add(emplyoee);
emplyoee.setListAge(emp.getListAge());
listDetails.add(emplyoee);
emplyoee.setListGen(emp.getListGen());
listDetails.add(emplyoee);
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
Log.d("bundle Size is ", "Emp Name is " + emp.getName());
Log.d("bundle Size is ", "Emp Sex is " + emp.getListGen());
Log.d("list Size is ", " ArrayList<Emplyoee> " + listDetails.size());
for (int i = 0; i < listDetails.size(); i++) {
Log.d("list Size is ", " ArrayList<Emplyoee> "
+ listDetails.get(i).getName().toString());
}
}
detailsAdapter=new DetailsAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, listDetails);
listView.setAdapter(detailsAdapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
// second activity
public class DetailsAdapter extends ArrayAdapter<Employee> {
private Context context;
private ArrayList<Employee> listDetails;
public DetailsAdapter(Context context, int resource,
ArrayList<Employee> listDetails) {
super(context, resource, listDetails);
// TODO Auto-generated constructor stub
this.context = context;
this.listDetails = listDetails;
}
private class ViewHolder
{
TextView empName,empCmpny,empDisig,empAge,empExp ;
ImageView empIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder=null;
Employee emplyoee=getItem(position);
LayoutInflater inflator=(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView == null)
{
convertView =inflator.inflate(R.layout.activity_listview, parent, false);
holder=new ViewHolder();
holder.empName=(TextView)convertView.findViewById(R.id.listName);
holder.empCmpny=(TextView)convertView.findViewById(R.id.listCmpny);
holder.empDisig=(TextView)convertView.findViewById(R.id.listDesignation);
holder.empIcon=(ImageView)convertView.findViewById(R.id.female);
convertView.setTag(holder);
}
holder=(ViewHolder)convertView.getTag();
for (int j = 0; j < listDetails.size(); j++) {
holder.empName.setText(emplyoee.getName());
holder.empCmpny.setText(emplyoee.getCmpny());
holder.empDisig.setText(emplyoee.getDisig());
if (emplyoee.getListGen().toString() == "Male") {
holder.empIcon.setImageResource(R.drawable.client_male_dark);
}
}
return convertView;
}
}
// POJO class
public class Employee implements Parcelable {
String listName = null;
String listCmpny = null;
String listDisig = null;
String listExp = null;
String listAge = null;
String listGen = null;
public String getName() {
return listName;
}
public String getListExp() {
return listExp;
}
public void setListExp(String listExp) {
this.listExp = listExp;
}
public String getListAge() {
return listAge;
}
public void setListAge(String listAge) {
this.listAge = listAge;
}
public String getListGen() {
return listGen;
}
public void setListGen(String listGen) {
this.listGen = listGen;
}
public void setName(String listName) {
this.listName = listName;
}
public String getCmpny() {
return listCmpny;
}
public void setCmpny(String listCmpny) {
this.listCmpny = listCmpny;
}
public String getDisig() {
return listDisig;
}
public void setDisig(String listDisig) {
this.listDisig = listDisig;
}
public static final Parcelable.Creator CREATOR = new Creator() {
#Override
public Employee createFromParcel(Parcel source) {
Employee emp = new Employee();
emp.listName = source.readString();
emp.listCmpny = source.readString();
emp.listDisig = source.readString();
emp.listAge = source.readString();
emp.listGen = source.readString();
emp.listExp = source.readString();
return emp;
}
public Employee[] newArray(int size) {
return new Employee[size];
}
};
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(listName);
dest.writeString(listCmpny);
dest.writeString(listDisig);
dest.writeString(listAge);
dest.writeString(listGen);
dest.writeString(listExp);
}
}
// DetailsEmp
public class DetailsEmp extends Activity {
public final static String PAR_KEY="key_par";
private EditText empName, empCmpny, empDisig, empAge, empExp;
private RadioGroup empGender;
private RadioButton empMale, empFemale;
Button save;
ArrayList<Employee> list = new ArrayList<Employee>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_emp);
// getting the details from the xml
empName = (EditText) findViewById(R.id.editName);
empCmpny = (EditText) findViewById(R.id.editCmpny);
empDisig = (EditText) findViewById(R.id.editDisignation);
empAge = (EditText) findViewById(R.id.editAge);
empExp = (EditText) findViewById(R.id.editExp);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
empGenderDetails();
}
});
}
protected void empGenderDetails() {
// TODO Auto-generated method stub
// empMale = (RadioButton) findViewById(R.id.male);
Employee emp = new Employee();
emp.setName(empName.getText().toString());
//list.add(emp);
emp.setCmpny(empCmpny.getText().toString());
//list.add(emp);
emp.setDisig(empDisig.getText().toString());
//list.add(emp);
emp.setListAge(empAge.getText().toString());
//list.add(emp);
emp.setListExp(empExp.getText().toString());
//list.add(emp);
empFemale = (RadioButton) findViewById(R.id.female);
empGender = (RadioGroup) findViewById(R.id.radioGroup);
int sel = empGender.getCheckedRadioButtonId();
empMale = (RadioButton) findViewById(sel);
emp.setListGen(empMale.getText().toString());
Log.d("Employee data ", " Emp " + emp.listName.toString()
+ empMale.getText().toString()
+ empExp.getText().toString());
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
Bundle b=new Bundle();
b.putParcelable(PAR_KEY , emp);
i.putExtras(b);
//setResult(RESULT_OK, i);
startActivity(i);
finish();
//list.add(emp);
Log.d("Emplyooe Size ","Emplyoee " + emp.getName());
/*
}
emplyoee.setName(emp.getName());
listDetails.add(emplyoee);
emplyoee.setCmpny(emp.getCmpny());
listDetails.add(emplyoee);
emplyoee.setDisig(emp.getDisig());
listDetails.add(emplyoee);
emplyoee.setListAge(emp.getListAge());
listDetails.add(emplyoee);
emplyoee.setListGen(emp.getListGen());
listDetails.add(emplyoee);
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
you keep adding a new emplyoee (mispelled btw, but that's up to you), you need to do
emplyoee.setName(emp.getName());
emplyoee.setCmpny(emp.getCmpny());
emplyoee.setDisig(emp.getDisig());
emplyoee.setListAge(emp.getListAge());
emplyoee.setListGen(emp.getListGen());
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
or:
addView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
emplyoee.setName(emp.getName());
emplyoee.setCmpny(emp.getCmpny());
emplyoee.setDisig(emp.getDisig());
emplyoee.setListAge(emp.getListAge());
emplyoee.setListGen(emp.getListGen());
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
Intent i = new Intent(getApplicationContext(), DetailsEmp.class);
startActivity(i);
}
});
Your way of using Adapter is quite a immature one. Please On click of the save button add your "emp" object to the ArrayList and don't recreate the adapter once again when your dataset is changed just notify it the data has changed. Have a method as given below in your adapter rather then having the data supply in the constructor.
public void setData(ArrayList<Employee> _listOfEmp){
this.listOfEmp = _listOfEmp;
}
and then notify the adapter in your activity when ever you change the dataset.
For your clarity.
Read this:
http://developer.android.com/reference/android/widget/ArrayAdapter.html
and see this example:
http://www.vogella.com/tutorials/AndroidListView/article.html