I have a problem with this code. This is a tutorial code that show how to get and show data from mysql DB. But when I try to run it I am getting a problem window that application has stopped unexpectedly. Any ideas how to fix it?
public class FoodActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream input = null;
StringBuilder sbuilder = null;
ArrayList <NameValuePair> nameValuePairs = new ArrayList <NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("1","Avinas"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/~jbarzelis/Bandymas/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
input = entity.getContent();
}
catch(Exception e){
Log.e("log_tag","Error in internet connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(input,"iso-8859-1"),8);
sbuilder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sbuilder.append(line + "\n");
}
input.close();
result = sbuilder.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
int fd_id;
String fd_name;
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id = json_data.getInt("FOOD_ID");
fd_name = json_data.getString("FOOD_NAME");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No food found", Toast.LENGTH_LONG).show();
}
catch(ParseException e1){
e1.printStackTrace();
}
}
}
Try adding the following to your
AndroidManifest.xmlbefore the opening<applicationelement…EDIT:
The reason you’re getting warnings about fd_id and fd_name never being read is because they never are. All you do in this code…
…is parse the JSON array using those variables (fd_id and fd_name) but you never do anything with them and there’s no more code after that block (except for the catch blocks which do nothing unless there’s an exception).
Try logging those variables as follows…