2

Hey fellow programmers <3
I want to transfer an String Array from my Service to my MainActivity via broadcastReceiver.
The String Array is wrapped in an Intent.
But when I try to get the String[] out of my intent
then it is an Array of Objects and I can´t just use intent.getStringArrayExtra(String).
Then I tried this:

How to convert object array to string array in Java?
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

But it doesen`t work either :/

public class MainActivity extends Activity implements View.OnClickListener {
final String LOG_TAG = "mainActivityLogs";
Button btnStartService;

private int numberOfFinishedTasks = 0;
private List<String> finishedTasksInTheLast60Sec = new ArrayList<>();
private int startedTasks = 0;
private ProgressBar pbService;
private Handler progressHandler = new Handler();

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //results in java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
        finishedTasksInTheLast60Sec = Arrays.asList(intent.getStringArrayExtra("finishedTasks"));

        //results in java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
        Object[] objectArray = intent.getStringArrayExtra("finishedTasks");
        String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
        finishedTasksInTheLast60Sec = Arrays.asList(stringArray);

        numberOfFinishedTasks += finishedTasksInTheLast60Sec.size();
        for (String finishedTask : finishedTasksInTheLast60Sec) {
            Log.d(LOG_TAG, finishedTask);
        }
    }
};

This function is in Service file MyService and var finishedTasks just contains name of Threads which are closed:

   private void sendBroadcast(List<String> finishedTasks) {
   Intent intent = new Intent("myServiceUpdate");
   intent.putExtra("finishedTasks", finishedTasks.toArray());
   LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
   }

I hope you can help and if you need the whole code just text me :)

1 Answer 1

2

While sending, cast the List type to ArrayList type by:

intent.putStringArrayListExtra("finishedTasks",(ArrayList<String>)finishedTasks);

While receiving just get the data by :

 List stringList = getIntent().getStringArrayListExtra("finishedTasks");
Sign up to request clarification or add additional context in comments.

1 Comment

intent.putStringArrayListExtra("finishedTasks",(ArrayList<String>)finishedTasks); was really helpful^^ thanks a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.