I am totally green in android. And I want to create App that gets data from server and shows it in the app. Can anyone tell me how to start it? I tried this code below. But only exception is showing that food isn't found.
private EditText outputStream;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream input = null;
StringBuilder sbuilder = null;
outputStream = (EditText)findViewById(R.id.output);
ArrayList <NameValuePair> nameValuePairs = new ArrayList <NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("ik.su.lt/~jbarzelis/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
HttpEntity entity = response.getEntity();
input = entity.getContent();
}
catch(Exception e){
e.printStackTrace();
}
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 + "
");
}
input.close();
result = sbuilder.toString();
}
catch(Exception e){
e.printStackTrace();
}
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");
outputStream.append(fd_id +" " + fd_name + "
");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No food found", Toast.LENGTH_LONG).show();
}
catch(ParseException e1){
e1.printStackTrace();
}
}
PHP code is correct it shows data. I think somethig is wrong with the code above.
<?php
mysql_connect("localhost","********","**********");
mysql_select_db("test");
$sql = mysql_query("select FOOD_NAME as 'Maistas' from FOOD where FOOD_NAME like 'A%'");
while($row = mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close;
?>