Listview viewholder and image - android

Everybody. I've tried to use a viewholder adapter, but I couldn't understand and my app stopped working. I need some help. I read some blogs that explained this. No success.
This is my code below and I just want how to modify this using a viewholder adapter or something else to my listview works fine with no lag. I'm more visua and if someone gives an example using my code, I'll appreciate for this. P.S: My Listview has more than 100 items, but I just reduced here to clarify and facilitate the view of my code.
public class Listagem extends Activity {
EditText edittext;
ListView listview;
String[] text;
String[] text2;
int[] image = {
R.drawable.wolf;
R.drawable.cat;
};
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<String> text2_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
text = getResources().getStringArray(R.array.text);
text2 = getResources().getStringArray(R.array.text2);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
if ("Howl".equals(text[position])) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.howl);
player.start();
}
if ("Meow".equals(text[position])) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.meow);
player.start();
}
}
});
listview.setAdapter(new MyCustomAdapter(text, text2, image));
edittext.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 = edittext.getText().length();
text_sort.clear();
text2_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++) {
if (textlength <= text[i].length()) {
if (edittext.getText().toString().equalsIgnoreCase((String) text[i].subSequence(0, textlength))) {
text_sort.add(text[i]);
text2_sort.add(text2[i]);
image_sort.add(image[i]);
}
}
}
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
if ("Howl".equals(text_sort.get(position))) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.howl);
player.start();
}
if ("Meow".equals(text_sort.get(position))) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.meow);
player.start();
}
}
});
listview.setAdapter(new MyCustomAdapter(text_sort, text2_sort, image_sort));
}
});
}
class MyCustomAdapter extends BaseAdapter {
String[] data_text;
String[] data_text2;
int[] data_image;
MyCustomAdapter() {
}
MyCustomAdapter(String[] text, String[] text2, int[] image) {
data_text = text;
data_text2 = text2;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<String> text2, ArrayList<Integer> image) {
data_text = new String[text.size()];
data_text2 = new String[text2.size()];
data_image = new int[image.size()];
for(int i=0;i<text.size();i++) {
data_text[i] = text.get(i);
data_text2[i] = text2.get(i);
data_image[i] = image.get(i);
}
}
public int getCount() {
return data_text.length;
}
public String getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
listview.setCacheColorHint(Color.TRANSPARENT);
listview.setFastScrollEnabled(true);
listview.setScrollingCacheEnabled(false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
TextView textview2 = (TextView) row.findViewById(R.id.TextView02);
Typeface font1 = Typeface.createFromAsset(getAssets(), "arial.ttf");
textview2.setTypeface(font1);
ImageView imageview = (ImageView) row.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
textview2.setText(data_text2[position]);
imageview.setImageResource(data_image[position]);
return row;
}
}
}

Your getView() method is wrong. It doesn't recycle views. That is the first problem you have to fix. Then if you want to improve the performance of the method by using the ViewHolder design pattern have a look to this tutorial
And please, follow the advises given to you in the above comments.

Related

Listview search does not show search results

