我做了什么 ::
JSON
webservice
来实现显示数据
并将其填入listview
search-filter
根据文字搜索元素
图我遇到的问题 ::发布一系列解释我问题的快照
listview
列表中的一系列元素
carl
时,我的名字会被过滤,只会显示匹配的结果
整体 ::发生的事情一旦被过滤我就不能再用它了...我必须重新编译整个项目
ListOfContacts.java
public class ListOfContacts extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String FLAG = "flag";
EditText mEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
mEditText = (EditText) findViewById(R.id.inputSearch);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(ListOfContacts.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://URL");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(ListOfContacts.NAME, jsonobject.getString("Person_Name"));
map.put(ListOfContacts.FLAG, "http://54.218.73.244:7004/"+jsonobject.getString("Image_Name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mEditText = (EditText) findViewById(R.id.inputSearch);
mEditText.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)
{
ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =mEditText.getText().toString();
for (int i = 0; i < arraylist.size(); i++)
{
String currentString =arraylist.get(i).get(ListOfContacts.NAME);
if (searchString.equalsIgnoreCase(currentString))
{
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
listview.setAdapter(adapter);
}
});
mProgressDialog.dismiss();
}
}
}
DataAcceptActivity.java
public class DataAcceptActivity extends Activity {
Button submit;
Button display;
ProgressDialog pDialog;
InputStream is;
EditText name;
ImageView imageView;
EditText search;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
int[] image_array={R.drawable.index,R.drawable.image1,R.drawable.image5,R.drawable.image6,R.drawable.image7,R.drawable.image8,R.drawable.image9,R.drawable.image10};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
name = (EditText) findViewById(R.id.editText1);
imageView = (ImageView) findViewById(R.id.imageView1);
display=(Button) findViewById(R.id.DISPLAY_BUTTON_ID);
search=(EditText) findViewById(R.id.inputSearch);
display.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent searchIntent=new Intent(DataAcceptActivity.this,ListOfContacts.class);
startActivity(searchIntent);
}
});
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MainTest().execute();
}
});
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
imageView.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* Method to post the image to the server.
* U will have to change the url which will accept the image data.
* @throws IOException
*/
public void postImageData() {
try
{
Bitmap bitmapOrg = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://URL");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
reqEntity.addPart("key", bab);
reqEntity.addPart("key1", new StringBody(name.getText().toString()));
}
catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", new StringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
}catch(Exception e){
e.getStackTrace();
}
}
public class MainTest extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DataAcceptActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_SHORT).show();
}
}
class ImageAdapter extends BaseAdapter{
Context cxt;
public ImageAdapter(DataAcceptActivity dataAcceptActivity) {
// TODO Auto-generated constructor stub
this.cxt=dataAcceptActivity;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return image_array.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;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView ;
if(convertView==null){
imageView=new ImageView(cxt);
imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(15, 15, 15, 15);
}else{
imageView=(ImageView) convertView;
}
imageView.setImageResource(image_array[position]);
return imageView;
}
}
}
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String FLAG = "flag";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://URL");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));;
map.put(MainActivity.FLAG, "http://url"+jsonobject.getString("restaurantIMAGE"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
有关解决此问题的任何想法,谢谢
答案 0 :(得分:3)
只需为搜索字符串长度设置条件。
mEditText.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)
{
ArrayList<HashMap<String, String>> arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =mEditText.getText().toString().trim();
if(searchString.length()>0)
{
for (int i = 0; i < arraylist.size(); i++)
{
String currentString =arraylist.get(i).get(ListOfContacts.NAME);
if (searchString.equalsIgnoreCase(currentString))
{
arrayTemplist.add(arraylist.get(i));
}
}
adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
listview.setAdapter(adapter);
}
else
{
adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
listview.setAdapter(adapter);
}
}
});
答案 1 :(得分:1)
答案 2 :(得分:0)
On Text Change Listener使用本地值设置适配器: -
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
ArrayList<String> STOREID_SUB = new ArrayList<String>();
ArrayList<String> STORE_NAME_SUB = new ArrayList<String>();
ArrayList<String> PHOTO_SUB = new ArrayList<String>();
final ArrayList<String> STORE_DESC_SUB = new ArrayList<String>();
textlength = searchText.getText().length();
for (int i = 0; i < STORE_NAME.size(); i++)
{
if (textlength <= STORE_NAME.get(i).length())
{
if (searchText.getText().toString().
equalsIgnoreCase((String) STORE_NAME.get(i).subSequence(0, textlength)))
{
STORE_NAME_SUB.add(STORE_NAME.get(i));
STOREID_SUB.add(STOREID.get(i));
PHOTO_SUB.add(PHOTO.get(i));
STORE_DESC_SUB.add(STORE_DESC.get(i));
}
}
}
adapter=new StoreSearchListAdapter(context, R.drawable.ic_launcher, R.drawable.ic_launcher, STORE_NAME_SUB, PHOTO_SUB,STORE_DESC_SUB);
singlePlaceChooserList.setAdapter(adapter);
}
答案 3 :(得分:-1)
尝试以下代码
if(arraryTemplist.size()>0){
adapter = new ListViewAdapter(ListOfContacts.this, arrayTemplist);
listview.setAdapter(adapter);
}else{
adapter = new ListViewAdapter(ListOfContacts.this, arraylist);
listview.setAdapter(adapter);
}