onclick按钮没有为api编辑文本字符串

时间:2016-12-01 04:13:58

标签: android api android-fragments onclicklistener

我正在使用API​​数据库开发卡路里应用程序。当用户单击搜索按钮时,它获取字符串,然后搜索数据库。由于某种原因,用户编辑文本“字符串”未被检索,因此无法搜索api数据库。当我进行调试时,我注意到字符串“”表示空。

再次感谢,api和android工作室的新手。

  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();
    foodET.isEmpty();
    FoodET.setText("");
    CalorieET.setText("");
    calorieET = ((EditText) 
   view.findViewById(R.id.caloriesEditText)).getText().toString();

   }







         @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:



            if (FoodET.getText().toString().equals(null) || 
           CalorieET.getText().toString().equals(null)||   
           CalorieET.getText().toString().equals("") || 
           CalorieET.getText().toString().equals("")){
                Toast.makeText(getActivity(), "Please enter information", 
           Toast.LENGTH_LONG).show();

                AlertDialog NotFound = new
                        AlertDialog.Builder(getContext()).create();
                NotFound.setTitle("Error");
                NotFound.setMessage("Food not found :(");
                NotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int 
                       which) {
                                dialog.dismiss();
                            }
                        });

            }
            else

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

}

2 个答案:

答案 0 :(得分:1)

当您执行AsyncTask

时,请改用这些值
FoodSearch search = new FoodSearch(foodET,  CalorieET );

创建视图时,以下值始终为空(在代码中不是必需的)。

getText

这就解释了为什么这不起作用

"file:///android_asset"

您应该始终尝试调用context.getResources().getAssets().open("fileName")以响应用户事件,以获取输入字段的最新值

我还建议你学习如何正确解析JSON数据(不要使用indexOf),或者到目前为止看看Retrofit库

答案 1 :(得分:1)

试试这个

case  R.id.SearchButton:
           String foodEtString=FoodET.getText().toString();
            FoodSearch search = new FoodSearch(foodEtString,  CalorieET );
            search.execute();
            break;

并在onCreate中添加此内容

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