【问题标题】:Get data from url in android从android中的url获取数据
【发布时间】:2012-09-03 02:00:17
【问题描述】:

我想从 url 获取数据。在这种情况下,我已经完成了数据转换为 json 并在 localhost (http://localhost/adchara1/index.php/?year=1) 中运行的完整 php

这是php脚本

<?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(); ?>

这就是结果

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

我想使用按钮单击并在 textview 中显示此结果

【问题讨论】:

  • 实际上你想问什么?同样的android代码或者你有任何疑问?
  • 在android中,我想从结果中获取url以显示在android的textView中。例如,在 android 中,我有 1 个按钮和 1 个 TextView,我想在 url [{"id":"1","name":"kongkea","sex":"1","birthyear":"1990"}, {"id":"2","name":"thida","sex":"0","birthyear":"2000"}]?&gt; 中获取结果以显示在 TextView 中。

标签: php android json url


【解决方案1】:
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;
}

}

使用此方法从服务器获取jsonString后,可以解析并展示Json中的数据。

编辑:您收到错误是因为您试图从服务器获取 json 的异步任务。您需要在后台执行此操作。您可以使用线程或使用 AsyncTask。

【讨论】:

  • 感谢您的回答,但它不起作用。这里是你的代码。 code
  • 谢谢。有用。我使用按钮清除 textview(tv.setText(""))。并再次获取数据但错误。是吗?
【解决方案2】:

在您的按钮 OnClickListener 中编写此代码

        try {
        String url = "http://YourIPAddress/adchara1/index.php/?year=1";
        HttpPost httppost = new HttpPost(url);
        try {
            HttpParams p = new BasicHttpParams();
            HttpClient httpclient = new DefaultHttpClient(p);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost,
                    responseHandler);
            JSONArray jArray = new JSONArray(responseBody);
            String text="";
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject e = jArray.getJSONObject(i);
                    text = text + "ID : "+e.getString("id")+"\n";
                    text = text + "Name : "+e.getString("name")+"\n";
                    text = text + "Sex : "+e.getString("sex")+"\n";
                    text = text + "Birthyear : "+e.getString("birthyear")+"\n";
            }
            Textview.setText(text);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
        t.printStackTrace();
    }

如果您有任何澄清,请通知我

【讨论】:

  • 感谢您的回答,但它不起作用。 Project。谢谢
【解决方案3】:
Button button =(Button) findViewById(R.id.button);
        TextView tv =(TextView) findViewById(R.id.textview);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String result = connectionFromServer("http://localhost/adchara1/index.php/?year=1");
                tv.setText(result);
            }
        });   

 public static String connectionFromServer(String url) throws IOException {

            BufferedReader inputStream = null;

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

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

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

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

这将在文本视图中显示结果。

【讨论】:

【解决方案4】:

您应该使用 HttpClient 简单地执行一个 get 请求,然后使用 JSONArray 对象将字符串转换为 Json Array。

http://developer.android.com/reference/org/apache/http/client/HttpClient.html

http://developer.android.com/reference/org/json/JSONArray.html

【讨论】:

  • 我尝试在很多教程中这样做,但它不起作用,所以我决定问。你能完成这段代码吗
猜你喜欢
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 2016-01-18
  • 2013-05-06
  • 2017-06-22
  • 1970-01-01
相关资源
最近更新 更多