1

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

我的问题是,我根据获得的帮助将所有功能都写到了一个类中。既然我学到了很多东西,我意识到这不是最好的方法,我应该为此开设自己的课程,并且不确定如何传输我的代码以轻松获取每个活动的操作栏而不添加所有代码到每一个活动。

这是我的搜索活动目前的样子:

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)

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

4

0 回答 0