Android中的Searchview不起作用

时间:2017-05-02 00:21:52

标签: java android xml android-layout searchview

我是java和android开发的新手,我一直在为一个学校项目的应用程序工作,我想要一个带有SearchView的操作栏。我已经查看了所有示例,但我无法让它工作。我已经搜索过,但没有任何帮助我来了。

问题是:我打开SearchView并输入我的搜索查询,但之后根本没有任何事情发生。

输入查询并点击搜索后,

我的pdLoading消息甚至没有显示。

那么你们有谁可以帮助我吗?这个项目对我来说非常重要。 所以这是我的代码:

提前致谢:D

search.java

package com.example.adek002319.brinkshopping;

import ...


public class search 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 searchapp mAdapter;

SearchView searchView = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
}

@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) search.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(getApplicationContext(), search.class)));
        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(search.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.1.5/Android/searchforapp.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<DataSearch> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(search.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);
                    DataSearch searchData = new DataSearch();
                    searchData.Productnaam = json_data.getString("productnaam");
                    searchData.Productprijs = json_data.getInt("productprijs");
                    searchData.Productretailer = json_data.getString("productretailer");
                    searchData.Description = json_data.getString("descripton");
                    data.add(searchData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.prijslijst);
                mAdapter = new searchapp(search.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(search.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(search.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(search.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}

activity_search.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>



<android.support.v7.widget.RecyclerView
        android:id="@+id/prijslijst"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="10dp"
        android:layout_weight="1"
        tools:ignore="InefficientWeight" />


</LinearLayout>

DataSearch.java

package com.example.adek002319.brinkshopping;

public class DataSearch {

public String Productnaam;
public int Productprijs;
public String Productretailer;
public String  Description;
}

searchapp.java

package com.example.adek002319.brinkshopping;

import ...

public class searchapp extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataSearch> data= Collections.emptyList();
DataSearch current;

// create constructor to initialize context and data sent from MainActivity
public searchapp(Context context, List<DataSearch> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.activity_search2, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataSearch current=data.get(position);
    myHolder.textProductnaam.setText(current.Productnaam);
    myHolder.textPrijs.setText("Prijs " + current.Productprijs);
    myHolder.textRetailer.setText("Retailer: " + current.Productretailer);
    myHolder.textDescription.setText("Description: " + current.Description);
    myHolder.textPrijs.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

@Override
public int getItemCount() {
    return data.size();
}


class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView textProductnaam;
    TextView textPrijs;
    TextView textRetailer;
    TextView textDescription;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        textProductnaam= (TextView) itemView.findViewById(R.id.textProductnaam);
        textPrijs = (TextView) itemView.findViewById(R.id.textPrijs);
        textRetailer = (TextView) itemView.findViewById(R.id.textRetailer);
        textDescription = (TextView) itemView.findViewById(R.id.textDescription);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
    }
}

activity_search2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_search2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.adek002319.brinkshopping.searchapp">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="fish name"
    android:id="@+id/textProductnaam"
    android:layout_marginLeft="5dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="price"
    android:id="@+id/textPrijs"
    android:textColor="@color/colorAccent"
    android:layout_alignParentRight="true"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Small Text"
    android:id="@+id/textDescription"
    android:layout_marginLeft="5dp"
    android:layout_below="@id/textProductnaam"
    android:textColor="#666"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="sd"
    android:id="@+id/textRetailer"
    android:layout_marginLeft="5dp"
    android:layout_below="@id/textDescription"
    android:textColor="#666"/>

AnroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.adek002319.brinkshopping">


<uses-permission android:name="android.permission.INTERNET"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">



    <activity android:name=".search" android:launchMode="singleTop"><intent-filter>
    <action android:name="android.intent.action.SEARCH" />
    <action android:name="android.intent.action.VIEW" />
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".search" />
</intent-filter></activity>
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable" />

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".recentitems" />
    <activity android:name=".FavoriteActivity" />

    <activity android:name=".searchapp"/> //i also get an error here that says searchapp has no default constuctor
</application>

0 个答案:

没有答案