API没有显示食物卡路里的正确值

时间:2016-11-30 05:08:52

标签: android api android-fragments httpurlconnection urlconnection

我目前正在开发卡路里应用程序,用户输入食物并使用api食物数据库检索卡路里。出于某种原因,每次我输入食物时,它都会检索相同的值。我不确定为什么它会给我这个价值。

提前致谢。我是android studio和使用API​​的新手。

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:


            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();
                        }
                    });
            }
       }
     }


  }

0 个答案:

没有答案