I have make a demo of auto suggest . I have name(string) and code(string) .I have around 2000 name with their codes ..So I take string array and put it in this format name-(code) example "Alexandra Palace-(AAP)",.my problem is that I need to filter using code not by name .Actually when I type in input field it match with name not with code .But I need to filter with code.
example
when I type "lwy" it will not show "MNCRLWY-(LWY)", can you please tell how I will achieve this ?
I try like this
public class GlobalList {
public static String[] stationList={
"MNCRLWY-(LWY)",
"Lympstone Commando-(LYC)",
"Lydney-(LYD)",
"Lye-(LYE)",
"Lympstone Village-(LYM)",
"Lymington Pier-(LYP)",
"Lymington Town-(LYT)",
"Lazonby & Kirkoswald-(LZB)",
"Leeds, Whitehall (Bus)-(LZZ)",
"Macclesfield-(MAC)",
"Maghull-(MAG)",
"Maidenhead-(MAI)",
"Malden Manor-(MAL)",
"Manchester Piccadilly-(MAN)",
"Martins Heron-(MAO)",
"Margate-(MAR)",
"Manors-(MAS)",
"Matlock-(MAT)",
"Mauldeth Road-(MAU)",
"Mallow-(MAW)",
"Maxwell Park-(MAX)",
"Maybole-(MAY)",
"Millbrook (Hampshire)-(MBK)",
"Middlesbrough-(MBR)",
"Moulsecoomb-(MCB)",
"Metro Centre-(MCE)",
"March-(MCH)",
"Marne La Vallee-(MCK)",
"Morecambe-(MCM)",
"Machynlleth-(MCN)",
"Manchester Oxford Road-(MCO)",
"Manchester Victoria-(MCV)",
"Maidstone Barracks-(MDB)",
"Maidstone East-(MDE)",
"Midgham-(MDG)",
"Middlewood-(MDL)",
"Maiden Newton-(MDN)",
"Morden South-(MDS)",
"Maidstone West-(MDW)",
"MAERDY-(MDY)",
"Meols Cop-(MEC)",
"Meldreth-(MEL)",
"Menheniot-(MEN)",
"Meols-(MEO)",
"Meopham-(MEP)",
"Merthyr Tydfil-(MER)",
"Melton-(MES)",
"Merthyr Vale-(MEV)",
"Maesteg (Ewenny Road)-(MEW)",
"Mexborough-(MEX)",
"Merryton-(MEY)",
"Morfa Mawddach-(MFA)",
"Minffordd-(MFD)",
"Minffordd-(MFF)",
"Milford Haven-(MFH)",
};
}
CustomAdapter :
public class CustomAutocompletAdapter extends BaseAdapter implements Filterable{
private String stationNameAndCodeValue ;
ArrayList<String> autolistArray;
ArrayList<String> objects;
private Context context;
public CustomAutocompletAdapter( Context context, String[] autolistArray){
this.autolistArray=new ArrayList<String>();
for(int i=0;i<autolistArray.length;i++){
this.autolistArray.add(autolistArray[i]);
} this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return autolistArray.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return autolistArray.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = mInflater.inflate(R.layout.custom_row_adapter, null);
}
final TextView stationNameAndCode = (TextView) v
.findViewById(R.id.item_selectStationName);
stationNameAndCodeValue = autolistArray.get(position);
stationNameAndCode.setText(stationNameAndCodeValue);
return v;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
Filter myFilter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
System.out.println("Constraint " + constraint);
Log.d("-----------", "publishResults");
if (results.count > 0 && results != null) {
objects = (ArrayList<String>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
Log.d("-----------", "performFiltering");
FilterResults results = new FilterResults();
List<String> FilteredArrList = new ArrayList<String>();
if (objects == null) {
objects = new ArrayList<String>(autolistArray); // saves
}
Locale locale = Locale.getDefault();
constraint = (String) constraint
.toString().toLowerCase(locale);
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = objects.size();
results.values = objects;
} else {
for (int i = 0; i < objects.size(); i++) {
String name= objects.get(i);
String newName = name.substring(name.indexOf('('),name.length()-1);
if (newName.toLowerCase(locale).contains(constraint))
{
FilteredArrList.add(name);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// TODO Auto-generated method stub
//convert object to string
Log.d("-----------", "convertResultToString");
return "";
}
};
return myFilter;
}
}
Main Activity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_station);
autocompleteView = (AutoCompleteTextView) findViewById(R.id.item_autoComplete);
STATION_LIST = new String[GlobalList.stationList.length
+ GlobalExtendStationList.stationList.length];
System.arraycopy(GlobalList.stationList, 0, STATION_LIST, 0,
GlobalList.stationList.length);
System.arraycopy(GlobalExtendStationList.stationList, 0,
STATION_LIST, GlobalList.stationList.length,
GlobalExtendStationList.stationList.length);
autosuggestAdapter = new CustomAutocompletAdapter(this,STATION_LIST);
autocompleteView.setAdapter(autosuggestAdapter);
Xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity=""
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose station"
android:layout_marginLeft="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<AutoCompleteTextView
android:id="#+id/item_autoComplete"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:ems="10"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="AutoCompleteTextView" >
<requestFocus />
</AutoCompleteTextView>
</LinearLayout>
</LinearLayout>
As you are checking the searching string in the whole string(name), so if it founds the serching string anywhere in the name then it adds to the resut.
So Use this
String newName = name.subString(indexOf('('),name.lastIndexOf(')'));
if (newName.toLowerCase(locale).contains(constraint))
{
FilteredArrList.add(name);
}
instead of
if (name.toLowerCase(locale).contains(constraint))
{
FilteredArrList.add(name);
}
Related
Six RadioButtons aligned as 3 columns and 2 rows in a RadioGroup, so 6 RB-s in RG. If user selects a RB, right under it image1 and text1 are shown and under alternated RB-s image1 and text2 are also shown. User may select any RB. The proper behavior looks like that https://photos.app.goo.gl/NEqTaxsY6daxD3kJA
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg">
<include layout="#layout/app_bar" />
<fragment
android:id="#+id/refreshLayoutFragment"
class="kz.fingram.RefreshLayoutFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_refresh_layout" />
<LinearLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/activity_margin"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:paddingStart="#dimen/activity_margin"
android:paddingTop="#dimen/activity_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/when_u_want_money"
android:textAppearance="#style/TextAppearance.Medium" />
<RadioGroup
android:id="#+id/months"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener}" />
<LinearLayout
android:id="#+id/thisIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<RadioGroup
android:id="#+id/months2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener2}" />
<LinearLayout
android:id="#+id/thatIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<Button
style="#style/Button.Primary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:enabled="#{viewModel.mIsNextEnabled}"
android:onClick="#{viewModel::nextOnClick}"
android:text="#string/next" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Java code:
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
public final class OptionsActivity extends BaseAppCompatActivity {
private ActivityOptionsBinding mBinding;
public static void show(#NonNull final Context ctx) {
StorageHelper.getInstance().setInvited(false);
BaseAppCompatActivity.show(ctx, OptionsActivity.class, true, false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_options);
setupToolbar();
mBinding.setViewModel(new ViewModel());
}
public final class ViewModel extends BaseObservable {
private static final int TERM_6_MONTH_ID = 1;
private static final int INSTALLMENT_10000_ID = 1;
private final RefreshLayoutFragment mRefreshLayout;
public boolean mIsNextEnabled;
public TeamFreeMonth mMonth;
private TeamFreeMonth[] mMonths;
ViewModel() {
mMonth = null;
mMonths = null;
mRefreshLayout = (RefreshLayoutFragment) getSupportFragmentManager()
.findFragmentById(R.id.refreshLayoutFragment);
mRefreshLayout.setup(mBinding.root, new RefreshLayoutFragment.Callback() {
#Override
public void reload() {
try {
loadData();
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
});
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg2 = findViewById(R.id.months2);
rg2.setOnCheckedChangeListener(null);
rg2.clearCheck();
rg2.setOnCheckedChangeListener(mMonthOnCheckedChangeListener2);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener2 =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
private void refreshMonths() {
mBinding.months.removeAllViews();
mBinding.months.clearCheck();
mBinding.months2.removeAllViews();
mBinding.months2.clearCheck();
mBinding.thisIs.removeAllViews();
mBinding.thatIs.removeAllViews();
final TeamFreeMonth oldMonth = mMonth;
mMonth = null;
checkButtonsState();
if (mMonths == null) {
return;
}
final TeamFreeMonth[] months = mMonths;
if (months.length == 0) {
return;
}
int halfMonths = months.length / 2;
for (int i = 0; i < halfMonths; i++) {
final String date = UtilitiesHelper.dateToStr(months[i].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
final String date2 = UtilitiesHelper.dateToStr(months[i + halfMonths].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
if (TextUtils.isEmpty(date) || TextUtils.isEmpty(date2)) {
continue;
}
final RadioButton rb = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months, false);
rb.setId(i);
rb.setTag(months[i]);
final SpannableString btnCaption = new SpannableString(date);
btnCaption.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date.length(), 0);
rb.setText(btnCaption);
final RadioButton rb2 = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months2, false);
rb2.setId(i + halfMonths);
rb2.setTag(months[i + halfMonths]);
final SpannableString btnCaption2 = new SpannableString(date2);
btnCaption2.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date2.length(), 0);
rb2.setText(btnCaption2);
if (i == 0) {
rb.setBackgroundResource(R.drawable.ll_radio_button_start);
rb2.setBackgroundResource(R.drawable.ll_radio_button_start);
} else if (i == halfMonths - 1) {
rb.setBackgroundResource(R.drawable.ll_radio_button_end);
rb2.setBackgroundResource(R.drawable.ll_radio_button_end);
}
mBinding.months.addView(rb);
mBinding.months2.addView(rb2);
TextView thisIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_this_is_item, mBinding.thisIs, false);
thisIs.setId(rb.getId());
thisIs.setText(getString(R.string.thisIs));
thisIs.setVisibility(View.INVISIBLE);
mBinding.thisIs.addView(thisIs);
TextView thatIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_that_is_item, mBinding.thatIs, false);
thatIs.setId(rb2.getId());
thatIs.setText(getString(R.string.thatIs));
thatIs.setVisibility(View.INVISIBLE);
mBinding.thatIs.addView(thatIs);
if (oldMonth != null && UtilitiesHelper.isDateEquals(oldMonth.getDate(), months[i].getDate())) {
mBinding.months.check(rb.getId());
mBinding.months2.check(rb2.getId());
}
}
selectMonth();
}
private void selectMonth()
{
int selectedId1 = mBinding.months.getCheckedRadioButtonId();
int selectedId = selectedId1 !=-1 ? selectedId1 : mBinding.months2.getCheckedRadioButtonId();
int n = mBinding.months.getChildCount();
List<TextView> views = new ArrayList<TextView>();
for (int i = 0; i < n; i++) {
views.add(i, (TextView) mBinding.thisIs.getChildAt(i));
views.add(i+3, (TextView) mBinding.thatIs.getChildAt(i));
}
int length = views.size();
for (int i = 0; i < length; i++) {
TextView child = views.get(i);
}
private void checkButtonsState() {
mIsNextEnabled = mMonth != null;
notifyChange();
}
public void nextOnClick(final View view) {
try {
final TeamFreeMonth[] months = mMonths;
if (mMonth == null || months == null || months.length == 0) {
throw new Exception(getString(R.string.enter_month));
}
SettingsHelper.setTermId(OptionsActivity.this, TERM_6_MONTH_ID);//
SettingsHelper.setTermRateId(OptionsActivity.this, mMonth.getTermRateId());//
SettingsHelper.setInstallmentId(OptionsActivity.this, INSTALLMENT_10000_ID);
SettingsHelper.setGoalDateInMillis(OptionsActivity.this, mMonth.getDate().getTime());//дата получения
SettingsHelper.setFirstGoalDateInMillis(OptionsActivity.this, months[0].getDate().getTime());
SettingsHelper.setGoalSum(OptionsActivity.this, mMonth.getSum());
BaseAppCompatActivity.show(OptionsActivity.this, SetGoalActivity.class, true, false);
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
private void loadData() {
try {
final AsyncTask<Void, Void, TeamFreeMonth[]> task = new AsyncTask<Void, Void, TeamFreeMonth[]>() {
private Exception mError = null;
#Override
protected void onPreExecute() {
mRefreshLayout.setRefreshing(true);
}
#Override
protected TeamFreeMonth[] doInBackground(Void... params) {
try {
TeamFreeMonth[] months = ServerHelper.getInstance().syncGetOptionMonths(OptionsActivity.this, TERM_6_MONTH_ID, INSTALLMENT_10000_ID);
if (months != null && months.length > 0)
return months;
} catch (Exception e) {
mError = e;
}
return null;
}
#Override
protected void onPostExecute(TeamFreeMonth[] result) {
try {
if (mError != null) {
throw mError;
}
mMonths = result;
refreshMonths();
checkButtonsState();
mRefreshLayout.setRefreshing(false);
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
};
task.execute();
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
}
}
Image1 is always the same, while text1 and text2 differ. Text1 'You' is shown under the selected RB and text2 'Your friend' - under alternating RB-s.
The quetion still is how to show/hide image1 and text 1 or text 2 alternatively?
I can show/hide image1 and text-s under RB-s which is in the same column, but not alternating RB-s.
Good day guys,
I successfully populated my custom-listview-layout in my activity,
but the problem is I can't get all the value of populated EditText in my listview, please help me what approach should I do,
thanks
Picture Adapter.java
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
final dataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate( R.layout.row_layout,parent, false);
handler = new dataHandler();
handler.pictures = (ImageView) row.findViewById(R.id.pictures);
handler.name = (TextView) row.findViewById(R.id.picturename);
handler.price= (EditText) row.findViewById(R.id.price);
handler.add = (Button) row.findViewById(R.id.btnplus);
handler.minus = (Button) row.findViewById(R.id.btnminus);
row.setTag(handler);
}else{
handler = (dataHandler) row.getTag();
}
PSP psp;
psp =(PSP) this.getItem(position);
Picasso.with(getContext()).load(psp.getPicture()).resize(200, 155).into(handler.pictures);
handler.name.setText(psp.getName());
handler.price.setText(psp.getPrice());
return row;
}
MainActivity.java
PictureAdapter adapter;
listView = (ListView) findViewById(R.id.ls);
adapter = new PictureAdapter(this,R.layout.row_layout);
listView.setAdapter(adapter);
try {
JSONArray users = response.getJSONArray("user");
for (int x = 0; x <= users.length()-1; x++) {
JSONObject user = users.getJSONObject(x);
PSP psp = new PSP(imageUri+user.getString("image")+".png",user.getString("username"),"0");
adapter.add(psp);
}
} catch (JSONException e) {
e.printStackTrace();
}
PSP.java
public class PSP
{
private String picture;
private String name;
private String price;
public String getPicture() {
return picture;
}
public PSP(String picture, String name, String price){
this.setPicture(picture);
this.setName(name);
this.setPrice(price);
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="80dp"
android:background="#000000">
<ImageView
android:id="#+id/pictures"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/picturename"
android:layout_width="115dp"
android:layout_height="75dp"
android:layout_toRightOf="#+id/pictures"
android:text="Kim Domingo"
android:gravity="center"
android:textColor="#FFFFFF"
/>
<Button
android:id="#+id/btnplus"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:text="+"
android:textSize="50px"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/picturename"
android:layout_toEndOf="#+id/picturename"
/>
<EditText
android:id="#+id/price"
android:layout_width="50dp"
android:layout_height="50dp"
android:focusable="false"
android:textColor="#FFFFFF"
android:inputType="number"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/btnplus"
android:layout_toEndOf="#+id/btnplus" />
<Button
android:id="#+id/btnminus"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:text="-"
android:textSize="50px"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/price"
android:layout_toEndOf="#+id/price" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#FFFFFF"
android:layout_below="#+id/pictures"
android:id="#+id/editText"></View>
I created same before like this
You can use the HashMap map = new HashMap<>(); for what item user click. I assume that you use two button click are available in adapter class if not then add it.
Step 1 First Declare the HashMap map = new HashMap<>(); in adapter.
Step 2 Then put value in HashMap map.put("key","value"); This code put in both plus and minus button click event.
Step 3 Call ShowHashMapValue(); method below to the map.put("key","value"); for see the HashMap values check logcat for that.
Compare this adapter code for understand easily if any problem just comment below.
ListAdapter.java
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
//price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
listViewHolder.tvPrices.getTag();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
ShowHashMapValue();
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
So so here is logic. You need to declare a boolean in PSP. by default set it to false.
Now when + button will be triggered you need to set that boolean check to true
then in your set price create this logic.
public String getPrice() {
if(check==true){
price++;
}
else{
price--;
}
return price;
}
If i correctly understand you then this surely will help you. Good Luck!
So, I have scoured the interwebs and I cannot find a solution for this based on other people's experiences, so I am posting this issue. (Please note that this is my 1st android app experience and I am debugging / updating an existing app.)
When I implement my custom NotesListAdapter (extends BaseAdapter) on the ListView, mListNotesView (mListNotesView.setAdapter(this)), and load the data into the ArrayList mNoteList, the getView function is not being called. Also, I found that mListNotesView.setBackgroundResource is not chaning the background of the control, either. I have a similar implementation on a previous activity that works exactly correct. When I copied over the class and changed it to handle my ArrayList, it broke. I have getCount returning the ArrayList size(), which is not 0, and getItemId returns position. I have a feeling it may be my XML or my setup because it's acting like the ListView is not visible. I am perplexed. How do I get the ListView to show? Anything inside of the getView has not been reached so it may be buggy.
ViewTicketOrderActivity (Some parts ommitted for size)
public class ViewTicketOrderActivity extends Activity {
MySQLDatabase myDataBase;
Ticket mTicket;
public ArrayList<Notes> mNotes = new ArrayList<Notes>();
String mErrorString;
Button mAddUpdateButton;
Button mAcceptButton;
//Button mViewNotesButton;
NotesListAdapter mNotesListAdapter;
static final int ERROR_DIALOG = 0;
static final int SUCCESS_DIALOG = 1;
static final int COMPLETED_DIALOG = 2;
static final int RESTART_DIALOG = 3;
static final int LOADING = 0;
static final int LOAD_ERROR = 1;
static final int LOADED = 4;
static final String TICKET_EXTRA = "ticket_extra";
static final String TAG = "ViewTicketOrderActivity";
private static final boolean gDebugLog = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewticketorder);
Activity context = this;
String theTitle = "Sundance Ticket Order";
theTitle += (MySQLDatabase.TESTING == true) ? " (DEV SERVER)" : " (LIVE)";
setTitle(theTitle);
myDataBase = MySQLDatabase.getMySQLDatabase(this);
if (gDebugLog) {
DebugLogger.logString(TAG, ".onCreate");
}
mNotesListAdapter = new NotesListAdapter(context, R.id.note_list);
Log.d(this.toString(),this.mNotesListAdapter.toString());
}
private class NotesListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<Notes> mNoteList;
private ListView mListNotesView;
private Activity mActivity;
int mState = LOADING;
String mErrorMessage;
private NotesListAdapter(Activity context, int listViewID) {
mActivity = context;
mNoteList = new ArrayList<Notes>();
mInflater = LayoutInflater.from(context);
mListNotesView = (ListView)context.findViewById(listViewID);
mListNotesView.setBackgroundResource(R.color.emergency_red);
mListNotesView.setAdapter(this);
Log.d(mListNotesView.toString(), String.valueOf(mListNotesView.getCount()));
this.notifyDataSetChanged();
//mListNotesView.setVisibility(View.VISIBLE);
}
void setLoading()
{
mState = LOADING;
this.notifyDataSetChanged();
}
void setLoadError(String errorString)
{
mState = LOAD_ERROR;
mErrorMessage = errorString;
this.notifyDataSetChanged();
}
void setNoteList(ArrayList<Notes> inNotes)
{
mState = LOADED;
mNoteList.clear();
mNoteList.addAll(inNotes);
Log.d("SetNoteList", "TRUE " + inNotes);
//mNoteList = mNotes;
this.notifyDataSetChanged();
}
/**
* Use the array index as a unique id.
*
* #see android.widget.ListAdapter#getItemId(int)
*/
#Override
public long getItemId(int position) {
return position;
}
public int getCount(){
if (mState == LOADED) {
Log.d("getCount",String.valueOf(mNoteList.size()));
return mNoteList.size();
} else {
return 0;
}
}
/**
* Make a view to hold each row.
*
* #see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
Log.d("getView",this.toString());
if (mState == LOADED) {
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there
// is no need
// to reinflate it. We only inflate a new View when the
// convertView supplied
// by ListView is null.
Notes note = this.getItem(position);
if (convertView == null) {
/*if (ticket.emergency())
{
convertView = mInflater.inflate(R.layout.emergency_ticket_list_item_opt,
null);
}
else
{
convertView = mInflater.inflate(R.layout.ticket_list_item,
null);
}*/
convertView = mInflater.inflate(R.layout.noteslist_item,
null);
// Creates a ViewHolder and store references to the two
// children views
// we want to bind data to.
holder = new ViewHolder();
holder.noteText = (TextView) convertView
.findViewById(R.id.text_note);
holder.dateText = (TextView) convertView
.findViewById(R.id.text_note_date);
holder.createByText = (TextView) convertView
.findViewById(R.id.text_note_by);
holder.createByIDText = (TextView) convertView
.findViewById(R.id.text_note_by_id);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the
// TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
// Bind the data efficiently with the holder.
holder.noteText.setText(note.note());
holder.dateText.setText(note.date());
holder.createByText.setText(note.createBy());
holder.createByIDText.setText(note.employeeID());
if(!mTicket.employeeID().equals(note.employeeID())){
convertView.setBackgroundResource(R.drawable.solid_purple);
}
} else if (mState == LOADING ) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.loading_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Loading tickets");
} else if (mState == LOAD_ERROR) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.load_error_view,
null);
}
TextView messageText = (TextView)convertView.findViewById(R.id.message);
messageText.setText("Error loading tickets");
String errorString = mErrorMessage != null ? mErrorMessage : "";
TextView errorText = (TextView)convertView.findViewById(R.id.errorText);
errorText.setText(errorString);
}
return convertView;
}
class ViewHolder {
TextView noteText;
TextView dateText;
TextView createByText;
TextView createByIDText;
}
//#Override
/*public int getCount() {
*//*if (mState == LOADED) {
*//*
Log.d("getCount mState " + mState,String.valueOf(mNoteList.size())+", "+String.valueOf(mNotes.size()));
return mNoteList.size();
*//*} else {
Log.d("getCount mState " + mState,"0");
return 0;
}*//*
}*/
#Override
public Notes getItem(int position) {
Log.d("getItem",mNoteList.get(position).toString());
return mNoteList.get(position);
}
#Override
public int getItemViewType (int position) {
int result = mState;
Log.d("getItemId",String.valueOf(position));
return result;
}
#Override
public int getViewTypeCount ()
{
return 4;
}
}
protected void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
mTicket = (Ticket)extras.getSerializable(TICKET_EXTRA);
}
else
{
mTicket = new Ticket();
}
if (mTicket.emergency())
{
setContentView(R.layout.view_emergency_ticketorder);
}
else
{
setContentView(R.layout.viewticketorder);
}
if (gDebugLog)
{
DebugLogger.logString(TAG, ".onResume mTicket " + mTicket);
}
TicketCheckService.clearNotificationForNewTicket(mTicket);
new GetTicketTask().execute();
new GetNotesTask().execute();
updateDisplayedTicket();
}
private void updateDisplayedTicket() {
mAddUpdateButton = (Button)findViewById(R.id.addUpdateButton);
mAcceptButton = (Button)findViewById(R.id.acceptButton);
//mViewNotesButton = (Button)findViewById(R.id.viewNotesButton);
String ticketStatus = myDataBase.getDescriptionStringForStatusString(mTicket.status());
if(ticketStatus == "Job Rejected") {
mAddUpdateButton.setText("Restart Job");
} else {
mAddUpdateButton.setText("Add Update");
}
if(ticketStatus == "Requested") {
mAcceptButton.setText("Accept");
} else if(ticketStatus != "Requested") {
mAcceptButton.setText("Back");
}
//mViewNotesButton.setText(R.string.viewNotes);
TextView idText = (TextView)findViewById(R.id.textTicketID);
idText.setText(mTicket.id());
//TextView descriptionText = (TextView)findViewById(R.id.textDescription);
//descriptionText.setText(mTicket.description());
TextView titleText = (TextView)findViewById(R.id.textTitle);
titleText.setText(mTicket.title());
TextView storeIDText = (TextView)findViewById(R.id.textStoreID);
storeIDText.setText(mTicket.store());
String formatPhone;
TextView storePhoneText = (TextView)findViewById(R.id.textStorePhone);
if(mTicket.phoneNo().isEmpty()){
formatPhone = "NO PHONE NO.";
} else {
storePhoneText = (TextView) findViewById(R.id.textStorePhone);
formatPhone = mTicket.phoneNo().replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)$2-$3");
storePhoneText.setOnClickListener(new CallClickListener(mTicket.phoneNo()));
}
storePhoneText.setText(formatPhone);
TextView categoryText = (TextView)findViewById(R.id.textCategory);
String categoryDescription = MySQLDatabase.getDescriptionStringForCategoryString(mTicket.category());
categoryText.setText(categoryDescription);
if(ticketStatus == "Completed Pending") {
showDialog(COMPLETED_DIALOG);
}
}
public void onClickAccept(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAcceptButton.getText() =="Accept") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new AcceptTicketTask().execute();
} else {
finish();
}
}
public void onClickAddUpdate(View v) {
try {
boolean maint = myDataBase.getSystemMaintStatus();
if(maint) {
setLoadError("The phone app is down for maintenance.");
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(mAddUpdateButton.getText() =="Add Update") {
Intent i = new Intent(this, UpdateTicketActivity.class);
i.putExtra(UpdateTicketActivity.TICKET_EXTRA, mTicket);
startActivity(i);
} else if(mAddUpdateButton.getText() =="Restart Job") {
mAddUpdateButton.setEnabled(false);
mAcceptButton.setEnabled(false);
new RestartTicketTask().execute();
}
}
private class AcceptTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "1", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString) {
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(SUCCESS_DIALOG);
mAcceptButton.setText("Back");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class RestartTicketTask extends AsyncTask<Void, Integer, String>
{
protected String doInBackground(Void... parent) {
mErrorString = null;
String result = null;
String updateTime = DateFormat.getDateTimeInstance().format(new Date(0));
try {
boolean success = myDataBase.updateTicket(mTicket.id(), mTicket.employeeID(), mTicket.description(), "7", updateTime, null);
if (!success)
{
result = "Could not update Ticket";
}
} catch (IOException e) {
// TODO Auto-generated catch block
result = "Could not update Ticket - " + e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String errorString)
{
if (null != errorString) {
mErrorString = errorString;
showDialog(ERROR_DIALOG);
} else {
showDialog(RESTART_DIALOG);
mAcceptButton.setText("Done");
mAddUpdateButton.setText("Add Update");
}
mAddUpdateButton.setEnabled(true);
mAcceptButton.setEnabled(true);
}
}
private class GetTicketTask extends AsyncTask<Void, Integer, Ticket>
{
String mError = null;
protected Ticket doInBackground(Void... parent) {
Ticket result = null;
try {
result = myDataBase.getTicketWithID(mTicket.id(), mTicket.employeeID());
} catch (IOException e) {
// TODO Auto-generated catch block
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Ticket result)
{
if (null != result) {
mTicket = result;
} else {
setLoadError(mError);
}
}
}
private class GetNotesTask extends AsyncTask<Void, Integer, ArrayList<Notes>> {
String mError = null;
protected ArrayList<Notes> doInBackground(Void... parent) {
ArrayList<Notes> result = new ArrayList<Notes>();
try {
result = myDataBase.getTicketNotes(mTicket.id());
} catch (IOException e) {
// TODO Auto-generated catch block
myDataBase.debugLog("Error caught" + e);
mError = e.getLocalizedMessage();
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(ArrayList<Notes> result) {
if (null != result) {
Log.d("Result", result.toString());
mNotes = result;
} else {
Log.d("SetNoteList","FALSE");
mNotesListAdapter.setLoadError(mError);
}
}
}
private void updateDisplayedNotes(){
ArrayList<Notes> newNotes = mNotes;
if(newNotes != null) {
mNotesListAdapter.setNoteList(newNotes);
}
}
/*private class updateDisplayedNotes extends AsyncTask<Void, Integer, ArrayList<Notes>> {
public ArrayList<Notes> newNotes = new ArrayList<Notes>();
public updateDisplayedNotes(){
super();
Log.d(this.toString(), "Updating");
}
protected ArrayList<Notes> doInBackground(Void... parent) {
Log.d(this.toString(), "Background Task");
for (Notes note : mNotes) {
Log.d(this.toString(),note.toString());
if(note != null) {
Log.d(this.toString(), "Note Added");
newNotes.add(note);
}
}
return newNotes;
}
protected void onPostExecute(ArrayList<Notes> newNotes)
{
if(newNotes != null) {
mNotes.clear();
mNotes.addAll(newNotes);
mNotesListAdapter.setNoteList(mNotes);
}
}
}*/
void setLoadError(String error) {
setContentView(R.layout.load_error_view);
TextView messageText = (TextView)findViewById(R.id.message);
messageText.setText("Error loading ticket");
String errorString = error != null ? error : "";
TextView errorText = (TextView)findViewById(R.id.errorText);
errorText.setText(errorString);
finish();
}
}
viewticketorder.xml (where note_list is)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical"
tools:context=".ViewTicketOrderActivity"
tools:ignore="HardcodedText" >
<TextView
android:id="#+id/textTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:text="#string/loadingTicket"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white_color"
android:textSize="20dp"
android:textIsSelectable="true"
android:background="#drawable/title_transparent_bg"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:text="#string/ticketID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textTicketID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="3dp"
android:paddingTop="2dp"
android:text="#string/storeID"
android:textAppearance="?android:attr/textAppearanceSmall"
tools:ignore="HardcodedText" />
<TextView
android:id="#+id/textStoreID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"/>
<TextView
android:id="#+id/textStorePhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:textColor="#color/white_color"
android:textIsSelectable="true"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView05"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:paddingTop="2dp"
android:text="#string/category"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="center_vertical"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/white_color"
android:focusable="true"
android:textIsSelectable="true"/>
</LinearLayout>
<ListView
android:id="#+id/note_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:divider="#drawable/ticket_item_divider"
android:dividerHeight="1dp"
tools:ignore="NestedWeights"
android:choiceMode="singleChoice"
android:clickable="true"
android:background="#drawable/title_transparent_bg">
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/acceptButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:onClick="onClickAccept" />
<Button
android:id="#+id/addUpdateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:onClick="onClickAddUpdate" />
</LinearLayout>
</LinearLayout>
notelist_item.xml (inflator)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text_note_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80FFFFFF"
android:orientation="vertical"
>
<TextView
android:id="#+id/text_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/text_item_color"
android:textSize="#dimen/big_text_item_size" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight=".70"
>
<TextView
android:id="#+id/text_note_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
<TextView
android:id="#+id/text_note_by_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/filler_string"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/text_sub_item_color" />
</LinearLayout>
</LinearLayout>
I'm going to recommend you reorganize your code. Here are some general tips:
1) Keep your views like ListView in the Activity class. Don't try to inflate the view in your adapter class. So in your activity's onCreate() after setContentView() you should have something like:
ListView listView = (ListView) findViewById(R.id.listView);
2) Next you need to get the data that will be shown in the listview and store it in a list. I didn't see in your code where the data comes from, but let's just say it comes from a database. You should create something like an ArrayList and store the data that you want to show in the ListView in the ArrayList
3) Next you need to create an adapter and pass the list of data into the adapter.
4) Once this has been done the ListView now has an adapter that will supply data to it. If you've done everything correctly then the system will eventually call getView() automatically and your code inside that should run and render the view.
Not an exact solution, but hopefully this explanation will help you figure it out.
I am new in Android development, I want to bind a Json array to android AutocompleteTextView in Form (Registration form).
the Json array is showed in below
{"Status":true,"errorType":null,"InstituteList":[{"InstituteID":"1","InstituteName":"Demo Institute"},{"InstituteID":"16","InstituteName":"Sheridan College"},{"InstituteID":"17","InstituteName":"iCent Prosp"},{"InstituteID":"18","InstituteName":"Seneca College"}]}
here the Type Institution Name is the auto completeTextView. The main requirement is that, I can bind the values like in the Json response InstituteName on the front end and When click on the Submit Button it needs to take the InstituteID Object.
Currently I can bind the InstituteName Object to AutocompleteTextView and Working fine.
But the Submit Action was not performing perfectly.
I cant getting the InstituteID in my codes for performing
Here is my code.
Getting response from web service as json array and binding in asyncTask.
#Override
protected void onPostExecute(String res) {
try
{
Log.i("Intitute List",res);
JSONObject responseObject = new JSONObject(res);
String status=responseObject.getString("Status");
ArrayList<String> listInstituteNames = new ArrayList<>();
JSONArray detailsArray = responseObject.getJSONArray("InstituteList");
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i);
listInstituteNames.add(obj.getString("InstituteName"));
}
//Log.i("InstituteName", String.valueOf(listInstituteNames));
myStringArray = listInstituteNames;
AutoCompleteAdapter adapter = new AutoCompleteAdapter(SignUpActivity.this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, listInstituteNames);
autoTextView.setThreshold(1);
autoTextView.setAdapter(adapter);
}
catch (JSONException e1) {
e1.printStackTrace();
}
AutoCompleteAdapter.java
package Adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> fullList;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
public AutoCompleteAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
fullList = (ArrayList<String>) objects;
mOriginalValues = new ArrayList<String>(fullList);
}
#Override
public int getCount() {
return fullList.size();
}
#Override
public String getItem(int position) {
return fullList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
private Object lock;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (lock) {
mOriginalValues = new ArrayList<String>(fullList);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
ArrayList<String> list = new ArrayList<String>(mOriginalValues);
results.values = list;
results.count = list.size();
}
} else {
final String prefixString = prefix.toString().toLowerCase();
ArrayList<String> values = mOriginalValues;
int count = values.size();
ArrayList<String> newValues = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
String item = values.get(i);
if (item.toLowerCase().contains(prefixString)) {
newValues.add(item);
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results.values!=null){
fullList = (ArrayList<String>) results.values;
}else{
fullList = new ArrayList<String>();
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
AutoCompleteTextView Section in XML File..
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/autoCompt"
android:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/instname_field"
android:layout_width="match_parent"
android:hint="Type Institution Name"
android:paddingLeft="10dp"
android:textColor="#fff"
android:background="#b8d1e5"
android:layout_height="40dp"
android:textSize="20dp"
android:ems="10"/>
</LinearLayout>
How can I solve this Issue. Thanks.
You can see #blackBelt comment that is the right way to do that.
But here i am explain you another method which is easy to understand using Hashmap instead of Object class .
HashMap<String, String> map_name_value = new HashMap<String, Stirng>();
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i)
listInstituteNames.add(obj.getString("InstituteName"))
map_name_value.put(obj.getString("InstituteName"),obj.getString("InstituteID"));
}
Then while clicking the item.
Do this:
autoTextView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos,
long id) {
Editable message = autoTextView.getText();
String item_name = message.toString();
String item_id = map_name_value.get(item_name);
//your stuff
}
});
//item_name is name of institute
// item_id is id of institute
I am using Geocoder to fetch matching addresses from a String.
I am trying to display the returned addresses to an AutoCompleteTextView.
I can see the values properly when I Log.i("Result:"," "+list_of_addresses);
Since we are talking about dynamic list loading I am calling adapter.NotifyDataSetChanged();
I am using addTextChangedListener to listen to the changes in the text input by the user
This is what the code looks like
public class Map extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
final Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
final ArrayList<String> address_name = new ArrayList<String>();
final AutoCompleteTextView search = (AutoCompleteTextView) findViewById(R.id.search);
search.setThreshold(1);
final ArrayAdapter<String> adapter =new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,address_name);
search.setAdapter(adapter); //moved this line out of the try block
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
List<Address> list = null;
Address address = null;
try {
list = gc.getFromLocationName(s.toString(), 10);
Log.i("List:", ""+list); //CAN see this log
} catch (IOException e) {
e.printStackTrace();
}
for(int i=0; i<list.size(); i++){
address = list.get(i);
address_name.add(address.getFeatureName().toString());
Log.i("Address: ", address.getFeatureName().toString()); //CANto see this Log
}
if(!list.isEmpty()){
list.clear();
}
adapter.notifyDataSetChanged();
search.showDropDown();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
}
Inside the for loop I am unable to see the log.i("Addresses:",address.getFeatureName.toString());
But when i change the for loop condition to i<=list.size() I do get the Log output but the application forcecloses with this error java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
Maybe that's why I am unable to see the Address list?
EDIT: I changed the for loop condition to i<list.size() also added search.showDropDown() after notifying dataset changed.
Any help would be appreciated! Thankyou.
You seem to have a problem with getting it to work. I'll paste what works for me really well, only relevant sections for AutoComplete.
onCreate
pickUpAutoComplete = new AutoComplete(this, R.layout.pickupautocomplete);
pickUpAutoComplete.setNotifyOnChange(true);
locationText = (AutoCompleteTextView) findViewById(R.id.locationText);
locationText.setOnItemClickListener(this);
locationText.setOnFocusChangeListener(this);
locationText.setAdapter(pickUpAutoComplete);
layout xml
<AutoCompleteTextView
android:id="#+id/locationText"
style="#style/registerLargestTextSize"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_margin="10dp"
android:layout_weight="6"
android:background="#ffffff"
android:completionThreshold="3"
android:focusable="true"
android:gravity="center"
android:hint="home location"
android:lines="3"
android:maxLines="3"
android:minLines="3"
android:paddingBottom="3dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideOverlay"
android:textColor="#b2b2b2"
android:textStyle="bold" />
AutoComplete Class, Don't forget to replace your API KEY
public class AutoComplete extends ArrayAdapter<String> implements Filterable {
private static final String LOG_TAG = "carEgiri";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "**YOUR API KEY HERE**";
private ArrayList<String> resultList;
public AutoComplete(IPostAutoCompleteUIChange context,
int textViewResourceId) {
super((Context) context, textViewResourceId);
}
#Override
public int getCount() {
if (resultList == null)
return 0;
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
The problem is related to a wrong or empty override of adapter methods:
#Override
public UPorPackageItem getItem(int index) {
return mValues.get(index);
}
#Override
public int getCount() {
if (mValues == null)
return 0;
return mValues.size();
}
you must implement the above method.
It will works