First, please bear with me as I am just a beginner in learning Android.
What I want is that when the user adds an item from another activity, the details will be shown from my listview in the MainActivity (I am using a regular expression for my search results). And when the user tries to search an item, I want the search results to show.
From my code below, only the added items are shown and the search results will not display.
Here is a snippet of my code from MainActivity.java
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.notifyDataSetChanged();
}//end if
}
//update the listview
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
Student.java
public class Student {
Uri uriImage;
String studlname, studfname, studcourse;
//constructor
public Student(Uri uriImage, String studlname, String studfname, String studcourse) {
super();
this.uriImage = uriImage;
this.studlname = studlname;
this.studfname = studfname;
this.studcourse = studcourse;
}
//getters and setters
public Uri getUriImage() {
return uriImage;
}
public void setUriImage(Uri uriImage) {
this.uriImage = uriImage;
}
public String getStudlname() {
return studlname;
}
public void setStudlname(String studlname) {
this.studlname = studlname;
}
public String getStudfname() {
return studfname;
}
public void setStudfname(String studfname) {
this.studfname = studfname;
}
public String getStudcourse() {
return studcourse;
}
public void setStudcourse(String studcourse) {
this.studcourse = studcourse;
}
}
Update your code as below
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.refreshList(findlist)
}//end if
}
//update the listview
anotheradapter.refreshList(findlist)
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
Add refresh List method in adapter
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
public void refreshList(ArrayList<Student> list){
this.list = list;
notifyDataSetChanged()
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
You need to update your adapter initialization as below.
Update in the onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
// initialize the findlist to show all student list by default
findlist.addAll(studentArrayList);
anotheradapter = new CustomAdapter(this, findlist);
// ----- Remove these lines - as you don't need multiple adapters
//adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
//adapter.notifyDataSetChanged();
//lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
// Remove the below line as you don't need to update the list multipletimes
//anotheradapter.notifyDataSetChanged();
}
}
// Add these lines to show the list of all student when the searchbox is empty. This will reset the findList to initial state.
if (txtsearch.getText().length() == 0 && findlist.isEmpty()) {
findlist.addAll(studentArrayList);
}
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}

RecyclerView shows previous values entered in an EditText in new rows

