【问题标题】:API Not Searching Food Database When Clicking The Search Button get error Permission denied单击搜索按钮时 API 未搜索食品数据库得到错误权限被拒绝
【发布时间】:2016-11-29 03:40:32
【问题描述】:

大家好,我正在开发一个卡路里应用程序,用户在该应用程序中单击搜索按钮,它应该从美国农业部食品成分数据库 API 中检索信息。出于某种原因,它没有做任何事情,我注意到我在 Logcat 中收到错误。

我是 Android 和 API 的新手。再次提前感谢..

logcat:

Here is the logcat Error I'm Getting

AddEntry.java

  public class AddEntry extends Fragment implements View.OnClickListener  {

  EditText FoodET,CalorieET;


  ImageButton Savebtn, Cancelbtn;
   Button searchbutton;

  String foodET,calorieET;


    //database
   private DatabaseHandler dba;


    public AddEntry() {
    // Required empty public constructor
   }


  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View myView = inflater.inflate(R.layout.fragment_add_entry, container, 
    false);
   Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
    Savebtn.setBackgroundColor(Color.TRANSPARENT);
    Savebtn.setOnClickListener(this);


    searchbutton = (Button) myView.findViewById(R.id.SearchButton);
    searchbutton.setOnClickListener(this);

    Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
    Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
    Cancelbtn.setOnClickListener(this);
    return myView;


   }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    FoodET= (EditText)view.findViewById(R.id.foodEditText);

    FoodET.setInputType(InputType.TYPE_CLASS_TEXT);

    CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
    CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);

    foodET = ((EditText) 
    view.findViewById(R.id.foodEditText)).getText().toString();
    calorieET = ((EditText) 
    view.findViewById(R.id.caloriesEditText)).getText().toString();

     }





   public void saveDataToDB (){

    Food food = new Food();

    String FoodName = FoodET.getText().toString().trim();
    String calString = CalorieET.getText().toString().trim();

    //convert the claories numbers to text

    if (!calString.equals("")) {

        int cal = Integer.parseInt(calString);


        food.setFoodName(FoodName);
        food.setCalories(cal);

        //call addFood method from the DatabaseHandler
        dba.addFood(food);
        dba.close();


        //clear the editTexts
        FoodET.setText("");
        CalorieET.setText("");

        //take the user to the next screen
        //

        ((appMain) getActivity()).loadSelection(0);
        ;
    }
    else
    {

        Toast.makeText(getActivity(), "Please enter information", 
         Toast.LENGTH_LONG).show();
    }

}

      @Override
      public void onClick(View v) {
    switch (v.getId()) {
        case  R.id.SearchButton:
            InputMethodManager inputManager = (InputMethodManager)

            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

            inputManager.hideSoftInputFromWindow( 
            getActivity().getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);


            FoodSearch search = new FoodSearch(foodET,CalorieET );

            search.execute();
            break;

        case R.id.SaveBtn:


            foodET = FoodET.getText().toString();
            calorieET=CalorieET.getText().toString();

            if (FoodET.getText().toString().equals(null) || 
            CalorieET.getText().toString().equals(null)||   
           CalorieET.getText().toString().equals("")){

                Toast.makeText(getActivity(), "Please enter information", 
             Toast.LENGTH_LONG).show();
            }


            ((appMain) getActivity()).loadSelection(0);


            break;


        case R.id.CancelBtn:

           // EditText descriptionET= 
         (EditText)getView().findViewById(R.id.foodEditText);
          //descriptionET.setText("");


            //EditText calorieET= 
           (EditText)getView().findViewById(R.id.caloriesEditText);

            //calorieET.setText("");

            ((appMain) getActivity()).loadSelection(0);

            break;
         }
               }

        @Override
        public void onDestroy() {
        super.onDestroy();

          }

          @Override
          public void onDetach() {
          super.onDetach();
           }




   private class FoodSearch extends AsyncTask<Void, Void, String> {
    String food;
    EditText calories;

    FoodSearch(String food, EditText calories){
        this.food = food;
        this.calories = calories;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            food = food.replaceAll(" ", "%20");
            URL url = new URL("http://api.nal.usda.gov/ndb/search/? 
         format=JSON&q=" + food 
        +"&max=1&offset=0&sort=r&api_
         key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
                    HttpURLConnection urlConnection = (HttpURLConnection)
                    url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new 
               InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();
                String result = stringBuilder.toString();
                if(result.contains("zero results")) {
                    String s = "empty";
                    return s;
                }
                JSONObject object = (JSONObject) new
                        JSONTokener(result).nextValue();
                JSONObject list = object.getJSONObject("list");
                JSONArray items = list.getJSONArray("item");
                String item = items.get(0).toString();
                int i = item.indexOf("ndbno\":\"") + 8;
                int f = item.indexOf("\"", i);
                String ndbno = item.substring(i,f);
                Log.d("DEBUG", ndbno);

                URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
                 ndbno="+ ndbno +"&type=b&format=JSON&api_
                key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
                HttpURLConnection urlConnection2 = (HttpURLConnection)
                        url2.openConnection();
                BufferedReader bufferedReader2 = new BufferedReader(new
                        InputStreamReader(urlConnection2.getInputStream()));
                StringBuilder stringBuilder2 = new StringBuilder();
                String line2;
                while ((line2 = bufferedReader2.readLine()) != null) {
                    stringBuilder2.append(line2).append("\n");
                }
                bufferedReader2.close();
                String res = stringBuilder2.toString();
                int index = res.indexOf("\"unit\": \"kcal\",") + 46;
                int index2 = res.indexOf("\"", index);
                String calories = res.substring(index,index2);
                urlConnection2.disconnect();
                return calories;
            }
            finally{
                urlConnection.disconnect();
            }

        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            String s = "empty";
            return s;
        }
    }
    protected void onPostExecute(String response) {
        if(!response.isEmpty() && !response.equals("empty")) {
            calories.setText(response);
        } else {
            AlertDialog foodNotFound = new
                    AlertDialog.Builder(getContext()).create();
            foodNotFound.setTitle("Error");
            foodNotFound.setMessage("Food not found :(");
            foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int  
                       which) {
                            dialog.dismiss();
                        }
                    });
                  }
               }
            }

          }

