public class MainActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=462";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//StrictMode.setThreadPolicy(policy);
httpStuff = (TextView) findViewById(R.id.price);
client = new DefaultHttpClient();
new Read().execute("lasttradeprice");
}
public JSONObject lastPrice(String username)
throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
//url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
//Toast.makeText(HttpExample.this, "error", Toast.LENGTH_LONG);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
@Override
protected void onPostExecute(String result) {
httpStuff.setText("Price" + result + "357");
}
@Override
protected String doInBackground(String... params) {
try {
json = lastPrice("lasttradeprice");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
当我从网站api获得lasttradeprice
时,我什么都没得到。
因此,当我运行应用程序时,textview只是null
。
这个问题可能是因为即使我在清单中给出了许可,app也无法访问Android吗?
答案 0 :(得分:0)
该url的json结构返回,
{
"success":1,
"return":{
"markets":{
"CLAM":{
"marketid":"462",
"label":"CLAM\/BTC",
"lasttradeprice":"0.00280009",
......
因此,定位lasttradeprice值如下,
json = lastPrice("lasttradeprice");
return json.getJSONObject("return")
.getJSONObject("markets")
.getJSONObject("CLAM")
.getString(params[0]);