从线程中获取字符串值



我有一个String变量,我在线程中设置了它的值,因为它使用的是netwok操作。

如何访问存储在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();
}
}

使用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();

在活动/片段中全局声明字符串。这样,您可以从任何地方访问它。

您还可以将handler.sendMessage(message);与字符串一起使用作为消息,以便在线程完成或任何时候发送它。然后,您可以检索您的字符串 int

protected Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        String status = (String) msg.obj;
        Log.i("Got a new message", "MESSAGE: "+status);
    }
};

希望对:)有所帮助

相关内容

  • 没有找到相关文章

最新更新