I'm creating an android app, in which I'm using recyclerView and the row of recyclerView is having editText.
This is my ReadingAdapter class
public class ReadingAdapter extends RecyclerView.Adapter<ReadingAdapter.ViewHolder> implements AdapterView.OnItemSelectedListener {
Context context;
String valOpenReading, valClosReading, valConsumption;
private List<ReadingData> readingList;
static String[] arrValOpenRead, arrValClosRead, arrValConsumption;
public ReadingAdapter(Context context, List<ReadingData> readingList) {
this.context = context;
this.readingList = readingList;
arrValOpenRead = new String[readingList.size()];
arrValClosRead = new String[readingList.size()];
arrValConsumption = new String[readingList.size()];
}
#Override
public ReadingAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reading_sheet_layout, parent, false);
return new ReadingAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final ReadingAdapter.ViewHolder holder, final int position) {
ReadingData tempData = readingList.get(position);
holder.pdtName.setText(tempData.pdtName);
holder.keyId.setText("Key "+tempData.keyId);
holder.etClosRead.addTextChangedListener(new TextWatcher() {
boolean ignore = false;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (ignore)
return;
ignore = true;
valOpenReading = holder.etOpenRead.getText().toString();
arrValOpenRead[position] = valOpenReading;
valClosReading = s.toString().equals("") ? "0": s.toString();
arrValClosRead[position] = valClosReading;
if (!valOpenReading.equals("")) {
if (Integer.parseInt(valClosReading) < Integer.parseInt(valOpenReading)) {
Toast.makeText(context, "Check once! closing reading should be more than opening reading!", Toast.LENGTH_LONG).show();
valConsumption = "0";
holder.consumption.setText("");
} else {
valConsumption = (Integer.parseInt(valClosReading) - Integer.parseInt(valOpenReading))+"";
arrValConsumption[position] = valConsumption;
holder.consumption.setText(valConsumption);
}
} else
Toast.makeText(context, "Please fill the opening reading!", Toast.LENGTH_SHORT).show();
ignore = false;
}
});
}
#Override
public int getItemCount() {
return readingList.size();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView pdtName, keyId, consumption;
EditText etOpenRead, etClosRead;
public ViewHolder(View view) {
super(view);
pdtName = (TextView)view.findViewById(R.id.txt_list_pdt_supp);
keyId = (TextView)view.findViewById(R.id.key_set);
etOpenRead = (EditText)view.findViewById(R.id.open_val_set);
etClosRead = (EditText)view.findViewById(R.id.clos_val_set);
consumption = (TextView)view.findViewById(R.id.consumption_val);
}
}
}
This is my ReadingData.java
public class ReadingData {
String pdtName, keyId, openReading, closReading, consumption;
public ReadingData(String pdtName, String keyId) {
this.pdtName = pdtName;
this.keyId = keyId;
}
}
Here, if I enter value in the starting items of the recyclerView then as I scroll up the items to the bottom of the list, the last item will have that value.
Please ignore the quality of image as we can't upload above of 2MiB of snap.
Here the views are recycled as the list is scrolled. How to prevent the copying values to the other item in the list.
And that Toast is also repeated several times. How to stop this.
update:
By the suggetion of LQ Gioan through the SO question How ListView's recycling mechanism works , I got the logic how ListView actually works with recycling of views.
But I'm not sure whether the recyclerView also works same.
But here in my case, how can I implement this process. pls someone help me here.
RecyclerView reuse views, in fact it only generate the as many as views that is visible on the screen. so it's expected if you can see a value you set for other rows
The solution would be set all attributes of the view that you are changing to default or whatever the row should present from your data set
So put addTextChangedListener insode ViewHolder constructor(you can get position by calling getAdapterPosition()) for better performance and set the editText value inside onBindViewHolder method from your data set
Your Activity Code:
ListView listview = (ListView) findViewById(R.id.list_view);
listview.setItemsCanFocus(true);
Adapter adapter = new Adapter (YourActivity.this, YourArrayList);
listview .setAdapter(adapter);
Adapter class
public class Adapter extends BaseAdapter {
// Declare Variables \\
Context mContext;
LayoutInflater inflater;
Activity act;
String[] temp;
public Adapter(Context context, ArrayList<String> list) {
mContext = context;
inflater = LayoutInflater.from(mContext);
act = (Activity) context;
//-------Temp String Array-------\\
temp = new String[this.count];
for (int i = 0; i < this.count; i++) {
temp[i] = list.get(i);
}
//---------------------------\\
}
public class ViewHolder {
TextView optionTitle;
EditText optionText;
int ref;
}
#Override
public int getCount() {
return list.size;
}
#Override
public Object getItem(int position) {
return temp[position];
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.lv_items_add_ques_options_mcq, null);
holder.optionTitle = (TextView) view.findViewById(R.id.add_ques_opts_count_mcq_tv);
holder.optionText = (EditText) view.findViewById(R.id.add_ques_opts_title_mcq_et);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.ref = position;
holder.optionTitle.setText(getCharForNumber(position) + ":");
holder.optionText.setText(temp[position]);
holder.optionText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
temp[holder.ref] = arg0.toString().trim();
}
});
return view;
}
public void getList() {
StaticValues.arrayListOptions = new ArrayList<String>(Arrays.asList(temp));
StaticValues.arrayListOptionsCount = new ArrayList<String>();
for (int i = 0; i < count; i++) {
StaticValues.arrayListOptionsCount.add(String.valueOf(i+1));
Log.e("err_al", StaticValues.arrayListOptions.get(i));
Log.e("err_al", StaticValues.arrayListOptionsCount.get(i));
}
}
private String getCharForNumber(int i) {
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
if (i > 25) {
return null;
}
return Character.toString(alphabet[i]);
}}

Implement a getFilter() in ArrayAdapter android listview

