从URL中的机器人获取的数据 [英] Get data from url in android

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

问题描述

我想从URL获取数据。在这种情况下,我已经得到了完整的PHP的数据转换成JSON已经在本地主机上运行(HTTP://localhost/adchara1/index.php/年= 1)

这是PHP脚本

 < PHP
 的mysql_connect(localhost的根,);
 mysql_select_db(测试);
 $ Q =请求mysql_query(SELECT * FROM人
 哪里
 birthyear>'$ _ REQUEST ['年'。');
 而($ E = mysql_fetch_assoc($ Q))
         $输出[] = $Ë;
   打印(json_en code($输出));
   则mysql_close(); ?>
 

这是结果

  [{ID:1,名:kongkea,性:1,birthyear:1990},{ID :2,名称:thida,性别:0,birthyear:2000}]≥
 

我想用按一下按钮,并显示该结果的TextView

解决方案

 公共类MainActivity延伸活动{

AsyncTask的<虚空,虚空,虚空> mTask;
字符串jsonString;

字符串URL = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=50cent&count=2";


按钮B;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    getActionBar()setDisplayHomeAsUpEnabled(真)。

    B =(按钮)findViewById(R.id.btnFetch);
    最后的TextView电视=(TextView中)findViewById(R.id.txtView);

    mTask =新的AsyncTask<虚空,虚空,虚空> (){

        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            尝试 {
                jsonString = getJsonFromServer(URL);
            }赶上(IOException异常E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }
            返回null;
        }

        @覆盖
        保护无效onPostExecute(无效的结果){
            super.onPostExecute(结果);

            tv.setText(jsonString);

        }

    };

    b.setOnClickListener(新OnClickListener(){

        公共无效的onClick(视图v){
            mTask.execute();
        }
    });
}


公共静态字符串getJsonFromServer(字符串URL)抛出IOException异常{

    BufferedReader中的InputStream = NULL;

    URL jsonUrl =新的网址(URL);
    的URLConnection直流= jsonUrl.openConnection();

    dc.setConnectTimeout(5000);
    dc.setReadTimeout(5000);

    的InputStream =新的BufferedReader(新的InputStreamReader(
            dc.getInputStream()));

    //读取JSON结果转换成字符串
    串jsonResult = inputStream.readLine();
    返回jsonResult;
}

}
 

获取jsonString从服务器使用这种方法后,您可以分析,并显示在JSON数据。

编辑:你得到的错误,因为你正试图从服务器的JSON出异步task.You需要做的是在后台。您可以使用一个线程或使用AsyncTask的。

I want to get data from url. in this case I've got complete php that data convert to json already and run in localhost (http://localhost/adchara1/index.php/?year=1)

This is the php script

<?php
 mysql_connect("localhost","root","");
 mysql_select_db("test");
 $q=mysql_query("SELECT * FROM people
 WHERE
 birthyear>'".$_REQUEST['year']."'");
 while($e=mysql_fetch_assoc($q))
         $output[]=$e;
   print(json_encode($output));
   mysql_close(); ?>

and this is result

[{"id":"1","name":"kongkea","sex":"1","birthyear":"1990"}, {"id":"2","name":"thida","sex":"0","birthyear":"2000"}]?>

I want to use button click and show this result in textview

解决方案

public class MainActivity extends Activity {

AsyncTask<Void, Void, Void> mTask;
String jsonString;

String url = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=50cent&count=2";


Button b;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    b = (Button) findViewById(R.id.btnFetch);
    final TextView tv = (TextView) findViewById(R.id.txtView);

    mTask = new AsyncTask<Void, Void, Void> () {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                jsonString = getJsonFromServer(url);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            tv.setText(jsonString);

        }

    };

    b.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            mTask.execute();
        }
    });
}


public static String getJsonFromServer(String url) throws IOException {

    BufferedReader inputStream = null;

    URL jsonUrl = new URL(url);
    URLConnection dc = jsonUrl.openConnection();

    dc.setConnectTimeout(5000);
    dc.setReadTimeout(5000);

    inputStream = new BufferedReader(new InputStreamReader(
            dc.getInputStream()));

    // read the JSON results into a string
    String jsonResult = inputStream.readLine();
    return jsonResult;
}

}

After Getting jsonString from server with this method, you can parse and show the data in the Json.

EDIT: You get error because you are trying to get json from server out of async task.You need to do it in the background. You can either use a thread or use AsyncTask.

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

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