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
。 這個問題可能是因爲應用程序無法訪問android,即使我在清單中給予權限?來自網站API的值總是返回爲零
'新的閱讀()執行( 「lasttradeprice」) ;「這是什麼意思? – Ubica
它應該在這裏把這個字符串傳給:保護字符串doInBackground(字符串... PARAMS){ \t \t \t嘗試{ \t \t \t \t JSON = lastPrice( 「lasttradeprice」); \t \t \t \t return json.getString(params [0]); – kiwicode
你有沒有檢查字符串是否成功通過?爲什麼在'json = lastPrice(「lasttradeprice」)中使用''lasttradeprice'';'如果這是要傳遞給此方法的字符串? – Ubica