Custom ListViews,ArrayLists,ArrayAdapters - android

I'm trying to build an Attendance Manager app for students and am using a custom ListView to display subject names and minimum attendance when tapped on.
These are the Issues I'm facing::
1) I want my first list item to be an "Add a subject item" and on tapping on that it goes to AddSubjectActivity and stores everything via SharedPreferences.
2)Once the submit button is pressed in the AddSubjectActivity i want the next list item to say "Tap to add a subject" and so on.
3) Basically ,suppose the ListView has 5 items, tapping on each item takes me to the AddSubject Activity, but information corresponding to the respective list Item being tapped is displayed in it.
This is my Code:
Class CustomAdapter
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(SecondActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
SecondActivity second=new SecondActivity();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView);
holder.img=(ImageView) rowView.findViewById(R.id.statsImageView);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
context.startActivity(new Intent(context, AddSubject.class));
}
});
return rowView;
}
}
SecondActivity: The Activity that contains the ListView
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle=getIntent().getExtras();
String fullNameFinal = bundle.getString("fullName");
String courseFinal = bundle.getString("course");
int avgAttendanceFinal= bundle.getInt("avgAttendance");
boolean logInStatusFinal = bundle.getBoolean("logInStatus");
nameTextView=(TextView)findViewById(R.id.nameTextView);
courseTextView=(TextView)findViewById(R.id.courseTextView);
nameTextView.setText(fullNameFinal);
courseTextView.setText(courseFinal);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
ListView lv;
Context context;
ArrayList prgmName;
int [] prgmImages={R.drawable.listblockgold,R.drawable.listblockindigo,R.drawable.listblocklime,R.drawable.listblockorange,R.drawable.listblockpink,R.drawable.listblockred,R.drawable.listblocksilver,R.drawable.listblocktan,R.drawable.listblockteal};
String [] prgmNameList={"Maths","P.Comm.","IOT","Operating Systems","Web Programming","DSP","PHP","Jquery","JavaScript"};
context=this;
lv=(ListView) findViewById(R.id.testListView);
lv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages));
`AddSubject Activity`
public class AddSubject extends AppCompatActivity {
//Buttons
Button missedMinus;
Button missedPlus;
//ButtonsEnd
//TextViews
TextView safeBunksNumber;
TextView missedLectures;
TextView totalLecturesTextView ;
TextView percentageTextView;
//TextViewsEnd
EditText missedLecturesTextView;
ProgressBar progressBar;
static String s= Integer.toString(10);
public void missedMinusClick(View view)
{
totalLecturesTextView=(TextView)findViewById(R.id.totalLecturesTextView);
int totalLectures= Integer.parseInt(totalLecturesTextView.getText().toString());
missedLecturesTextView=(EditText)findViewById(R.id.missedLecturesTextView);
int missedLectures= Integer.parseInt(missedLecturesTextView.getText().toString());
missedLecturesTextView.setText(Integer.toString(missedLectures-1));
safeBunksNumber=(TextView)findViewById(R.id.safeBunksNumber);
int safeBunksNumber;
}
public void missedPlusClick(View view2)
{
missedLecturesTextView=(EditText)findViewById(R.id.missedLecturesTextView);
int missedLectures= Integer.parseInt(missedLecturesTextView.getText().toString());
missedLecturesTextView.setText(Integer.toString(missedLectures+1));
}
public void submitOnClick1(View view3)
{
EditText subName = (EditText)findViewById(R.id.subName);
EditText totalLecturesTextView = (EditText)findViewById(R.id.totalLecturesTextView);
EditText missedLecturesTextView =(EditText)findViewById(R.id.missedLecturesTextView);
String subjectName = subName.getText().toString();
int totalLectures = Integer.parseInt(totalLecturesTextView.getText().toString());
int missedLectures = Integer.parseInt(missedLecturesTextView.getText().toString());
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.yashrandive.attendancemanager", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("subName",subjectName);
sharedPreferences.edit().putInt("totalLectures",totalLectures);
sharedPreferences.edit().putInt("missedLectures",missedLectures);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_subject);
}
}

Related

Delete row view from custom list using base Adapter solution

