0

在我的主要活动中,我使用线程进行连接并从服务器获取结果。

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 类中使用它。您能否建议我在成功连接到服务器后更改活动的方法?

4

2 回答 2

1

由于您是从 an 调用此类,因此Activity您可以将Context其发送到constructor

 ABDAServerConnection sc = new ABDAServerConnection(MainActivity.this);

然后构建一个构造函数

 public class ABDAServerConnection
{
    Context mContext;
    public  ABDAServerConnection(Context c)
{
     mContext = c;
} 

然后创建Intent

mContext.startActivity(new Intent(mContext, AnotherActivity.class)); 
于 2013-05-08T02:54:22.890 回答
0

在 ABDAServerConnection 类的构造函数中存储对上下文类 (MainActivity.this) 的引用,并在第一个参数中使用它。

于 2013-05-08T02:52:49.840 回答