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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With