1
我一直在嘗試使用JSON/PHP Web服務層來通過我的Android應用程序訪問MySQL數據庫,它的工作原理(從日誌中我可以看到變量持有正確的信息),但是當我嘗試並通過值返回到主線程,他們沒有被存儲?傳回在單獨線程中創建的變量? Android
public class ViewErrands extends Activity {
public String result = "";
InputStream is;
String json = "lol"; //set as lol to begin with, to be overwritten with string from DB
TextView tv;
public int iss;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
tv = (TextView) findViewById(R.id.tvtv);
sendPostRequest();
tv.setText(json + "LOL" + iss); // the "lol" + "LOL" + 0 (should be 6) appear
}
public void sendPostRequest() {
class runCode extends AsyncTask<String, String, String> { // seperate task
@Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("idnum", "1"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.182/FYP/xshowall.php"); // PHP script to show all where id > POST
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "error in http conn " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "error converting " + e.toString());
}
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
json = "id: " + json_data.getInt("ID") + ", title: " + json_data.getString("TITLE")
+ ", content: " + json_data.getString("CONTENT");
);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return null;
}
}
runCode sendPostReqAsyncTask = new runCode();
sendPostReqAsyncTask.execute();
}
首先,當我嘗試複製一個值時,json變量保持爲'lol',就好像它從未改變過一樣。 這是與獨立進程有關嗎?我能做些什麼呢?
您,先生!我愛你! –