In my list view have a four Text View and Images.
I want to set filter on txtcompany text view
I am trying to implement a getFilter() but it provide a wrong result
Please help me how can implement getFilter() in listview
List View ArrayAdapter source code
class Data extends ArrayAdapter
{
Button imageView;
TextView txtcompany;
TextView txtDesc;
TextView txtPosition;
TextView txtState;
TextView txtCity;
String[] companyarray;
String[] positonarray;
String[] cityarray;
String[] statearray;
String[] Descarray;
String[] contry;
String[] pass;
ArrayList<String> receiceValueOfAdapter=new ArrayList<String>(6);
ArrayList<String> time=new ArrayList<String>(6);
Context context;
Data(Context c, String[] company, String[] position, String[] city, String[] state,ArrayList<String> receiveValue, String[] Desc,ArrayList<String> time1,
String[] pass,String[] contry)
{
super(c,R.layout.list_item,R.id.txt_company,company);
this.context=c;
this.pass=pass;
this.companyarray=company;
this.positonarray=position;
this.cityarray=city;
this.statearray=state;
this.receiceValueOfAdapter=receiveValue;
this.Descarray=Desc;
this.time=time1;
this.contry=contry;
}
public View getView(int position, View convertView, ViewGroup parent) {
final String description;
String upperString="";
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View row;
row=mInflater.inflate(R.layout.list_item, parent,false);
txtcompany = (TextView) row.findViewById(R.id.txt_company);
imageView = (Button) row.findViewById(R.id.img);
//imageView.setVisibility(View.INVISIBLE);
txtPosition= (TextView) row.findViewById(R.id.txt_position);
txtCity= (TextView) row.findViewById(R.id.txt_city);
txtState= (TextView) row.findViewById(R.id.txt_state);
if(companyarray[position].toString().length()>0)
upperString = companyarray[position].substring(0,1).toUpperCase() + companyarray[position].substring(1);
txtcompany.setText(" "+upperString);
txtPosition.setText(" "+positonarray[position]);
Log.d("City",statearray[position]+"City "+cityarray[position]);
if(cityarray[position].toString().length()==0)
{
txtCity.setText(statearray[position]);
}
if(statearray[position].toString().trim().length()==0)
{
txtCity.setText(" "+cityarray[position]);
}
if(statearray[position].toString().trim().length()<2 && cityarray[position].toString().trim().length()<2)
{
txtCity.setText(" "+contry[position]);
}
if(statearray[position].toString().trim().length()>=2 && cityarray[position].toString().trim().length()>=2)
{
txtCity.setText(" "+cityarray[position]+", "+statearray[position]);
}
txtState.setText(""+time.get(position));
imageView.setTag(receiceValueOfAdapter.get(position));
description= Descarray[position];
final int l=position;
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
// Toast.makeText(contect, ""+ txtPosition.getText().toString(), Toast.LENGTH_LONG).show();
try{
String strurl1=pass[l].trim();
String strurl= strurl1.trim();
if (!strurl.trim().startsWith("https://") && !strurl.trim().startsWith("http://")){
strurl = "http://"+ strurl;
}
Intent ii = new Intent(Intent.ACTION_VIEW);
ii.setData(null);
ii.setData(Uri.parse(strurl));
startActivity(ii);
}
catch(Exception e)
{
}
}
});
return row;
}
}
EditText change Listener java code
lstsearch.addTextChangedListener(new TextWatcher()
{
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
Main_listview.this.datadap.getFilter().filter(charSequence);
}
public void afterTextChanged(Editable editable)
{
}
});
You can create custom method like this.
public void filter(String charText,int flag)
{
if(flag==0){
charText = charText.toLowerCase(Locale.getDefault());
if (charText.length() == 0)
{
ListofDetails.addAll(arraylist);
}
else
{
for (ListofDetails wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText))
{
NewList.add(wp);
}
}
}
elseif
{
///do some code
}
}

AlertDialog selectedItem is null

