我有一个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();
}
}
答案 0 :(得分:2)
使用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();
答案 1 :(得分:0)
在Activity / Fragment中全局声明字符串。这样你就可以从任何地方访问它。
您还可以将public class DirectoryTree
{
public static async Task<TreeView> ListDirectory(string path)
{
TreeView treeView = new TreeView();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Nodes.Add(await CreateDirectoryNode(rootDirectoryInfo));
return treeView;
}
private static async Task<TreeNode> CreateDirectoryNode(DirectoryInfo directoryInfo)
{
try
{
var directoryNode = new TreeNode(directoryInfo.Name);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(await CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name));
return directoryNode;
}
catch ( Exception ex)
{
var directoryNode = new TreeNode(directoryInfo.Name);
return directoryNode;
}
}
}
与您的String一起使用,以便在您的线程完成时或任何时候发送它。然后,您可以检索String int
handler.sendMessage(message);
希望有所帮助:)