如何获取每个活动的搜索操作栏?

时间:2013-06-30 03:12:37

标签: android android-activity android-actionbar android-search

我无法让我的搜索活动发挥作用。在堆栈上获得大量帮助后,我现在有一个带有操作栏的搜索活动,该操作栏可以执行搜索并向用户显示结果。

我的问题是,我根据我的帮助将所有功能写入一个类。现在我已经学到了很多东西,我意识到这不是最好的方法,我应该有自己的类,我不知道如何转移我的代码,轻松获取每个活动的操作栏,而无需添加所有代码对每一项活动。

以下是我的搜索活动目前的内容:

public class Search extends Activity implements OnQueryTextListener {

private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("logIN", "starting activity");
        setContentView(R.layout.activity_search);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
        searchView.setOnQueryTextListener(this);
        return true;
    }

    //get entered search and pop up a toast to show query entered
    public boolean onQueryTextSubmit (String query) {

        //toast query 
        Toast.makeText(this, "Searching for: " + query + "...", Toast.LENGTH_SHORT).show();

        //make json variables to fill

        // url to make request
        String url = "searchURLWillGoHere";



        try {
            query = URLEncoder.encode(query, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        String jsonUrl = url + query;



        //todo: get json 
        new ReadJSONResult().execute(jsonUrl);

        return false;
    }

    public class ReadJSONResult extends AsyncTask
    <String, Void, String> {
        protected String doInBackground(String... urls) {
            return readJSONFeed(urls[0]);
        }

        protected void onPostExecute(String result) {
            try {

                //start progress bar
                //requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  
                //setProgressBarIndeterminateVisibility(true);


                ///get 


                JSONObject json = new JSONObject(result);

                //acces listview
                lv = (ListView) findViewById(android.R.id.list);

                //make array list for beer
                final List<BeerData> beerList = new ArrayList<BeerData>();



                //get json items
                for(int i = 0; i < json.getJSONArray("data").length(); i++) {

                    String beerId = GetBeerDataFromJSON(i,"id", json);
                    String beerName = GetBeerDataFromJSON(i,"name", json);
                    String beerDescription = GetBeerDataFromJSON(i,"description" , json);
                    String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
                    String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
                    String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
                    String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
                    String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
                    String beerGlass = GetBeerGlassFromJSON(i, json );
                    String beerStyle = GetBeerStyleFromJSON(i,"name", json );
                    String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
                    String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
                    String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
                    String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
                    String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );

                    //get long and latt
                    String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
                    String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );

                    String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
                    String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);



                    //create beer object
                    BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
                            beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
                            beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);

                    //add beer to list
                    beerList.add(thisBeer);


                }

                //update listview
                BeerSearchAdapter adapter1 = new BeerSearchAdapter(Search.this ,R.layout.listview_item_row, beerList);
                lv.setAdapter(adapter1);


                //set up clicks
                lv.setOnItemClickListener(new OnItemClickListener() {    
                       @Override
                       public void onItemClick(AdapterView<?> arg0, View arg1,
                                                int arg2, long arg3) {
                              Intent i = new Intent(Search.this, BeerPage.class); 

                              BeerData beerInfo = beerList.get(arg2);


                              //Toast.makeText(MainActivity.this,  beerInfo.beerName, Toast.LENGTH_SHORT).show();

                              i.putExtra("myBeerObject",  beerInfo);   
                              i.setClass(Search.this, BeerPage.class);


                              startActivity(i); 



                       } 
                   });

                //end progress bar
                //setProgressBarIndeterminateVisibility(false);






            } catch (Exception e) {
                Log.d("ReadBeerDataTask", e.getLocalizedMessage());
            }          
        }
    }

    private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
        String whatIsTheKeyYouAreLookFor = whatToGet;
        int whereInTheJSONArrayForLoopIsTheData = position;
        String holder = "";
        try{
            holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;
    }


    //get icons
        private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
            String whatIsTheKeyYouAreLookFor = whatToGet;
            int whereInTheJSONArrayForLoopIsTheData = position;
            String holder = "";
            try{
                holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
            } catch (JSONException e) {
                holder = "N/A";
            }



            return holder;
        }

    //get icons
    private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
        String whatIsTheKeyYouAreLookFor = whatToGet;
        int whereInTheJSONArrayForLoopIsTheData = position;
        String holder = "";
        try{
            holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;
    }

    //get style information
        private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
            String whatIsTheKeyYouAreLookFor = whatToGet;
            int whereInTheJSONArrayForLoopIsTheData = position;
            String holder = "";
            try{
                holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);

            } catch (JSONException e) {
                holder = "N/A";
            }



            return holder;
        }

        //get location data
        private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
            String whatIsTheKeyYouAreLookFor = whatToGet;
            int whereInTheJSONArrayForLoopIsTheData = position;
            String holder = "";
            try{
                holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);

            } catch (JSONException e) {
                holder = "N/A";
            }



            return holder;
        }

    //get brewery information
        //get style information
                private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
                    String whatIsTheKeyYouAreLookFor = whatToGet;
                    int whereInTheJSONArrayForLoopIsTheData = position;
                    String holder = "";
                    try{
                        holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);

                    } catch (JSONException e) {
                        holder = "N/A";
                    }



                    return holder;
                }

    //get glass
    private String GetBeerGlassFromJSON(int position, JSONObject json ) {

        int whereInTheJSONArrayForLoopIsTheData = position;
        String holder = "";
        try{
            holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;
    }


    //gets the json from the inputed url
    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }        
        return stringBuilder.toString();
    }


    @Override
    public boolean onQueryTextChange(String newText) {
        // TODO Auto-generated method stub
        return false;
    }




}

更新:我在评论中提出了建议并使用了我的search.java并转到了我的beerPage并进行了扩展搜索:

public class BeerPage extends Search

我现在可以在BeerPage上进行搜索,但是当我尝试执行搜索时,它强制关闭此错误:

06-30 10:13:16.357: E/AndroidRuntime(22194): FATAL EXCEPTION: main
06-30 10:13:16.357: E/AndroidRuntime(22194): java.lang.NullPointerException: println needs a message
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.util.Log.println_native(Native Method)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.util.Log.d(Log.java:138)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at com.example.beerportfoliopro.Search$ReadJSONResult.onPostExecute(Search.java:196)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at com.example.beerportfoliopro.Search$ReadJSONResult.onPostExecute(Search.java:1)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.os.AsyncTask.finish(AsyncTask.java:631)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.os.Looper.loop(Looper.java:155)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at android.app.ActivityThread.main(ActivityThread.java:5536)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at java.lang.reflect.Method.invokeNative(Native Method)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at java.lang.reflect.Method.invoke(Method.java:511)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
06-30 10:13:16.357: E/AndroidRuntime(22194):    at dalvik.system.NativeStart.main(Native Method)

我认为问题是啤酒页面没有列表视图,但搜索页面确实如此。我可以将其更改为搜索页面以显示啤酒页面搜索的结果吗?

0 个答案:

没有答案