【问题讨论】:

    标签: java android android-fragments android-asynctask httpurlconnection


    【解决方案1】:

    您可以在同一类中调用异步任务,并在 onPost 执行部分中显示警报对话框

    public class AddEntry extends Fragment implements View.OnClickListener {
    
    EditText DescriptionET,CalorieET; ImageButton Savebtn, Cancelbtn; Button searchbutton; String description , calorieAmt; //database 
    private DatabaseHandler dba;
    
    public AddEntry() { 
        // Required empty public constructor 
    }
    
    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) { // Inflate the layout for this fragment View myView = inflater.inflate(R.layout.fragment_add_entry, container, false);
           Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
           Savebtn.setBackgroundColor(Color.TRANSPARENT);
           Savebtn.setOnClickListener(this);
    
    
           searchbutton = (Button) myView.findViewById(R.id.SearchButton);
           searchbutton.setOnClickListener(this);
    
           Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
           Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
           Cancelbtn.setOnClickListener(this);
           return myView;
    
            }
    
    
         @Override
         public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
    
        DescriptionET.setInputType(InputType.TYPE_CLASS_TEXT);
    
        CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
        CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
    
    
        //save to database:
    
    
    
        }
           public void saveDataToDB (){
    
           Food food = new Food();
    
        String name = DescriptionET.getText().toString().trim();
        String calString = CalorieET.getText().toString().trim();
    
        //convert the claories numbers to text
    
        if (!calString.equals("")) {
    
            int cal = Integer.parseInt(calString);
    
    
            food.setFoodName(name);
            food.setCalories(cal);
    
            //call addFood method from the DatabaseHandler
            dba.addFood(food);
            dba.close();
    
    
            //clear the editTexts
            DescriptionET.setText("");
            CalorieET.setText("");
    
            //take the user to the next screen
            //
    
            ((appMain) getActivity()).loadSelection(0);
            ;
            }
            else
            {
    
               Toast.makeText(getActivity(), "Please enter information",   
            Toast.LENGTH_LONG).show();
           }
    
          }
    
                 @Override
             public void onClick(View v) {
              switch (v.getId()) {
            case  R.id.SearchButton:
                InputMethodManager inputManager = (InputMethodManager)
    
                getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    
    
                inputManager.hideSoftInputFromWindow(  
    
                getActivity().getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    
                FoodSearch search = new FoodSearch(description,CalorieET);
                search.execute();
    
    
                break;
    
            case R.id.SaveBtn:
    
    
                description = DescriptionET.getText().toString();
                calorieAmt=CalorieET.getText().toString();
    
                if (DescriptionET.getText().toString().equals(null) || 
               CalorieET.getText().toString().equals(null)|| 
              CalorieET.getText().toString().equals("")){
    
                    Toast.makeText(getActivity(), "Please enter information", 
                Toast.LENGTH_LONG).show();
                }
    
    
                ((appMain) getActivity()).loadSelection(0);
    
    
                break;
    
    
            case R.id.CancelBtn:
    
    
               // EditText descriptionET= 
             (EditText)getView().findViewById(R.id.foodEditText);
              //descriptionET.setText("");
    
    
                //EditText calorieET= 
             (EditText)getView().findViewById(R.id.caloriesEditText);
                //calorieET.setText("");
    
                ((appMain) getActivity()).loadSelection(0);
    
                break;
                 }
                }
    
    
                 @Override
                 public void onDestroy() {
                 super.onDestroy();
    
                  }
    
              @Override
              public void onDetach() {
              super.onDetach();
             }
    
          }
        private class FoodSearch extends AsyncTask<Void, Void, String>{
            String food;
            EditText calories;
    
            FoodSearch(String food, EditText calories){
               this.food = food;
               this.calories = calories;
             }
    
             @Override
             protected String doInBackground(Void... params) {
             try {
                food = food.replaceAll(" ", "%20");
                URL url = new URL("http://api.nal.usda.gov/ndb/search/?
                format=JSON&q=" + food +"&max=1&offset=0&sort=r&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
                HttpURLConnection urlConnection = (HttpURLConnection) 
              url.openConnection();
                try {
                    BufferedReader bufferedReader = new BufferedReader(new 
                    InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    bufferedReader.close();
                    String result = stringBuilder.toString();
                    if(result.contains("zero results")) {
                        String s = "empty";
                        return s;
                    }
                    JSONObject object = (JSONObject) new 
                    JSONTokener(result).nextValue();
                    JSONObject list = object.getJSONObject("list");
                    JSONArray items = list.getJSONArray("item");
                    String item = items.get(0).toString();
                    int i = item.indexOf("ndbno\":\"") + 8;
                    int f = item.indexOf("\"", i);
                    String ndbno = item.substring(i,f);
                    Log.d("DEBUG", ndbno);
    
                    URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?ndbno="+ ndbno +"&type=b&format=JSON&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
                    HttpURLConnection urlConnection2 = (HttpURLConnection) 
                    url2.openConnection();
                    BufferedReader bufferedReader2 = new BufferedReader(new 
                    InputStreamReader(urlConnection2.getInputStream()));
                    StringBuilder stringBuilder2 = new StringBuilder();
                    String line2;
                    while ((line2 = bufferedReader2.readLine()) != null) {
                        stringBuilder2.append(line2).append("\n");
                    }
                    bufferedReader2.close();
                    String res = stringBuilder2.toString();
                    int index = res.indexOf("\"unit\": \"kcal\",") + 46;
                    int index2 = res.indexOf("\"", index);
                    String calories = res.substring(index,index2);
                    urlConnection2.disconnect();
                    return calories;
                }
            finally{
                urlConnection.disconnect();
            }
    
        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            String s = "empty";
            return s;
            }
         }
        protected void onPostExecute(String response) {
            if(!response.isEmpty() && !response.equals("empty")) {
                calories.setText(response);
            } else {
                AlertDialog foodNotFound = new 
                AlertDialog.Builder(getContext()).create();
                foodNotFound.setTitle("Error");
                foodNotFound.setMessage("Food not found :(");
                foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                }
            }
        }
    

    【讨论】:

    • 我尝试按照您提供的代码并将其放在课堂上,但是这样做时,这行代码是红色的 ("api.nal.usda.gov/ndb/search?format=JSON&q=" + food +"&max=1&offset= 0&sort=r&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");和 urlConnection
    • 对不起,这行出错了 getInputStream 说无法获取方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多