gpt4 book ai didi

php - 从android中的url获取数据

转载 作者:太空狗 更新时间:2023-10-29 15:33:45 25 4
gpt4 key购买 nike

我想从 url 获取数据。在这种情况下,我有完整的 php,数据已经转换为 json 并在本地主机中运行(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(); ?>

这是结果

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

我想使用按钮点击并在 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;
}

}

通过该方法从服务器获取jsonString后,即可解析并展示Json中的数据。

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

关于php - 从android中的url获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12347688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com