机器人,正从服务器的数据 [英] Android, getting data from server

查看:133
本文介绍了机器人,正从服务器的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在android系统完全绿色。我想创建应用程序从服务器获取数据并显示在应用程序。谁能告诉我怎么开始呢?我试过低于这个code。但唯一的例外是显示食物是找不到的。

 私人的EditText的OutputStream;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    字符串结果= NULL;
    输入的InputStream = NULL;
    StringBuilder的sbuilder = NULL;
    的OutputStream =(EditText上)findViewById(R.id.output);
    ArrayList的<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();    尝试{
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(ik.su.lt/~jbarzelis/index.php);
        httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
        HTT presponse响应= httpclient.execute(httppost);
        如果(response.getStatusLine()的getStatus code()!= 200){
            Log.d(MyApp的,服务器遇到错误);
        }
        HttpEntity实体= response.getEntity();
        输入= entity.getContent();
    }
    赶上(例外五){
        e.printStackTrace();
    }
    尝试{
        的BufferedReader读者=新的BufferedReader(新InputStreamReader的(输入,ISO-8859-1),8);
        sbuilder =新的StringBuilder();        串线= NULL;        而((行= reader.readLine())!= NULL){
            sbuilder.append(行+\\ n);
        }
        input.close();
        结果= sbuilder.toString();
    }
    赶上(例外五){
        e.printStackTrace();
    }
    INT fd_id;
    串fd_name;
    尝试{
        JSONArray jArray =新JSONArray(结果);
        JSONObject的json_data = NULL;
        的for(int i = 0; I< jArray.length();我++){
            json_data = jArray.getJSONObject(ⅰ);
            fd_id = json_data.getInt(FOOD_ID);
            fd_name = json_data.getString(FOOD_NAME);
            outputStream.append(fd_id ++ fd_name +\\ n);
        }
        }
    赶上(JSONException E1){
        Toast.makeText(getBaseContext(),无食物中,Toast.LENGTH_LONG).show();
    }
    赶上(ParseException的E1){
        e1.printStackTrace();
    }
}

PHP code是正确的它显示的数据。我认为somethig是错误的code以上。

 < PHP
    mysql_connect(本地主机,********,**********);
    mysql_select_db(测试);
    $ SQL =的mysql_query(选择FOOD_NAME为Maistas食品,其中像FOOD_NAME'A%');
    而($行= mysql_fetch_assoc($ SQL))$输出[] = $行;
    打印(json_en code($输出));
    mysql_close;
?>


解决方案

 包com.Valluru;进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.util.ArrayList;
进口的java.util.List;
进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.ListActivity;
进口android.content.Intent;
进口android.net.ParseException;
进口android.net.Uri;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.ArrayAdapter;
进口android.widget.ListView;
进口android.widget.TextView;
进口android.widget.Toast;公共类食品扩展ListActivity {
字符串结果= NULL;
InputStream为= NULL;
StringBuilder的SB = NULL;
清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
ListView的list1的;@覆盖
公共无效的onCreate(捆绑savedInstanceState)
{
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    list1的=(的ListView)findViewById(android.R.id.list);    // HTTP POST
    尝试{
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpPost httppost =新HttpPost(http://10.0.2.2/food.php);
        HTT presponse响应= httpclient.execute(httppost);
        HttpEntity实体= response.getEntity();
        是= entity.getContent();
    }赶上(例外五){
        Log.e(log_tag,在HTTP连接错误+ e.toString());
    }    //响应转换为字符串
    尝试{
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,ISO-8859-1),8);
        SB =新的StringBuilder();
        sb.append(reader.readLine()+\\ n);
        串行=0;        而((行= reader.readLine())!= NULL){
            sb.append(行+\\ n);
        }        is.close();
        结果= sb.toString();    }赶上(例外五){
        Log.e(log_tag,错误转换结果+ e.toString());
    }    //配对数据
    串fd_id;
    串fd_name;
    尝试{
    JSONArray jArray =新JSONArray(结果);
    JSONObject的json_data = NULL;    的for(int i = 0; I< jArray.length();我++){
            json_data = jArray.getJSONObject(ⅰ);
            fd_id = json_data.getString(FOOD_ID);            fd_name = json_data.getString(FOOD_NAME);
            nameValuePairs.add(新名单<字符串,字符串>(fd_id,fd_name));
    }    list1.setAdapter(新ArrayAdapter<NameValuePair>(getApplicationContext(),android.R.layout.simple_expandable_list_item_1,nameValuePairs));    }赶上(JSONException E1){
        Toast.makeText(getBaseContext(),无食物中,Toast.LENGTH_LONG).show();
    }赶上(ParseException的E1){
        e1.printStackTrace();
    }}
}

list.java
    包com.Valluru;

 进口org.apache.http.NameValuePair;进口android.R.integer;公共类列表&LT; T,V&GT;实现的NameValuePair {
数据T;
V文本;公示名单(T数据,V文本)
{
    this.data =数据;
    this.text =文本;
}@覆盖
公共字符串的toString(){
    返回text.toString();
}@覆盖
公共字符串的getName(){
    返回(字符串)数据;
}@覆盖
公共字符串的getValue(){
    返回(字符串)文本;
}
}

food.php

 &LT; PHP
  mysql_connect(localhost的根);
  mysql_select_db(食物);
  $ SQL =的mysql_query(SELECT * FROM食物放在FOOD_NAME LIKE'%');
  而($行= mysql_fetch_assoc($ SQL))$输出[] = $行;
  打印(json_en code($输出));
  mysql_close();
?&GT;

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 + "\n");
        }
        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 + "\n");
        }


        }
    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;
?>

解决方案

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() + "\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{
    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();
?>

这篇关于机器人,正从服务器的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