I have code for ListwithImage list. But when i try to onclickItem shows with Dialog, but Dialog shows null. I implement onclickItemListener . I tried this code without image, Dialog shows selected list. But when i try with image, it won't work.
MyCode:
public class MainActivity extends Activity {
EditText edittext;
ListView listview;
String[] text = { "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten" };
int[] image = { R.drawable.one, R.drawable.two, R.drawable.three,
R.drawable.four, R.drawable.five, R.drawable.six, R.drawable.seven,
R.drawable.eight, R.drawable.nine, R.drawable.ten };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
edittext.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 = edittext.getText().length();
text_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++)
{
if (textlength <= text[i].length())
{
if (edittext.getText().toString().
equalsIgnoreCase((String) text[i].subSequence(0, textlength)))
{
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter
(text_sort, image_sort));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
// TODO Auto-generated method stub
listview.getItemAtPosition(position);
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setTitle("List");
adb.setMessage(" selected Item is="
+ listview.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
}
});
}
class MyCustomAdapter extends BaseAdapter
{
String[] data_text;
int[] data_image;
MyCustomAdapter()
{
}
MyCustomAdapter(String[] text, int[] image)
{
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Integer> image)
{
data_text = new String[text.size()];
data_image = new int[image.size()];
for(int i=0;i<text.size();i++)
{
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount()
{
return data_text.length;
}
public String getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) row
.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
}
your getting wrong values in Your Alert
wrong
+listview.getItemAtPosition(position));
right
adb.setMessage(" selected Item is="+text_sort.get(position).toString());
Try changing this:
adb.setMessage(" selected Item is= " + listview.getItemAtPosition(position));
To this:
adb.setMessage(" selected Item is= " + text_sort.get(position));

Custom font, typeface doesn't work

Hello, Everybody. This is my code below, I'm using a custom font (arial) in my app, but something is wrong about my code typeface, maybe I put it in a wrong position (you all see it at the end of the code) or I missed some detail. I don't know. So, check it out! I need some help!
public class Listagem extends Activity {
EditText edittext;
ListView listview;
String[] text;
String[] text2;
int[] image = {
R.drawable.wolf;
R.drawable.cat;
};
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<String> text2_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
text = getResources().getStringArray(R.array.text);
text2 = getResources().getStringArray(R.array.text2);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
if ("Howl".equals(text[position])) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.howl);
player.start();
}
if ("Meow".equals(text[position])) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.meow);
player.start();
}
}
});
listview.setAdapter(new MyCustomAdapter(text, text2, image));
edittext.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 = edittext.getText().length();
text_sort.clear();
text2_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++) {
if (textlength <= text[i].length()) {
if (edittext.getText().toString().equalsIgnoreCase((String) text[i].subSequence(0, textlength))) {
text_sort.add(text[i]);
text2_sort.add(text2[i]);
image_sort.add(image[i]);
}
}
}
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
if ("Howl".equals(text_sort.get(position))) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.howl);
player.start();
}
if ("Meow".equals(text_sort.get(position))) {
MediaPlayer player = MediaPlayer.create(Listagem.this, R.raw.meow);
player.start();
}
}
});
listview.setAdapter(new MyCustomAdapter(text_sort, text2_sort, image_sort));
}
});
}
class MyCustomAdapter extends BaseAdapter {
String[] data_text;
String[] data_text2;
int[] data_image;
MyCustomAdapter() {
}
MyCustomAdapter(String[] text, String[] text2, int[] image) {
data_text = text;
data_text2 = text2;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<String> text2, ArrayList<Integer> image) {
data_text = new String[text.size()];
data_text2 = new String[text2.size()];
data_image = new int[image.size()];
for(int i=0;i<text.size();i++) {
data_text[i] = text.get(i);
data_text2[i] = text2.get(i);
data_image[i] = image.get(i);
}
}
public int getCount() {
return data_text.length;
}
public String getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater mInflater = getLayoutInflater();
convertView = mInflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
holder.image = (ImageView) convertView.findViewById(R.id.ImageView01);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(data_text[position]);
holder.text2.setText(data_text2[position]);
holder.image.setImageResource(data_image[position]);
Typeface font1 = Typeface.createFromAsset(getAssets(), "arial.ttf");
TextView text2 = (TextView) findViewById(R.array.text2);text2.setTypeface(font1);
return convertView;
}
}
}
You can check this class
https://github.com/Neferetheka/Helper-Tools-for-Android/blob/master/FontManager.java
Then you just have to call the init method of the FontManager when your activity is created, and use the setTypeface method on your textviews

Categories

Resources