2016-12-01 42 views
1

我正在开发使用API​​数据库卡路里的应用程序。当用户点击搜索按钮时,它获取字符串,然后搜索数据库。出于某种原因,用户编辑文本“字符串”不被检索,因此无法搜索api数据库。当我进行调试时,我注意到字符串是“”意思是空的。的onclick按钮没有得到编辑的文本串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(); 
         } 
        }); 
      } 
     } 
    } 

} 
+0

顺便说'.equals(空)'是不是你如何检查,如果事情是零。并且getText或toString永远不会为这些对象返回null –

回答

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

我补充说,并得到错误应用公共无效saveDataToDB()崩溃 – TrEy

+0

显示java.lang.NullPointerException:试图调用虚拟方法android.text.Editable android.widget.EditText.getText() '在一个空ob – TrEy

+0

真棒!它的工作表现出它的价值!党的人你的生活品味 – TrEy

1

当你去执行的AsyncTask

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

当创建视图(而不是在你的代码需要)下面的值总是空使用这些值来代替。

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

所以这解释了为什么这个没有工作

FoodSearch search = new FoodSearch(foodET, CalorieET); 

您应尽量响应,以获得最新的输入值(一个或多个)来调用getText用户事件田

我还建议你学会如何正确地解析JSON数据(不使用的indexOf),或走那么远,看起来到改造图书馆

+0

这些值进入onclick方法。这些值是从我还没有使用 – TrEy