TrEy TrEy - 8 days ago 8
Android Question

onclick button not getting edit text string for api

I'm developing a Calorie app using an API Database. When the user clicks the search button it gets the string and then searches the database. For some reason the user edit text "string" is not being retrieved therefore not being able to search the api database. When I did the debug I noticed that the string is "" meaning empty.

Thanks again so much, New to api and android studio.

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

}

Answer

Try this

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

And Add this in onCreate as well

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