Hi I can not delete a row from list View i don't know how to delete it i search a lot from Internet i try out many examples but yet i can't solve the issue . when i click the hldr.delete button the complete row of list View delete from the list solution pls.
PlaceOrder Activity
public class PlaceOrder extends Activity {
String [] pIds;
String [] pNames;
String [] pPrizes;
static ListView lv;
ImageView bck;
String [] listImages;
String food_id;
String userdata[];
Intent i;
TextView totalprze;
float tprize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
lv=(ListView)findViewById(R.id.cart_list);
bck=(ImageView) findViewById(R.id.placeholder_bg_btn);
totalprze =(TextView) findViewById(R.id.place_order_price);
i=new Intent(this,Menu.class);
bck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle bundle=new Bundle();
//bundle.putStringArray("images", ListImages);
bundle.putString("food_id", food_id);
bundle.putStringArray("images", listImages);
bundle.putStringArray("userData",userdata);
i.putExtras(bundle);
startActivity(i);
}
});
if(this.getIntent().getExtras()!=null)
{
Bundle b=this.getIntent().getExtras();
pIds=b.getStringArray("pId");
pNames=b.getStringArray("PName");
pPrizes=b.getStringArray("pPrize");
userdata=b.getStringArray("userData");
tprize=b.getFloat("totalprize");
food_id=b.getString("food_id");
listImages=b.getStringArray("images");
String prz=Float.toString(tprize);
totalprze.setText("$"+prz);
lv.setAdapter(new cartAdapter(PlaceOrder.this, pIds, pNames, pPrizes,userdata));
pIds=null;
pNames=null;
pPrizes=null;
}
}
public void onBackPressed() {
pIds=null;
pNames=null;
pPrizes=null;
}
}
CartAdapter
public class cartAdapter extends BaseAdapter{
String [] pIdz;
String [] pNamz;
String [] pPrizs;
String [] userData;
// List<String> imges;
Context context;
// private ShopingCartHelper obj;
private static LayoutInflater inflater=null;
JSONArray jCat = null;
int count=0;
ProgressDialog pDialog;
public cartAdapter(PlaceOrder ctx,
String[] pIds,String[] pNams, String[] pprise,String [] userdata) {
pIdz=pIds;
pNamz=pNams;
context=ctx;
pPrizs=pprise;
userData=userdata;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
if(pIdz==null){
Toast.makeText(context, "There is issue with net connection.", Toast.LENGTH_LONG).show();
//Intent i=new Intent(context,WelcomeActivity.class);
//context.startActivity(i);
return count ;
}else{
return pIdz.length;
}
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class holder{
TextView pid;
TextView pname;
TextView pprise;
Button delete;
ListView lv;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final holder hldr=new holder();
View rowView = null;
Bitmap bitmap = null;
rowView = inflater.inflate(R.layout.place_order_item_list, null);
hldr.pid=(TextView) rowView.findViewById(R.id.item_id);
hldr.pname=(TextView) rowView.findViewById(R.id.item_name);
hldr.pprise=(TextView) rowView.findViewById(R.id.item_price);
hldr.delete=(Button) rowView.findViewById(R.id.delete);
hldr.pid.setText(pIdz[position]);
hldr.pname.setText(pNamz[position]);
hldr.pprise.setText(pPrizs[position]);
/* convertView.setTag(hldr);
hldr.delete.setTag(hldr);*/
//
// Picasso.with(context).load(imgs[position]).into(hldr.img);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// rowView.remove(position); //removing from your List
//Toast.makeText(context, "Delete",Toast.LENGTH_LONG).show();
int pid=Integer.parseInt(hldr.pid.getText().toString());
//Toast.makeText(context, "pid"+pid, Toast.LENGTH_LONG).show();
new ShopingCartHelper(context).delProduct(pid);
//PlaceOrder.lv.removeViewAt(position);
notifyDataSetChanged();
}
});
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// // TODO Auto-generated method stub
// cartAdapter.this.pIdz.remove[position];
// Toast.makeText(context, "hi",Toast.LENGTH_LONG).show();
}
});
return rowView;
// TODO Auto-generated method stub
}
}
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3. And if you want to delete from the listview the array which you are used should be dynamic(Adding & Deleting). So make the pIdz; pNamz;pPrizs;userData into some Modal Object, and prepare the list of Modal Objects and pass it to adapter and make the life easier
You'd be better off with a List, e.g. an ArrayList:
hldr.delete.setTag(position);
hldr.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position = (int)v.getTag();
list.remove(position);
notifyDataSetChanged();
}
});
First.
You should make a object that stores all your different strings instead of using multiple arrays for each value.
Ej:
class MyClass
{
String id;
String name
String price;
public MyClass(String id, String name, String price)
{
this.id = id;
this.name = name;
this.price = price;
}
}
That way you wouldnt have to delete the position of each of the arrays.
And finally to answer your question, just delete the value of position you want to delete for each of the arrays.
Since they are Array and not ArrayList you will need to recreate it with the correct new dimension (Note it will be much easier with ArrayList).
Then just call notifyDataSetChanged() on your Adapter class.
Hope this helps.

