Search code examples
javaandroidjava-threads

How do I get a string from a thread or return a String form a Thread?


Im using a webservice that get a data and stores in a String. I need to use this String but I cant take it. Global variables don't work in Threads. I'm using a traditional Thread new Thread() { public void run() {.


Solution

  • Use LocalBroadcastManager to send and receive data. This way you can avoid memory leak issues.

    Here is code for activity

    public class YourActivity extends Activity {
    
        private void signal(){
            LocalBroadcastManager.getInstance(YourActivity.this).registerReceiver(receiver, new IntentFilter("Your action name"));
            Intent yourAction = new Intent(YourActivity.this, YourIntentService.class);
            String string = "someData";
            yourAction .putExtra("KEY_WITH_URL", string);
            startService(yourAction);
        }
    
        private BroadcastReceiver receiver = new BroadcastReceiver() {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                String string = intent.getStringExtra("KEY_WITH_ANSWER");
                //Do your code 
    
            }
        };
    
    }
    

    Here code for thread which download String or whatever

    public class YourIntentService extends IntentService {
    
        @Override
        protected void onHandleIntent(Intent intent) {
            // Download here
    
            Intent complete = new Intent ("Your action name");
            complete.putExtra("KEY_WITH_ANSWER", stringToReturn);
            LocalBroadcastManager.getInstance(YourIntentService.this).sendBroadcast(complete);
    
        }
    
    }
    

    You can use Thread instead of IntentService.