I created an ListView which is filled by SQLite Database.
In my App you can add books to a database and you can view the booklist in the BookDataListActivity
Now I would like to implement a SearchView to filter the books. I used this Video https://www.youtube.com/watch?v=c9yC8XGaSv4&list=PLfBjz1j1UV9kdwpvU1YGsjKoNxOtoKTCs&index=1
But it doesnt work.
Following my code. Hopefully you can help me.
package com.kasutwentyseven.gui4selfshelf.Books;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.kasutwentyseven.gui4selfshelf.R;
public class BookDataListActivity extends Activity {
public ListView booklistView;
public SearchView searchView;
public SQLiteDatabase sqLiteDatabaseBooks;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView)findViewById(R.id.book_list_view);
searchView = (SearchView) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(),R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
bookListDataAdapter.getFilter().filter(text);
return false;
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if(cursor2.moveToFirst())
{
do{
String booktitle, bookauthor,bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
}while(cursor2.moveToNext());
}
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " is selected", Toast.LENGTH_LONG).show();
}
});
}
}
How do I implement a Filter?
EDIT: As asked the BookListAdapter
package com.kasutwentyseven.gui4selfshelf.Books;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.TextView;
import com.kasutwentyseven.gui4selfshelf.R;
import java.util.ArrayList;
import java.util.List;
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
}
Related
I implemented ExpandableListView using this example, the only 2 diff from my code and example code is: I implemented on dialog box instead of activity and 2nd diff is my data is coming from SQLite.
So, I successfully implemented ExpandableListView and data is coming on perfect position according to group/child pos also. There is no issue in the code.
Now, later I implemented search functionality in the same ExpandableListAdapter.
Problem: Suppose, I want to search Electricity, (which is twice in my case also "E" is matching in more than one time) So, when I search "E", it shows me a list of matches with "E" and that is good, but when I do the second letter "L" it crashes on getChild method and tells me that index is "1" and size is "1" I know it should be 2, but I don't know how is it possible? Because the same getChild method works when it shows me the ExpandableList!!
I tried to debug also, that main Group size is coming right for the first time, but later it remains zero (0).
See:
Code:
Dialog Class:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tekitsolutions.remindme.Adapter.CustomSpinnerAdapter;
import com.tekitsolutions.remindme.Adapter.CustomSpinnerClass;
import com.tekitsolutions.remindme.Adapter.DialogListAdapter;
import com.tekitsolutions.remindme.Adapter.ExpandableCategoryAdapter;
import com.tekitsolutions.remindme.Interface.CategoryListener;
import com.tekitsolutions.remindme.Interface.HamburgerMenuListener;
import com.tekitsolutions.remindme.Interface.ResultListener;
import com.tekitsolutions.remindme.Model.CategoryHeader;
import com.tekitsolutions.remindme.Model.CategoryResponse;
import com.tekitsolutions.remindme.Model.CustomCategory;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ProvidersInfo;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.Context.MODE_PRIVATE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.CUSTOM_CATEGORY_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.PROVIDER_CATEGORY_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.PROVIDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_ACCOUNT_NUMBER;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_ALIAS_NAME;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_OWNER_NAME;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_PROVIDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_PROVIDER_NAME;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_PROVIDER_NUMBER;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_SUB_PROVIDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.SUB_PROVIDER_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.CUSTOM_HEADER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.ELECTRICITY_BILL;
import static com.tekitsolutions.remindme.Utils.CommonUtils.ELECTRICITY_BILL_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GAS;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GAS_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GENERAL_HEADER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.INSURANCE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.INSURANCE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.LANDLINE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.LANDLINE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.NO_CATEGORY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.OTHER_HEADER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_PROVIDER_CODE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.RESULT_FAILED;
import static com.tekitsolutions.remindme.Utils.CommonUtils.RESULT_OKAY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.WATER_BILL;
import static com.tekitsolutions.remindme.Utils.CommonUtils.WATER_BILL_ID;
public class CategoryDialog extends BaseClass implements View.OnClickListener, Callback<String>, HamburgerMenuListener, ResultListener {
private static final String TAG = CategoryDialog.class.getSimpleName();
int i = 0;
private String landlineName, getProviderName, defaultName = "", phoneNum, customCategoryName, selected = "", getConsumerNum, getAccountNum, getOwnerName;
private long tempId = 0, categoryId, getCustomCategoryId, providerId, customCategoryId = 0, subProviderId;
private boolean stop = true, insurance, isEditPayment = false, isDeletedSQLite = false, isDeletedServer = false, isClicked = false;
private ExpandableCategoryAdapter expandableCategoryAdapter;
private List<CustomCategory> categories, customCategories;
private RecyclerView dialogRecyclerView;
private ExpandableListView expandableListView;
private DatabaseAdapter dbAdapter;
private Context context;
private SharedPreferences profilePreference;
private View promptsView;
private CustomCategory customCategory;
private List<Reminder> dialogListItems;
private ImageView info, search, close;
private DialogListAdapter dialogListAdapter;
private Activity activity;
private ProviderDialog providerDialog;
private TextView categoryToolbar, title, inputInsuranceProvider, textViewError, inputBillProvider, errorView, information, subProviderError, providerError, customProviderError, consumerError, ownerError;
private EditText searchText, userInput, inputConsumerNumber, name, inputAccountNumber, inputCustomProvider;
private ProvidersInfo providersInfo;
private AlertDialog informationDialog, mDialog;
private CategoryListener categoryListener;
private General provider, subProvider;
private RelativeLayout relativeProvider, subProviderLayout, accountLayout, customLayout;
private LinearLayout spinnerLayout;
private List<General> mainInsuranceList = new ArrayList<>();
private CustomSpinnerAdapter spinnerAdapter;
private CustomSpinnerClass spinInsuranceList;
private ArrayList<CategoryHeader> headerArrayList = new ArrayList<CategoryHeader>();
private CategoryHeader categoryHeader;
public CategoryDialog(Context context, Activity activity) {
super(context, activity);
this.activity = activity;
this.context = context;
}
private void init() {
categories = new ArrayList<>();
customCategories = new ArrayList<>();
dbAdapter = RemindMe.getInstance().adapter;
search = promptsView.findViewById(R.id.search);
close = promptsView.findViewById(R.id.close);
categoryToolbar = promptsView.findViewById(R.id.category_toolbar);
searchText = promptsView.findViewById(R.id.search_text);
dialogListItems = new ArrayList<>();
profilePreference = context.getSharedPreferences(PROFILE, MODE_PRIVATE);
providerDialog = new ProviderDialog(context);
providerDialog.setResultListener(this);
getDataFromSharedPref();
}
private void search() {
searchText.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) {
expandableCategoryAdapter.filterData(s.toString());
if (count == 0) {
if (headerArrayList.size() == 0) {
loadSomeData();
}
expandAll();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void loadSomeData() {
categoryHeader = new CategoryHeader(GENERAL_HEADER, categories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(OTHER_HEADER, categories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(CUSTOM_HEADER, customCategories);
headerArrayList.add(categoryHeader);
}
public void setCategoryListener(CategoryListener listener) {
this.categoryListener = listener;
}
private void setClickListener() {
search.setOnClickListener(this);
close.setOnClickListener(this);
}
public void showCategoryDialog() {
LayoutInflater li = LayoutInflater.from(context);
promptsView = li.inflate(R.layout.row_category_dialog_layout, null);
init();
findViewById();
setClickListener();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder.setPositiveButton(context.getString(R.string.add), null);
alertDialogBuilder.setNegativeButton(context.getString(R.string.cancel), null);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setCancelable(false);
recyclerView();
search();
mDialog = alertDialogBuilder.create();
mDialog.setCancelable(false);
mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
Button buttonNegative = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isEditPayment = false;
showDialogBox(0);
}
});
buttonNegative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
mDialog.show();
}
private void findViewById() {
expandableListView = promptsView.findViewById(R.id.expandableList);
}
private void recyclerView() {
loadArrayListData();
expandableCategoryAdapter = new ExpandableCategoryAdapter(context, headerArrayList, this);
try {
expandableListView.setAdapter(expandableCategoryAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
}
//method to expand all groups
private void expandAll() {
int count = expandableCategoryAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
expandableListView.expandGroup(i);
}
}
ExpandableListAdapter:
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tekitsolutions.remindme.Interface.HamburgerMenuListener;
import com.tekitsolutions.remindme.Model.CategoryHeader;
import com.tekitsolutions.remindme.Model.CustomCategory;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Utils.CommonUtils;
import java.util.ArrayList;
import java.util.List;
public class ExpandableCategoryAdapter extends BaseExpandableListAdapter {
private static final String TAG = ExpandableCategoryAdapter.class.getSimpleName();
private Context context;
private List<CategoryHeader> originalList;
private List<CategoryHeader> headerList;
private HamburgerMenuListener menuInterface;
public ExpandableCategoryAdapter(Context context, List<CategoryHeader> generalList, HamburgerMenuListener menuInterface) {
this.context = context;
this.headerList = new ArrayList<CategoryHeader>();
this.headerList.addAll(generalList);
this.originalList = generalList;
this.menuInterface = menuInterface;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
List<CustomCategory> countryList = headerList.get(groupPosition).getCategoryList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Resources resources = context.getResources();
CustomCategory customCategory = (CustomCategory) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_general_list, null);
}
TextView name = convertView.findViewById(R.id.tv_category_item);
ImageView icon = convertView.findViewById(R.id.iv_category_icon);
Button logo = convertView.findViewById(R.id.iv_custom_category_icon);
ImageView hamburgerMenu = convertView.findViewById(R.id.hamburger_menu);
if (customCategory != null) {
if (customCategory.getCustCategoryName() != null) {
name.setText(customCategory.getCustCategoryName().trim());
}
if (customCategory.getIcon() != null && customCategory.getCustCategoryId() <= CommonUtils.WATER_BILL_ID) {
icon.setVisibility(View.VISIBLE);
logo.setVisibility(View.GONE);
hamburgerMenu.setVisibility(View.GONE);
icon.setImageResource(resources.getIdentifier(customCategory.getIcon(), "drawable",
context.getPackageName()));
} else {
icon.setVisibility(View.GONE);
logo.setVisibility(View.VISIBLE);
hamburgerMenu.setVisibility(View.VISIBLE);
logo.setText(customCategory.getCustCategoryName().substring(0, 1));
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
menuInterface.onClickListItem(headerList.get(groupPosition).getCategoryList().get(childPosition).getCustCategoryId());
}
});
hamburgerMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (menuInterface != null) {
menuInterface.onClickHamburger(headerList.get(groupPosition).getCategoryList().get(childPosition).getCustCategoryId());
}
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
if (headerList.get(groupPosition).getHeaderName().equals(CommonUtils.GENERAL_HEADER)) {
return CommonUtils.LANDLINE_ID;
}
if (headerList.get(groupPosition).getHeaderName().equals(CommonUtils.OTHER_HEADER)) {
return CommonUtils.WATER_BILL_ID;
}
return headerList.get(groupPosition).getCategoryList().size();
}
#Override
public Object getGroup(int groupPosition) {
return headerList.get(groupPosition);
}
#Override
public int getGroupCount() {
return headerList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
CategoryHeader categoryHeader = (CategoryHeader) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row_custom_category_list, null);
}
TextView heading = view.findViewById(R.id.header_view);
heading.setText(categoryHeader.getHeaderName().trim());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
headerList.clear();
if (query.isEmpty()) {
headerList.addAll(originalList);
} else {
for (CategoryHeader categoryHeader : originalList) {
List<CustomCategory> categoryList = categoryHeader.getCategoryList();
List<CustomCategory> newList = new ArrayList<CustomCategory>();
for (CustomCategory customCategory : categoryList) {
if (customCategory.getCustCategoryName().toLowerCase().contains(query)) {
newList.add(customCategory);
}
}
if (newList.size() > 0) {
CategoryHeader nContinent = new CategoryHeader(categoryHeader.getHeaderName(), newList);
headerList.add(nContinent);
}
}
}
notifyDataSetChanged();
}
}
Solved by adding separate arraylist according to header name. Also added field/tag in databse.
private void loadSomeData() {
List<CustomCategory> generalCategories = new ArrayList<>();
generalCategories.addAll(dbAdapter.getCategoryById(null, 0, GENERAL_HEADER));
List<CustomCategory> otherCategories = new ArrayList<>();
otherCategories.addAll(dbAdapter.getCategoryById(null, 0, OTHER_HEADER));
categoryHeader = new CategoryHeader(GENERAL_HEADER, generalCategories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(OTHER_HEADER, otherCategories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(CUSTOM_HEADER, customCategories);
headerArrayList.add(categoryHeader);
}
Here is my code of the populated listview adapter that I have
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class ListViewAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list, null);
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView companyName = (TextView) convertView.findViewById(R.id.companyName);
Contact m = DataList.get(position);
name.setText(m.getName());
companyName.setText(String.valueOf(m.getCompanyName()));
return convertView;
}
}
And here is my main
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new ListViewAdapter(this, l);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, ContactDetail.class);
startActivity(i);
}
});
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(MainActivity.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
}
this code works properly and populates my listview, however, when I click on an item in the listview I have another listview populating that displays all contact items...I just want ONE contact item to display.
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ListViewContactAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Contact> DataList;
public ListViewContactAdapter(Activity activity, List<Contact> dataitem) {
this.activity = activity;
this.DataList = dataitem;
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.contactlistinfo, null);
ImageView i = (ImageView) convertView.findViewById(R.id.imageView2);
TextView tv2 = (TextView) convertView.findViewById(R.id.textView2);
TextView tv4 = (TextView) convertView.findViewById(R.id.textView4);
TextView tv6 = (TextView) convertView.findViewById(R.id.textView6);
TextView tv8 = (TextView) convertView.findViewById(R.id.textView8);
TextView tv17 = (TextView) convertView.findViewById(R.id.textView17);
TextView tv18 = (TextView) convertView.findViewById(R.id.textView18);
TextView tv19 = (TextView) convertView.findViewById(R.id.textView19);
TextView tv20 = (TextView) convertView.findViewById(R.id.textView20);
TextView tv10 = (TextView) convertView.findViewById(R.id.textView10);
TextView tv12 = (TextView) convertView.findViewById(R.id.textView12);
TextView tv14 = (TextView) convertView.findViewById(R.id.textView14);
TextView tv16 = (TextView) convertView.findViewById(R.id.textView16);
Contact m = DataList.get(position);
tv2.setText(m.getName());
tv4.setText(m.getCompanyName());
tv6.setText(m.getHome());
tv12.setText(m.getMobile());
tv14.setText(m.getWork());
tv8.setText(m.getStreet());
tv18.setText(m.getCity());
tv17.setText(m.getState());
tv19.setText(m.getZipCode());
tv20.setText(m.getCountry());
tv10.setText(m.getBirthdate());
tv16.setText(m.getEmail());
i.setImageURI(Uri.parse("https://s3.amazonaws.com/technical-challenge/v3/images/elmer-fudd-small.jpg"));
return convertView;
}
}
Now here is where I have it being populated. But why does it display as another list listview? I want only ONE item.
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ContactDetail extends AppCompatActivity {
private static final String url = "https://s3.amazonaws.com/technical-challenge/v3/contacts.json";
private List<Contact> l = new ArrayList<Contact>();
private ListView listView;
private ListViewContactAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_detail);
listView = (ListView) findViewById(R.id.list2);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
JsonArrayRequest jsonreq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++)
try {
JSONObject obj = response.getJSONObject(i);
// Phone
JSONObject phone = obj.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
String work = phone.getString("work");
//Address
JSONObject address = obj.getJSONObject("address");
String street = address.getString("street");
String city= address.getString("city");
String state= address.getString("state");
String country= address.getString("country");
String zipCode= address.getString("zipCode");
Contact dataSet = new Contact();
dataSet.setName(obj.getString("name"));
dataSet.setCompanyName(obj.getString("companyName"));
dataSet.setBirthdate(obj.getString("birthdate"));
dataSet.setEmail(obj.getString("emailAddress"));
dataSet.setHome(home);
dataSet.setMobile(mobile);
dataSet.setWork(work);
dataSet.setStreet(street);
dataSet.setState(state);
dataSet.setCity(city);
dataSet.setZipCode(zipCode);
dataSet.setCountry(country);
dataSet.setImage(obj.getString("largeImageURL"));
l.add(dataSet);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(ContactDetail.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("Error!!!");
alert.show();
}
});
Controller.getInstance(this).addToRequestQueue(jsonreq);
}
}
I guess your ContactDetail activity is getting the list again. And why do you need to show a listview again if you only need one item upon clicking of one item in your first activity.
Anyway, if you still want to use listview in your ContactDetail then do this..
in your listview.setOnItemClickListener on MainActivity
Intent intent = new Intent(MainActivity.this, ContactDetail.this);
intent.putExtra("contact", l.get(position));
startActivity(intent);
in your ContactDetails activity, replace it with this.. remove that JsonArrayRequest
listView = (ListView) findViewById(R.id.list2);
Contact contact = getIntent().getSerializableExtra("contact");
l.add(contact);
adapter = new ListViewContactAdapter(this, l);
listView.setAdapter(adapter);
and also make sure that your Contact object implements Serializable
I got a source code about GridView.
But, I confused why some code were error.
These are the code. I got error on OnClick Method in MainActivity. Is here anyone help me? Thanks
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
}
});
I want to each item that when it clicked shown the detailed image and text. I also get code like this but when I clicked "GingerBread" item, it goes to first item ("Astro")
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
// intent.putExtra("android.intent.extra.TEXT", Integer.parseInt(getIntent().getStringExtra("android.intent.extra.TEXT")));
intent.putExtra("title", item.getTitle());
//Start details activity
startActivity(intent);
overridePendingTransition(R.anim.home_detail_entry, R.anim.home_detail_exit);
}
});
MainActivity.java
package com.acer.gridview;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
public static String[] bitmapName = {
"Astro", "Bender", "Cupcake", "Donut", "Eclair",
"Froyo", "Gingerbread", "HoneyComb"
};
public static int[] bitmapId = {
R.drawable.Astro, R.drawable.Bender, R.drawable.Cupcake, R.drawable.Eclair,
R.drawable.Froyo, R.drawable.Gingerbread, R.drawable.HoneyComb
};
private GridViewAdapter gridAdapter;
private GridView gridView;
ArrayList < ImageItem > imageItems;
private ArrayList < ImageItem > getData() {
imageItems = new ArrayList();
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
int i = 0;
for (;;) {
if (i > 7) {
return imageItems;
}
Bitmap localBitmap = BitmapFactory.decodeResource(getResources(), bitmapId[i], localOptions);
imageItems.add(new ImageItem(localBitmap, bitmapName[i]));
i += 1;
}
}
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > AdapterView, View View, int Int, long Long) {
////////////This code shown error///////////////////
AdapterView = ((ImageItem) imageItems.get(Int)).getTitle();
toDetail(Int, AdapterView);
////////////This code shown error///////////////////
}
});
}
public void toDetail(int Int, String String) {
Intent localIntent = new Intent(this, DetailActivity.class);
localIntent.putExtra("android.intent.extra.TEXT", Integer.toString(Int));
localIntent.putExtra("title", String);
startActivity(localIntent);
}
/**
* A placeholder fragment containing a simple view.
*/
private boolean ActionBar(final Intent aIntent) {
try {
startActivity(aIntent);
return true;
} catch (ActivityNotFoundException e) {
return false;
}
}
public void showDialog() {
LayoutInflater inflater = getLayoutInflater();
View localView = inflater.inflate(R.layout.help_dialog, null);
((ImageView) localView.findViewById(R.id.imageView1)).setImageResource(R.drawable.makhrojulhuruf);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(localView);
builder.show();
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}
GridViewAdapter.java
package com.acer.gridview;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Acer on 08/02/2016.
*/
public class GridViewAdapter extends ArrayAdapter<ImageItem> {
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId, ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = (ImageItem) data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
ImageItem.java
package com.acer.gridview;
import android.graphics.Bitmap;
/**
* Created by Acer on 08/02/2016.
*/
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap Bitmap, String String)
{
setImage(Bitmap);
setTitle(String);
}
public Bitmap getImage()
{
return this.image;
}
public String getTitle()
{
return this.title;
}
public void setImage(Bitmap Bitmap)
{
this.image = Bitmap;
}
public void setTitle(String String)
{
this.title = String;
}
}
I have a list view inside a fragment like this:
The contacts section shows the user contacts and the groups section shows user groups. both of them are using fragments. I have been able to implement the custom listview for them. Code for contactadaptor used to populate the listview in contact section is given below:
package com.project.iandwe.Adaptor;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.project.iandwe.Data.ContactData;
import com.project.iandwe.R;
import java.util.ArrayList;
/**
* Created by NathanDrake on 6/4/2014.
*/
public class ContactSelectAdaptor extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
ArrayList<ContactData> listViewRows;
Context context;
public SparseBooleanArray checkboxState;
public ContactSelectAdaptor(Context context){
//Resources resources = context.getResources();
this.context =context;
UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(context);
Cursor cursor = userDatabaseAdapter.getUserContacts();
listViewRows = new ArrayList<ContactData>();
checkboxState = new SparseBooleanArray();
while (cursor.moveToNext()){
// ContactData listViewRow = new ListViewRow();
String contact_id = cursor.getString(0);
String first_name = cursor.getString(1);
String last_name = cursor.getString(2);
String email = cursor.getString(3);
String icon = cursor.getString(4);
// Log.d("ContactSelectAdaptor"," " + contact_id + " " + first_name + " " + last_name+ " " + email);
if (last_name == null){
last_name = " ";
}
listViewRows.add(new ContactData(contact_id,first_name,last_name,email,icon));
}
cursor.close();
}
#Override
public int getCount() {
return listViewRows.size();
}
#Override
public Object getItem(int position) {
return listViewRows.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewClass viewClass = null;
if (row==null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.listview_contact_select, parent, false);
viewClass = new ViewClass(row);
row.setTag(viewClass);
}
else {
viewClass = (ViewClass) row.getTag();
}
/* ImageView imageView = (ImageView) view.findViewById(R.id.imageViewProfile);
TextView textViewName = (TextView) view.findViewById(R.id.textViewDisplayName);
TextView textViewEmail = (TextView) view.findViewById(R.id.textViewEmailAddress);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxSelected);
*/
ContactData contactData = listViewRows.get(position);
Uri uri = contactData.getIcon();
if (uri!=null){ viewClass.imageView.setImageURI(uri); }
else { viewClass.imageView.setImageResource(R.drawable.ic_contacts); }
viewClass.textViewName.setText(contactData.getFirst_name());
viewClass.textViewEmail.setText(contactData.getEmail());
viewClass.checkBox.setTag(position);
viewClass.checkBox.setChecked(checkboxState.get(position,false));
viewClass.checkBox.setOnCheckedChangeListener(this);
return row;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkboxState.put((Integer) buttonView.getTag(), isChecked);
}
class ViewClass {
ImageView imageView;
TextView textViewName;
TextView textViewEmail;
CheckBox checkBox;
ViewClass (View view){
imageView = (ImageView) view.findViewById(R.id.imageViewProfile);
textViewName = (TextView) view.findViewById(R.id.textViewDisplayName);
textViewEmail = (TextView) view.findViewById(R.id.textViewEmailAddress);
checkBox = (CheckBox) view.findViewById(R.id.checkBoxSelected);
}
}
}
This is how i try to pick up the contacts that have been selected by the user:
package com.project.iandwe.Menu;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.project.iandwe.Adaptor.ContactSelectAdaptor;
import com.project.iandwe.Adaptor.UserDatabaseAdapter;
import com.project.iandwe.R;
import java.util.ArrayList;
/**
* Created by NathanDrake on 5/4/2014.
*/
public class ContactsFragments extends Fragment {
TextView textView;
ListView listView;
String eventId;
public ContactsFragments(){}
public ContactsFragments (String eventID){
this.eventId=eventID;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_contact,container, false );
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(getActivity());
//textView = (TextView) getActivity().findViewById(R.id.textViewSample);
// textView.setText(userDatabaseAdapter.getUserContacts());
listView = (ListView) getActivity().findViewById(R.id.listViewContacts);
ContactSelectAdaptor contactSelectAdaptor = new ContactSelectAdaptor(getActivity());
listView.setAdapter(contactSelectAdaptor);
listView.setVisibility(View.VISIBLE);
/* Checking who all customers have been invited to the events
* http://stackoverflow.com/questions/18162931/get-selected-item-using-checkbox-in-listview */
Cursor cursor = userDatabaseAdapter.getUserContacts();
cursor.moveToFirst();
for (int i=0; i<contactSelectAdaptor.checkboxState.size();i++){
if (contactSelectAdaptor.checkboxState.get(i)==true){
String contact_id = cursor.getString(0);
String first_name = cursor.getString(1);
String last_name = cursor.getString(2);
String email = cursor.getString(3);
//String icon = cursor.getString(4);
long id = userDatabaseAdapter.insertUserInvite(eventId,contact_id,email,first_name,last_name,0,0,0,0);
if (id<0){
Log.e("UserEventContactInsert","Failure");
}
}
cursor.moveToNext();
}
cursor.close();
}
}
AS i am new to android, i am not sure if the above code to check for user selection of checkboxes should be done in which section of the fragment? I would actually like to populate this data if the user has selected the Done menu presented on the top right corner but then i am finding it difficult to spend the sparse boolean array from fragment to activity. Is there a way this can be accomplished?
Adding code for the main activity which has the "Done" menu button:
package com.project.iandwe;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.project.iandwe.Adaptor.FragmentContactAdaptor;
import com.project.iandwe.Adaptor.UserDatabaseAdapter;
/**
* Created by NathanDrake on 5/21/2014.
*/
public class AddContacts extends FragmentActivity {
ViewPager viewPager = null;
String name;
String eventId,description,date, time, location;
protected void onCreate( Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.add_contacts);
viewPager = (ViewPager) findViewById(R.id.pager_contacts);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new FragmentContactAdaptor(fragmentManager));
//viewPager.setCurrentItem(1);
Intent intent = getIntent();
eventId = intent.getExtras().getString("eventId");
name = intent.getExtras().getString("name");
description = intent.getExtras().getString("description");
date = intent.getExtras().getString("date");
time = intent.getExtras().getString("time");
location = intent.getExtras().getString("location");
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_event_finish,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_finish:
//UserDatabaseAdapter userDatabaseAdapter = new UserDatabaseAdapter(this);
//long id = userDatabaseAdapter.insertUserEvent(name,description,date,time,location);
//if (id>0 ) {
Toast.makeText(this,"Event successfully Created",Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
// }
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
In the menu done handler try to get your adapter in this way:
ContactsFragments fragment = (ContactsFragments) getSupportFragmentManager()
.findFragmentByTag("ContactsFragments");
ListView listView = fragment.listView;
ContactSelectAdaptor adapter = (ContactSelectAdaptor)listView.getAdaptor();
If you have the adaptor then your sparseb boolean array is visible.
When I add new item to list view my previous item goes away. It only displays latest item.
I have two editview, name and email. And a button create player. On button click, name and email should add as one item(2 line) in list view.
Please help.
Regards
CreateTeamActivity.java
package com.recscores.android;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.Toast;
public class CreateTeamActivity extends Activity implements OnClickListener {
Button addPlayer;
Button createPlayer;
LinearLayout view_createPlayer;
TableLayout numberPad;
EditText Email;
EditText Name;
EditText teamname;
ListView Roster;
private CustomAdapter adapter;
private ArrayList<PlayerInfo> fetch = new ArrayList<PlayerInfo>();
private PlayerInfo info = new PlayerInfo();
private ListView lv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_team);
addPlayer = (Button)findViewById(R.id.addplayer);
createPlayer = (Button)findViewById(R.id.createplayer);
Email = (EditText)findViewById(R.id.email);
Name = (EditText)findViewById(R.id.name);
lv = (ListView)findViewById(android.R.id.list);
adapter = new CustomAdapter(CreateTeamActivity.this,
android.R.id.list,
fetch);
lv.setAdapter(adapter);
createPlayer.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.createplayer: /** Create Player */
info.SetName(Name.getText().toString());
info.SetEmail(Email.getText().toString());
fetch.add(info);
counter++;
// lv.invalidateViews();
adapter.notifyDataSetChanged();
//Thread.sleep(2000);
break;
}
}
}
CustomAdapter.java
package com.recscores.android;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<PlayerInfo>{
private ArrayList<PlayerInfo> entries;
private Activity activity;
public CustomAdapter(Activity a, int textViewResourceId, ArrayList<PlayerInfo> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
public int getCount()
{
return entries.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.add_player_listview, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.name);
holder.item2 = (TextView) v.findViewById(R.id.email);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final PlayerInfo custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.GetName());
holder.item2.setText(custom.GetEmail());
}
return v;
}
}
Try adding
PlayerInfo info = new PlayerInfo();
before
info.SetName(Name.getText().toString());