私の主な活動では、スレッドを使用して接続を行い、サーバーから結果を取得しています。
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 クラス内では使用できません。サーバーへの接続が成功した後にアクティビティを変更する方法を教えてください。