我使用Thread
爲Webservice
,但我不能得到Thread
的數據,因爲我不能從Thread
返回數據。如何從線程返回值?
這是我WebService.java
:
public class Webservice {
static String result;
public static String readUrl(final String url) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
result = ConvertInputStreamToString(stream);
Log.i("xxx","OK" + result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return result;
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
這是NotesActivity.java
:
public class NotesActivity extends Activity {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
String result = Webservice.readUrl("http://192.168.200.101:8081/note-server/");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
thread.start();
}
}
這是我StructTask.java
:
public class StructTask {
public long id;
public String title;
public String desc;
public boolean done;
}
此代碼返回給我NULL。
你真的不想要onCreate中新線程的典當。這可能會導致各種問題,包括內存泄漏和應用程序生命週期問題。你需要做的是檢查Android設備AsyncTask。 – Bex
您可以使用sharedprefrences臨時存儲數據或使用靜態變量並在您的線程中分配值 –
爲什麼您不使用async? – Andy