How to add TextWatcher to Activity in android

只愿长相守 提交于 2019-12-24 09:59:12

问题


I am very much new to android and trying to learn various techniques including Search bar using Edit Text options. I am currently parsing Twitter using JSON and storing it in a list activity. Also, implementing is the search bar using EditText option such that when a user enters anything it receives a new arraylist.But somehow it needs to get integrated with TextWatcher and ListActivity.

The actual error received : Create Constructor of TextWatcher. TwitterFeedAdapter has constructor as public TwitterFeedAdapter(Activity a, int textViewResourceId, ArrayList tweets) but when I get the search values back I use TwitterFeedAdapter as ArrayList but it needs to implement TextWatcher.

Any ideas how can I revert the way I am doing or any better help.

/**TwitterFeedActivity**/

public class TwitterFeedActivity extends Activity implements TextWatcher{

public Bitmap placeholder;

private EditText et;
private ListView listView;

private ArrayList<Tweet> tweets;
private ArrayList<Tweet> array_sort= new ArrayList<Tweet>();
int textLength = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tweets = getTweets("android", 1);

    listView = (ListView) findViewById(R.id.ListViewId);
    et = (EditText)findViewById(R.id.EditText01);

    listView.setAdapter(new TwitterFeedAdapter(this, R.layout.list_item, tweets));  

    et.addTextChangedListener(new TextWatcher()
    {

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
            textLength = et.getText().length();
            array_sort.clear();

            for (int i = 0; i < tweets.size(); i++)
            {
                if (textLength <= tweets.size())
                {
                    if(et.getText().toString().equalsIgnoreCase((String)((CharSequence) tweets.get(i)).subSequence(0,textLength)))
                        {
                         array_sort.add(tweets.get(i));
                         }
                    }
              }
                            /***** Error is here since TwitterFeedAdapter has Activity implemented for it *******/
            listView.setAdapter(new TwitterFeedAdapter(this, R.layout.list_item array_sort));
            }
        });

}

public ArrayList<Tweet> getTweets(String searchTerm, int page) {
    String searchUrl = "http://search.twitter.com/search.json?q=@" 
                        + searchTerm + "&rpp=100&page=" + page;

    ArrayList<Tweet> tweets = new ArrayList<Tweet>();

    HttpClient client = new  DefaultHttpClient();
    HttpGet get = new HttpGet(searchUrl);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String responseBody = null;
    try{
        responseBody = client.execute(get, responseHandler);

    }catch(Exception ex) {
        ex.printStackTrace();
    }

    JSONObject jsonObject = null;
    JSONParser parser=new JSONParser();

    try {
        Object obj = parser.parse(responseBody);
        jsonObject=(JSONObject)obj;

    }catch(Exception ex){
        Log.v("TEST","Exception: " + ex.getMessage());
    }

    JSONArray arr = null;

    try {
        Object j = jsonObject.get("results");
        arr = (JSONArray)j;
        System.out.println(arr + "Array");
    }catch(Exception ex){
        Log.v("TEST","Exception: " + ex.getMessage());
    }

    for(Object t : arr) {
        Tweet tweet = new Tweet(
                ((JSONObject)t).get("from_user").toString(),
                ((JSONObject)t).get("text").toString(),
                ((JSONObject)t).get("profile_image_url").toString()
                );
        tweets.add(tweet);
    }

    return tweets;
}   

/** Classes **/

public class Tweet {
    public String username;
    public String message;
    public String image_url;
    public Boolean usernameSet = false;
    public Boolean messageSet = false;
    public Boolean imageSet = false;
    public Bitmap avatar;

    public Tweet(String username, String message, String url) {
        this.username = username;
        this.message = message;
        this.image_url = url;
    }
}
 }

/**TwitterFeedAdapter.java****/

public class TwitterFeedAdapter extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
private Activity activity;
public ImageManager imageManager;

public TwitterFeedAdapter(Activity a, int textViewResourceId, ArrayList<Tweet> tweets) {
    super(a, textViewResourceId, tweets);
    this.tweets = tweets;
    activity = a;

    imageManager = new ImageManager(activity.getApplicationContext());
}

public static class ViewHolder{
    public TextView username;
    public TextView message;
    public ImageView image;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    ViewHolder holder;
    if (v == null) {        
        LayoutInflater vi = 
            (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.list_item, null);
        holder = new ViewHolder();
        holder.username = (TextView) v.findViewById(R.id.username);
        holder.message = (TextView) v.findViewById(R.id.message);
        holder.image = (ImageView) v.findViewById(R.id.avatar);
        v.setTag(holder);
    }
    else
        holder=(ViewHolder)v.getTag();

    final Tweet tweet = tweets.get(position);
    if (tweet != null) {
        holder.username.setText(tweet.username);
        holder.message.setText(tweet.message);
        holder.image.setTag(tweet.image_url);
        imageManager.displayImage(tweet.image_url, activity, holder.image);
    }
    return v;
}

}


回答1:


Where you are setting the adapter try changing this to TwitterFeedActivity.this as follows...

listView.setAdapter(new TwitterFeedAdapter(TwitterFeedActivity.this, R.layout.list_item, array_sort));

EDIT: Also your code is missing a comma between R.layout.list_item and array_sort. I've added it to my example above.




回答2:


Came across a similar issue trying to implement a TextWatcher

Simply needed to add

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}

Left them blank and it fixed my problem.



来源:https://stackoverflow.com/questions/8782701/how-to-add-textwatcher-to-activity-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!