How to update values in database using an update image button in custom list adapter?

This is my custom list adapter. I want to update the values in table using the update ImageButton in the list. On clicking it, the old values should be shown in a new activity and then the edited value must be stored in the database. However, I am unable to pass an intent inside the onClick() method.
Please suggest me a solution
public class CustomListAdapter extends BaseAdapter implements ListAdapter
{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
OnItemSelectedListener onItemSelectedListener;
public int pos;
String pass,pass2,edit,epass;
public CustomListAdapter(List list, Context context) {
this.list = (ArrayList<String>) list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
//pass2 = list.toString();
return list.get(pos);
}
//#Override
//public Long getItemId(int pos) {
//
// //just return 0 if your list items do not have an Id variable.
//}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_custom_list, null);
}
//Handle TextView and display string from your list
final TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
ImageButton editBtn = (ImageButton)view.findViewById(R.id.edit_btn);
//Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position);
pass = listItemText.getText().toString();
notifyDataSetChanged();
pass2 = pass.substring(0,pass.indexOf(' '));
System.out.println(pass2);
Moneydb.delete(pass2);
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
edit=listItemText.getText().toString();
epass = listItemText.getText().toString();
edit = epass.substring(0,epass.indexOf(' '));
Moneydb.edit(edit);
}
});
return view;
}
protected Context getContext() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return list.get(position).getId();
return 0;
}
public void clear() {
//CustomListAdapter collection = null;
// TODO Auto-generated method stub
list.clear();
notifyDataSetChanged();
}
I suggest you to assign and ContextMenu to your list view with two MenuItem, Edit and Delete and write associated code outside of adapter
or you can start Activity by :
Intent new_intent = new Intent(v.getRootView().getContext(),edit_activity.class);
new_intent.putExtra("Key","Value");
v.getRootView().getContext().startActivity(new_intent);
i think the first method is best ;)

How to set radiobutton unchecked in adapter class

