[android]获取字符串值出某个线程

发布时间: 2016/8/29 19:05:03
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有 String 我和变量,设置它的值内螺纹,因为它使用网络操作。

如何可以访问中存储的值 Strings

public class HomeActivity extends AppCompatActivity {

// Initialize AWS DynamoDB Client
public static AmazonDynamoDBClient ddbClient;
public static DynamoDBMapper mapper;
public static Aqua aqua;

// App details
public static String a = "A";
public static String b;
public static Boolean c;
public static String d;
public static String e;
public static String f;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    // Initialize the Amazon Cognito credentials provider
    CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(),
            "******", // Identity Pool ID
            Regions.**** // Region
    );

    // Initialize AWS DynamoDB
    ddbClient = new AmazonDynamoDBClient(credentialsProvider);
    mapper = new DynamoDBMapper(ddbClient);

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // Get app details
                aqua = mapper.load(Aqua.class, a);
                b = aqua.getB();
                c = aqua.getC();
                d = aqua.getD();
                e = aqua.getE();
                f = aqua.getF();
            } catch (Exception e) {
                Log.e("error", e.getMessage());
            }
        }
    });
    thread.start();
}
}

解决方法 1:

使用 ExecutorService 和提交 Callable (下面假定你想要在 b、 c、 d、 e、 f 内部存储的数据)︰

ExecutorService exec = Executors.newSingleThreadExecutor();
Future<String[]> future = exec.submit(new Callable<String[]>() {
    @Override
    public String[] call() {
        try {
            // Get app details
            aqua = mapper.load(Aqua.class, a);
            b = aqua.getB();
            c = aqua.getC();
            d = aqua.getD();
            e = aqua.getE();
            f = aqua.getF();
        } catch (Exception e) {
            Log.e("error", e.getMessage());
        }
        return new String[] {b, c, d, e, f};
    }
});
// ... b will be at value[0], c at value[1]
String[] value = future.get();
官方微信
官方QQ群
31647020