Manpreet
Manpreet

Reputation: 580

Starting activity from a separate thread?

I have an android application that takes a photograph in the main thread and creates a new thread in order to send this image to the server and receives the response. Now, I want to save the information sent by the server in the contact list of my phone, for that I am trying to start an activity on this new thread using the following code:

private void addContact() {

    Intent intent = new Intent(Intent.ACTION_INSERT);
    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);

    intent.putExtra(ContactsContract.Intents.Insert.NAME, DisplayName);
    intent.putExtra(ContactsContract.Intents.Insert.PHONE, WorkNumber);
    intent.putExtra(ContactsContract.Intents.Insert.EMAIL, emailID);

    this.startActivity(intent);

}

but his is throwing me error: System Service not available to Activities before onCreate()

What I think of this message is that since in this new thread it doesn't have any onCreate() method, that is the reason it throws this error.

Can someone tell me how should I start this activity.

Upvotes: 1

Views: 624

Answers (1)

Yash Sampat
Yash Sampat

Reputation: 30611

Instead of using a separate Thread to send data to the server, try using an AsyncTask:

  1. Make the network call in doInBackground() and return the server response in a Bundle or a String[] array to onPostExecute().

  2. In onPostExecute(), add the server data to the intent and then call startActivity().

Try this. It will work. You are getting an error because you are calling startActivity() on another thread. You need to call it on the main (UI) thread.

Upvotes: 1

Related Questions