在我的主要活动中,我使用线程进行连接并从服务器获取结果。
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
ABDAServerConnection sc = new ABDAServerConnection();
sc.getCategories();
} catch (Exception e) {
Log.i(TAG,"thread1: " + e);
}
}
});
thread.start();
我想在连接成功执行后更改我的活动,即我从服务器获取结果。
public class ABDAServerConnection {
public void getCategories() {
HttpResponse response = null;
StringBuilder str = new StringBuilder();
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ABDAURLs.getCategories);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
String result = "";
try {
// Execute HTTP Post Request
response = httpclient.execute(httppost);
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n" );
}
in.close();
result = str.toString();
Log.i("NFC",result);
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("results");
for (int i=0; i < jArray.length(); i++)
{
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
int id = oneObject.getInt("category_id");
String name = oneObject.getString("category_name");
//Add this "MenuCategory" item to the global menu_category array
ABDACategories m1 = new ABDACategories(id,name);
GlobalList.getCategories().add(m1);
}
//AT THIS POINT, I WANT TO START ANOTHER ACTIVITY
}catch(Exception ex){
result = "Error";
Log.i("NFC","Problem: " +ex);
}
} catch (ClientProtocolException e) {
Log.i("NFC","ClientProtocolException: " +e);
} catch (IOException e) {
Log.i("NFC","IOException: " +e);
}
return;
}
}
通常,我会使用
startActivity(new Intent(MainActivity.this, AnotherActivity.class));
但在这种情况下,我不能在我的 ABDAServerConnection 类中使用它。您能否建议我在成功连接到服务器后更改活动的方法?