Return A String From A Thread Android Java
Solution 1:
The correct way of doing this is using Callable and Future interfaces.
publicstaticvoidmain(String[] args)throws ExecutionException, InterruptedException {
ExecutorServiceexecutorService= Executors.newSingleThreadExecutor();
CallableClasscallableClass=newCallableClass();
Future<String> future = executorService.submit(callableClass);
Stringname= future.get();
System.out.println(name);
}
publicclassCallableClassimplementsCallable<String> {
@Overridepublic String call()throws Exception {
return"John Doe";
}
}
Solution 2:
Use interface to make it work properly.
privateinterfaceDataListener{
voidonDataReady(String data);
}
privateString str_Name = "";
publicvoidonCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity);
setDataToText(str_Url, newDataListener() {
@OverridepublicvoidonDataReady(String data) {
str_Name = data;
System.out.println(str_Name);
}
});
}
privatevoidsetDataToText(final String urlStr,final DataListener dataListener) {
newThread(newRunnable() {
@Overridepublicvoidrun() {
// TODO Auto-generated method stub//A code to retrieve data is executed//Data is Converted and added to the string str_Data;String str_Data = "John Doe";
dataListener.onDataReady(str_Data);
}
}).start();
}
Solution 3:
You can do something like this.
String str_Data = "";
publicvoidonCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity);
String str_Name = "";
str_Name = setDataToText(str_Url);
}
privateStringsetDataToText(String urlStr) {
newThread(newRunnable() {
@Overridepublicvoidrun() {
// TODO Auto-generated method stub//A code to retrieve data is executed//Data is Converted and added to the string str_Data;
str_Data = "John Doe";
}
}).start();
return str_Data;
}
Solution 4:
You can't change the value of a local variable inside that thread. If you want to access variable in that thread, they need to be declared final, which implies that you cannot change their values.
Basically there is no sense in returning a value from a thread in your case, because you can't know when that value will be ready.
There are various of options to use the value you got from your database: you can use listeners, eventbus (use with caution), you can declare str_Data as a field in that class (but watch out what happens on screen rotation). So if you need to show that value in your layout, you can display a progress bar when you start the thread, and hide it + set the value you got in the layout when the thread finishes its work
Post a Comment for "Return A String From A Thread Android Java"