从android中的url获取数据

kon*_*kea 2 php url android json

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

这是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(); ?>
Run Code Online (Sandbox Code Playgroud)

这是结果

[{"id":"1","name":"kongkea","sex":"1","birthyear":"1990"}, {"id":"2","name":"thida","sex":"0","birthyear":"2000"}]?>
Run Code Online (Sandbox Code Playgroud)

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

osa*_*gan 8

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

}
Run Code Online (Sandbox Code Playgroud)

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

编辑:你得到错误,因为你试图从服务器中获取异步任务的json.你需要在后台执行.您可以使用线程或使用AsyncTask.


pon*_*raj 5

将此代码写入Button 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();
    }
Run Code Online (Sandbox Code Playgroud)

如果您有任何澄清通知我