Skip to content Skip to sidebar Skip to footer

Android, Getting Data From Server

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 ex

Solution 1:

package com.Valluru;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

publicclassFoodextendsListActivity {
Stringresult=null;
InputStreamis=null;
StringBuilder sb=null;
List<NameValuePair> nameValuePairs = newArrayList<NameValuePair>();
ListView list1;

@OverridepublicvoidonCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    list1 = (ListView) findViewById(android.R.id.list);

    //http posttry{
        HttpClienthttpclient=newDefaultHttpClient();
        HttpPosthttppost=newHttpPost("http://10.0.2.2/food.php");
        HttpResponseresponse= httpclient.execute(httppost);
        HttpEntityentity= response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        Log.e("log_tag", "Error in http connection"+e.toString());
    }

    //convert response to stringtry{
        BufferedReaderreader=newBufferedReader(newInputStreamReader(is,"iso-8859-1"),8);
        sb = newStringBuilder();
        sb.append(reader.readLine() + "\n");
        String line="0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        result=sb.toString();

    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
    }

    //paring data
    String fd_id;
    String fd_name;
    try{
    JSONArrayjArray=newJSONArray(result);
    JSONObject json_data=null;

    for(int i=0;i<jArray.length();i++){
            json_data = jArray.getJSONObject(i);
            fd_id =json_data.getString("FOOD_ID");

            fd_name = json_data.getString("FOOD_NAME");
            nameValuePairs.add(newlist<String, String>(fd_id, fd_name));
    }

    list1.setAdapter(newArrayAdapter<NameValuePair>(getApplicationContext(),android.R.layout.simple_expandable_list_item_1,nameValuePairs));

    }catch(JSONException e1){
        Toast.makeText(getBaseContext(), "No FOOD Found", Toast.LENGTH_LONG).show();
    }catch (ParseException e1){
        e1.printStackTrace();
    }

}
}

list.java package com.Valluru;

import org.apache.http.NameValuePair;

import android.R.integer;

publicclasslist<T,V> implementsNameValuePair {
T data;
V text;

publiclist(T data, V text)
{
    this.data = data;
    this.text = text;
}

@OverridepublicStringtoString(){
    return text.toString();
}

@OverridepublicStringgetName() {
    return (String) data;
}

@OverridepublicStringgetValue() {
    return (String) text;
}
}

food.php

<?php
  mysql_connect("localhost","root");
  mysql_select_db("FOOD");
  $sql=mysql_query("select * from FOOD where FOOD_NAME like '%'");
  while($row=mysql_fetch_assoc($sql)) $output[]=$row;
  print(json_encode($output));
  mysql_close();
?>

Solution 2:

Things to try:

  1. On the server, are there any foods starting with A?
  2. Have you tried returning a simple string from the script, as opposed to running a query?
  3. Does any of your Log calls write into LogCat? If so, what does it say?
  4. Does the initial httpclient.execute work or is the exception triggered?
  5. Set a breakpoint on result = sbuilder.toString(), and debug the value. Is there a valid JSON dictionary in there, or something else?
  6. If step 4 and/or 5 fail, and you are not sure why, try analyzing your http traffic using Fiddler.

If any of the above steps eludes you, you have to take a step back from your project and figure these things out first. Experiment, learn and ask specific questions where needed.

Solution 3:

You failed parsing thoes fields:

fd_id = json_data.getInt("FOOD_ID");fd_name = json_data.getString("FOOD_NAME")

;

It's a server bug

Post a Comment for "Android, Getting Data From Server"