我的代码有点问题。我有一个SearchView,它允许用户使用PHP和JSON从SQL数据库中搜索输入的值,以便将结果查看到RecyclerView。基本上,我使用Volley将我的Android应用程序连接到网络服务器。
问题在于我的搜索布局上有一个按钮,按下时会弹出一个日历,要求用户选择日期。当用户选择日期时,所选日期将显示在TextView中。但是,我希望日期显示在SearchView中。
以下是我的搜索类代码:
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private TextView tvDisplayDate;
//private DatePicker dpResult;
private Button btnChangeDate;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
SearchView searchView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDateOnView();
addListenerOnButton();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager)
MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
// Every time when you press search button on keypad an Activity is
recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.x.x/test/test-search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data
from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve
data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new
Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new
OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for
entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as
class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.datecodes =
json_data.getString("datecode");
fishData.names = json_data.getString("name");
fishData.emails = json_data.getString("email");
fishData.timecodes = json_data.getInt("timecode");
fishData.numbers = json_data.getInt("numbers");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView)
findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFish.setAdapter(mAdapter);
mRVFish.setLayoutManager(new
LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
// You to understand what actually error is and handle
it appropriately
Toast.makeText(MainActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
// display current date
public void setCurrentDateOnView() {
//getMenuInflater().inflate(R.menu.search_main, null);
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
//dpResult = (DatePicker) findViewById(R.id.dpResult);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1, if you want to
.append(year).append("")
.append(month<10?("0"+month):(month)).append("")
.append(day<10?("0"+day):(day)).append(""));
// set current date into datepicker
//dpResult.init(year, month, day, null);
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener,
year, month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new
StringBuilder().append(year).append("")
.append(month<10?("0"+month):(month)).append("")
.append(day<10?("0"+day):(day)).append(""));
// set selected date into datepicker also
//dpResult.init(year, month, day, null);
}
};
}
这是我的布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/fishPriceList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:layout_weight="1"
/>
<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="viewStart"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="?attr/editTextColor" />
<Button
android:id="@+id/btnChangeDate"
android:layout_width="175dp"
android:layout_height="wrap_content"
android:background="@color/bg_login"
android:text="Change Date"
android:textColor="@color/white" />
</LinearLayout>
查看容器的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="@+id/textFishName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Date"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:text="Number"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/colorAccent" />
<TextView
android:id="@+id/textSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textFishName"
android:layout_marginLeft="5dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#666" />
<TextView
android:id="@+id/TimeCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Time Code"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#666"
android:textSize="18sp"
android:layout_below="@+id/textType"
android:layout_alignParentStart="true" />
<TextView
android:id="@+id/textType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textSize"
android:layout_marginLeft="5dp"
android:text="Email"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#666" />
</RelativeLayout>
这是search_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".SearchResultsActivity">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
</menu>
此外,我似乎无法“按订购”搜索结果。搜索很好,它按预期工作。但问题是,我无法按照RecyclerView中的结果设置。