I have a customdialog box ,in this i have a listview and a spinner item.The listview contains textview and a radio button in each row.I can select only one row at a time with the help of radio buttons.This is happening.
Problem is coming when i select spinner items and then i select radio button ,the previous radio button is still selected.Now what i want when i select spinner items ,the previously selected radiobuttons should be unchecked.
Note:my spinner is in Main class and radio button is in CustomAdapterClass which i am calling in my Main class
Here is my code: Adapter Class:
public class APTRequestCustomAdapter extends BaseAdapter{
Context context;
ArrayList<APTRequestCustomdetails> APTRequestCustomitems;
private static String display_aptstatus1="";
public static String adapterbookingid="";
private boolean userSelected = false;
public static RadioButton mCurrentlyCheckedRB;
String patientid1="";
public static String from2="";
public static String to2="";
public static String testing2="";
public static String cancelbookid="";
public static String radiostring="";
public static String troubleradiobutton="";
private int selectedItemIndex=-1;
public APTRequestCustomAdapter(Context context,
ArrayList<APTRequestCustomdetails> aPTRequestCustomitems) {
super();
this.context = context;
this.APTRequestCustomitems = aPTRequestCustomitems;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return APTRequestCustomitems.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return APTRequestCustomitems.get(arg0);
}
#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;
final int pos=position;
if(v==null){
v = LayoutInflater.from(context).inflate(R.layout.backupcustomdailoguniversalappointment,null);
}
TextView patientname=(TextView)v.findViewById(R.id.txtpatientname);
TextView tag=(TextView)v.findViewById(R.id.txttype);
TextView phone=(TextView)v.findViewById(R.id.txtphone);
TextView age=(TextView)v.findViewById(R.id.txtage);
TextView Apptstatus=(TextView) v.findViewById(R.id.txtapptstatus);
TextView bookid=(TextView) v.findViewById(R.id.txtbookingid);
ImageView remove=(ImageView)v.findViewById(R.id.txtremove);
RadioButton radio=(RadioButton)v.findViewById(R.id.txtRadiobutton);
patientname.setPaintFlags(patientname.getPaintFlags() |Paint.UNDERLINE_TEXT_FLAG);
patientname.setText(APTRequestCustomitems.get(position).getPatient_Name());
tag.setText(APTRequestCustomitems.get(position).getTag());
phone.setText(APTRequestCustomitems.get(position).getPhone());
age.setText(APTRequestCustomitems.get(position).getAge());
Apptstatus.setText(APTRequestCustomitems.get(position).getAppointmentstatus());
bookid.setText(APTRequestCustomitems.get(position).getBookingId());
Apptstatus.setVisibility(View.INVISIBLE);
bookid.setVisibility(View.INVISIBLE);
//APT_CustomRequestResponse.radiostring="";
// adapterbookingid=APTRequestCustomitems.get(pos).getBookingId().toString();// wrong code
patientname.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("Hello buddy");
Intent io=new Intent(context, PatientSummaryActivity.class);
DoctorGlobal.patid=APTRequestCustomitems.get(pos).getPatient_ID();
DoctorGlobal.patname=APTRequestCustomitems.get(pos).getPatient_Name();
System.out.println("PATID"+DoctorGlobal.patid);
context.startActivity(io);
}
});
if (position==getCount()-1 && userSelected==false) {
// radio.setChecked(true);
mCurrentlyCheckedRB = radio;
} else {
radio.setChecked(false);
}
if(APTRequestCustomitems.get(position).getAppointmentstatus().equals("1")){
remove.setVisibility(View.INVISIBLE);
radio.setVisibility(View.INVISIBLE);
v.setBackgroundColor(Color.parseColor("#1569C7"));
}else
{
v.setBackgroundColor(Color.parseColor("#FFFFFF"));
remove.setVisibility(View.VISIBLE);
radio.setVisibility(View.VISIBLE);
radio.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
APTRequestCustomAdapter.radiostring="checkedtrue";
if (mCurrentlyCheckedRB !=null) {
if (mCurrentlyCheckedRB ==null)
mCurrentlyCheckedRB = (RadioButton) v;
mCurrentlyCheckedRB.setChecked(true);
// Toast.makeText(context, ""+pos, Toast.LENGTH_LONG).show();
adapterbookingid=APTRequestCustomitems.get(pos).getBookingId().toString();
}
if (mCurrentlyCheckedRB == v)
return;
mCurrentlyCheckedRB.setChecked(false);
((RadioButton) v).setChecked(true);
mCurrentlyCheckedRB = (RadioButton) v;
}
});
}
return v;
}
}
And this is the code where i am calling the adapter class:
This method is in Async Class on PostExecute()method
public void showCustomDialog() {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
List<String> list=new ArrayList<String>();
list.add("Normal");
list.add("Low");
list.add("High");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.customdialoguniversalappointment);
ListView listcustomuniversalappt=(ListView) dialog.findViewById(R.id.listcustomuniversalappt);
LinearLayout layoutsubject=(LinearLayout) dialog.findViewById(R.id.layoutsubject);
LinearLayout layoutappt=(LinearLayout) dialog.findViewById(R.id.layoutappt);
spinnerappt=(Spinner)dialog.findViewById(R.id.permissionspinner);
ImageView cancel=(ImageView)dialog.findViewById(R.id.imgcancel);
Button cancelappt=(Button)dialog.findViewById(R.id.btncancelappt);
Button confirmappt=(Button)dialog.findViewById(R.id.btnconfirmappt);
EditText subject=(EditText) dialog.findViewById(R.id.edtsubject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerappt.setAdapter(dataAdapter);
spinnerappt.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
selected_item=arg0.getItemAtPosition(arg2).toString();
APTRequestCustomAdapter.mCurrentlyCheckedRB.setChecked(false);//this line of code is not executing,the radio button remains checked in the view
if(APTRequestCustomAdapter.mCurrentlyCheckedRB.isChecked()){// this lines of codes are not executing even though the radio button is checked ,i don't know why
APTRequestCustomAdapter.mCurrentlyCheckedRB.setChecked(false);// And this line is also not executing
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
APTRequestCustomAdapter adap=new APTRequestCustomAdapter(context,run_custom_universal_apptdata());
listcustomuniversalappt.setAdapter(adap);
/*//runapptstatus_method();
listcustomuniversalappt.setChoiceMode(1);
/
dialog.show();
}
Try to use your Custom Adapter like,
public class MyRadioAdapter extends BaseAdapter
{
private Context mContext;
private ArrayList<Variation> mVariations;
private int mSelectedVariation;
public MyRadioAdapter(Context context, ArrayList<Variation> variations, int selectedVariation)
{
mContext = context;
mVariations = variations;
mSelectedVariation = selectedVariation;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
if(view==null)
{
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_radio_adapter_item, null);
}
final Variation variation = mVariations.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
RadioButton radio = (RadioButton) view.findViewById(R.id.radio);
name.setText(variation.getName());
if(position==mSelectedVariation) radio.setChecked(true);
else radio.setChecked(false);
view.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mSelectedVariation = position;
MyRadioAdapter.this.notifyDataSetChanged();
}
});
return view;
}
here Radio buttons are usually grouped by Radio Group.When one RadioButton within a group is selected, all others are automatically deselected.

save editbox values in the custom listview

am having a two editbox. the values enter in that has to placed in the custom listview its working fine for this...
but i want to save this values in the list view permanently.so that if the phones switches off and again run the app then the values have to be saved ..like phone contact number and name have to be saved..
here am ataching the code
public class Editcard extends Activity{
EditText cardname,cardDescription ;
MyApplication app;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editcredit);
app = ((MyApplication) getApplicationContext());
cardname =(EditText)findViewById(R.id.cardash);
cardDescription =(EditText)findViewById(R.id.editdescription);
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
app.carddata =cardname.getText().toString();
System.out.println("Gotcardname"+app.carddata);
app.descriptiondata =cardDescription.getText().toString();
System.out.println("gotDescription"+app.descriptiondata);
app.arryList.add(app.carddata);
app.arryList1.add(app.descriptiondata);
Intent saveIntent =new Intent(Editcard.this,Newcard.class);
startActivity(saveIntent);
}
});
}
}
public class MyApplication extends Application{
ArrayList<String> arryList = new ArrayList<String>();
ArrayList<String> arryList1 = new ArrayList<String>();
String carddata,descriptiondata,=null;
}
public class Newcard extends Activity {
MyAdapter adapter;
ListView listView;
LayoutInflater lay;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newcard);
app = ((MyApplication) getApplicationContext());
TextView newcard =(TextView)findViewById(R.id.newcard);
newcard.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent card = new Intent(Newcard.this,Editcreditcard.class);
startActivity(card);
}
});
listView = (ListView) findViewById(R.id.cardlist);
adapter =new MyAdapter(this, app.arryList,app.arryList1);
listView.setAdapter(adapter);
}
public class MyAdapter extends BaseAdapter {
Context context = null;
ArrayList<String> items= null;
ArrayList<String> items1= null;
public MyAdapter(Newcard newcard, ArrayList<String> items,
ArrayList<String> items1) {
// TODO Auto-generated constructor stub
this.items = items;
this.items1 = items1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items;
//return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View layout = null;
TextView produ = null;
TextView desc = null;
if (convertView == null) {
lay = LayoutInflater.from(getApplicationContext());
layout = lay.inflate(R.layout.customlist, null);
} else {
layout = convertView;
}
produ = (TextView) layout.findViewById(R.id.card);
produ.setText("" +app.arryList.get(position));
desc= (TextView) layout.findViewById(R.id.descrip);
desc.setText("" +app.arryList1.get(position));
return layout;
}
}
}
use can use SharedPreferences, that will save your values permanently, untill they are changed(by changing values in editbox) or user reinstall (clear data) application. Shared Preferences works like this
// save string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("some_key", string); // here string is the value you want to save
editor.commit();
// restore string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
string = settings.getString("some_key", "");

Android - EditText as search box doesn't work

I would like to enable search functionality to EditText. My requirement is like this:
when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the EditText, if again, I cleared the EditText and tried to type "co", then it should show the drop-down list "copy","come","cow"....
I want to enable this feature to my EditText view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
EditText ed;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText)findViewById(R.id.EditText1);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0, textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}
}
And this is my ListView Adapter
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;
}
}
I think an AutoCompleteTextView might be more suitable to implement this feature.
Check out this example to create your own Listener to check the values inside Edittext on key press event - How to implement your own Listener
Instead of extending BaseAdapter you extend ArrayAdapter. It implements the Filterable interface for you. In TextWatcher call getFilter().filter(text); method.
public void afterTextChanged(Editable s) {
listview.getAdapter().getFilter().filter(s);
}

Categories

Resources