我在android studio中有一个项目,它从在线数据库加载数据并将这些数据放在listview中。列表视图上方有一个EditText,我想在列表视图中搜索我在里面写的值。我试图让this tutorial适应我的但我得到很多错误和崩溃,我无法解决因为我是一个菜鸟。你能帮助我让教程适应我的项目吗?下面是没有搜索过滤器的代码。如果你想我可以上传我的尝试与错误。提前谢谢!
AllStudents.java:
public class AllStudents extends AppCompatActivity {
ListView StudentListView;
ProgressBar progressBar;
String HttpUrl = "http://sissy-nickels.000webhostapp.com/AllStudentData.php";
List<String> IdList = new ArrayList<>();
String LessonName;
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
String FinalJSonObject;
HashMap<String,String> ResultHash = new HashMap<>();
String ParseResult ;
List<Student> studentList;
@Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(AllStudents.this, AddStudent.class));
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allstudents);
StudentListView = (ListView)findViewById(R.id.listview2);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
LessonName = getIntent().getStringExtra("Lesson");
HttpWebCall(LessonName);
//Adding ListView Item click Listener.
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(AllStudents.this,SingleStudent.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
finish();
}
});
}
public void HttpWebCall(final String LessonName){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(AllStudents.this,"Loading Data",null,true,true);
}
@Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(AllStudents.this).execute();
}
@Override
protected String doInBackground(String... params) {
ResultHash.put("LessonName",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpUrl);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(LessonName);
}
// JSON parse class started from here.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Student student;
studentList = new ArrayList<Student>();
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
student = new Student();
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
student.StudentName = jsonObject.getString("Regnum").toString();
studentList.add(student);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
StudentListView.setVisibility(View.VISIBLE);
ListAdapter adapter = new ListAdapter(studentList, context);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}}
ListAdapter.java
public class ListAdapter extends BaseAdapter {
Context context;
List<Student> valueList=null;
public ListAdapter(List<Student> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
if(valueList==null){
valueList = new ArrayList<>();
}
}
@Override
public int getCount()
{
return this.valueList.size();
}
@Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem;
convertView = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInfiater.inflate(R.layout.listviewitem, null);
viewItem.TextViewStudentName = (TextView)convertView.findViewById(R.id.textView1);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.TextViewStudentName.setText(valueList.get(position).StudentName);
return convertView;
}}class ViewItem{ TextView TextViewStudentName;}
Student.java:
public class Student {
public String StudentName ;}
listview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient"
android:padding="15dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24dp" />
avtivity_allstudents.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_show_all_students"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.djale.login_register.AllStudents"
android:background="@drawable/gradient"
>
<EditText
android:id="@+id/search"
android:layout_width="250dp"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:background="#11000000"
android:ems="10"
android:drawableLeft="@drawable/ic_search_black_24dp"
android:hint=" Search by reg. number"
android:inputType="textPersonName"
android:textColorHint="@android:color/holo_blue_dark"
android:textSize="18sp" />
<ListView
android:id="@+id/listview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="@+id/search" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
/>
答案 0 :(得分:1)
你可以这样做:
search=(EditText)findviewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
searchList=new ArrayList<>();
for(studentList name: String){
if(name.toLowerCase().contains(editable.toString().toLowerCase())){
searchList.add(name);
}
}
//clear data in adapter
//add searchList to your adapter
}
});
答案 1 :(得分:0)
您可以将TextChangedListener
添加到搜索框(EditText
)。在onTextChanged()
中,过滤列表&amp;相应地更新ListView
。
在AllStudents.java
中,尝试进行以下更改:
public class AllStudents extends AppCompatActivity {
.....
@Override
protected void onCreate(Bundle savedInstanceState) {
....
StudentListView.setOnItemClickListener(...)
// add TextChangedListener to search box.
// It listens for user's entered text & filter students' list by name
EditText searchEditText = (EditText) findViewById(R.id.search);
searchEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
// when text is entered in search box, filter list by search text
@Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
filterStudents(cs);
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
// check student's name whether contain text entered in search box
private void filterStudents (CharSequence cs) {
List<Student> filteredList = new ArrayList<>();
if (TextUtils.isEmpty(cs)) {
// no text is entered for search, do nothing
return;
}
// build new student list which filtered by search text.
for (Student student : studentList) {
if (student.StudentName.contains(cs)) {
filteredList.add(student);
}
}
// show filtered list in listview
ListAdapter adapter = new ListAdapter(filteredList, this);
StudentListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}