dongwan5381 2012-03-04 07:28 采纳率: 100%
浏览 84
已采纳

Android,从服务器获取数据

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;
?>
  • 写回答

3条回答 默认 最新

  • douqingji3026 2012-04-26 16:40
    关注
    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;
    
    public class Food extends ListActivity {
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    ListView list1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list1 = (ListView) findViewById(android.R.id.list);
    
        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/food.php");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }
    
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new   InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "
    ");
            String line="0";
    
            while ((line = reader.readLine()) != null) {
                sb.append(line + "
    ");
            }
    
            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{
        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.getString("FOOD_ID");
    
                fd_name = json_data.getString("FOOD_NAME");
                nameValuePairs.add(new list<String, String>(fd_id, fd_name));
        }
    
        list1.setAdapter(new ArrayAdapter<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;
    
    public class list<T,V> implements NameValuePair {
    T data;
    V text;
    
    public list(T data, V text)
    {
        this.data = data;
        this.text = text;
    }
    
    @Override
    public String toString(){
        return text.toString();
    }
    
    @Override
    public String getName() {
        return (String) data;
    }
    
    @Override
    public String getValue() {
        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();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM