Unable to call second activity from asynctask - java

I need to call a new activity from onPostExecute() method of ASyncTask but the context is returning null.
public class ImageDownloadTask extends AsyncTask<String,Void,ArrayList<String>> {
public final String search = "https://www.google.co.in/search?&tbm=isch&q=";
public final String searchAlbum = "album+art";
ArrayList<String> arrayList=new ArrayList<String>();
ArrayList<String> urlList=new ArrayList<String>();
Context context;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<String> doInBackground(String... urls) {
System.out.println(urls.length);
arrayList.clear();
urlList.clear();
for(int i=0;i<urls.length;i++) {
String url = urls[i];
String finalUrl = search + url + searchAlbum;
try {
//Log.i("URL", finalUrl);
urlList.add(finalUrl);
Document document = Jsoup.connect(finalUrl).get();
String result = document.toString();
//Pattern pattern = Pattern.compile("<img class=\"rg_ic rg_i\" data-src=\"(.*?)\" data-sz");
Pattern newPattern = Pattern.compile("\"ou\":\"(.*?)\",\"ow\"");
//Matcher m = pattern.matcher(result);
Matcher newMatcher = newPattern.matcher(result);
if(newMatcher.find())
arrayList.add(newMatcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Printing Images");
System.out.println(urlList);
System.out.println(arrayList);
return arrayList;
}
#Override
protected void onPostExecute(ArrayList<String> strings) {
if(context!=null) {
Intent i = new Intent(context,MusicPlayerActivity.class).putExtra("arrayImages",arrayList);
context.startActivity(i);}
else
Log.i("Context","NULL"); //Check why it is null*****
super.onPostExecute(strings);
}
}
The Output is Context:NULL.
Why is it null, i have tried making a variable of type MainActivity and Activity, but both doesn't solve the problem.
Thank you for your time.

You declare your context variable but never set it:
Context context;
So yes, it is null when you try and use it.
You should populate it before you try to use it - perhaps pass a reference to to the calling Activity or similar.

Put this ImageDownloadTask inside your Activity, then you can call it using below code
new MyTask().execute(urls);
and on you ImageDownloadTask change onPostExecute function to this one
#Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
Intent i = new Intent(YourActivityName.this, MusicPlayerActivity.class).putExtra("arrayImages", strings);
startActivity(i);
}
}
}

Related

How to properly pass context to AsyncTask and then to another class?

I'm working on app that will use biometric as an option to login. Before I use the actual biometric prompt I need to check one thing from server - I use AsyncTask to do it. So, to sum up - I invoke AsyncTask from Parent Activity (login.java), and then AsyncTask uses biometricUtils.java class, that makes biometric prompt. The point is, I keep passing null instead of context to biometricUtils.java:
Attempt to invoke virtual method 'java.util.concurrent.Executor android.content.Context.getMainExecutor()' on a null object reference at biometricUtils.<init>(biometricUtils.java:34)
I have no idea to pass the context correctly.
Here's my code:
login.java
public class login extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Bundle bundle = getIntent().getExtras();
final boolean flag = false;
final String androidID = bundle.getString("androidID");
final Activity thisActivity = this;
final Context context = getApplicationContext();
// login using biometrics
Button btnBiometricLogin = findViewById(R.id.btnBiometricLogin);
btnBiometricLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAndroidID async = new checkAndroidID(context);
async.getParentActivity(thisActivity);
async.setFlag(flag);
async.execute(androidID);
}
});
}
}
checkAndroidID.java
public class checkAndroidID extends AsyncTask <String, Void, String> {
openHTTP openHTTP = new openHTTP();
requestHTTP requests = new requestHTTP();
Activity parentActivity;
private WeakReference<Context> contextRef;
Boolean flag;
public checkAndroidID(Context context){
contextRef = new WeakReference<>(context);
}
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
public void setFlag (Boolean flag){
this.flag = flag;
}
#Override
protected String doInBackground(String... strings) {
try {
HttpURLConnection httpConn = openHTTP.prepareConnection("url");
String json = "{ \"androidID\": \"" + strings[0] + "\" }";
requests.sendData(json, httpConn);
return requests.receiveData(httpConn);
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
String[] result = s.split(";");
Context ctx = contextRef.get();
if (result[0].equals("TRUE")) flag = true;
if (!flag) Toast.makeText(parentActivity, "Biometric authentication is now unavailable." +
" Please login using username and password", Toast.LENGTH_SHORT).show();
else {
biometricUtils biometrics = new biometricUtils(ctx);
biometrics.getParentActivity(parentActivity);
biometrics.getUsername(result[1]);
biometrics.inovkeBiometricPrompt();
}
super.onPostExecute(s);
}
}
and biometricUtlis.java
public class biometricUtils {
Activity parentActivity;
String username;
Context context;
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
public void getUsername(String s){
this.username = s;
}
public biometricUtils(Context context){
this.context = context;
}
// creating a variable for our Executor
Executor executor = ContextCompat.getMainExecutor(context); // LINE 34
// this will give us result of AUTHENTICATION
final BiometricPrompt biometricPrompt = new BiometricPrompt((FragmentActivity) parentActivity, executor, new BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
}
// THIS METHOD IS CALLED WHEN AUTHENTICATION IS SUCCESS
#Override
public void onAuthenticationSucceeded(#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Intent intent = new Intent(parentActivity.getApplicationContext(), tmp.class);
intent.putExtra("username", username);
parentActivity.startActivity(intent);
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
});
// creating a variable for our promptInfo
// BIOMETRIC DIALOG
final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder().setTitle("Biometrical login")
.setDescription("Place your fingerprint on scanner to proceed").setNegativeButtonText("Cancel").build();
public void inovkeBiometricPrompt() {
biometricPrompt.authenticate(promptInfo);
}
}

How do I call notifyDataSetChanged() from a AsyncTask that is in another class

So I am trying to call notifyDataSetChanged() to update the ArrayList on completion of OnPostExecute However I am finding it quite hard to do with the AsyncTask being in another class. I also cannot call it in setpagecontent as it is a static method.
I appreciate all the help provided :)
PostListActivity.java
public class PostListActivity extends AppCompatActivity {
ArrayList<String> Posts_Array_List = new ArrayList<String>();
// private RequestQueue mQueue;
ArrayAdapter<String> PostsAdaptor;
ListView lv;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_list);
mContext=PostListActivity.this;
lv = (ListView) findViewById(R.id.LV_Post_list);
PostsAdaptor = new ArrayAdapter<String>(PostListActivity.this, android.R.layout.simple_list_item_1, Posts_Array_List);
PostsAdaptor.notifyDataSetChanged();
lv.setAdapter(PostsAdaptor);
String stringUrl = "https://www.reddit.com/r/cars/hot.json?limit=1";
new DownloadAsyncTask(mContext,stringUrl).execute();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String myParam = extras.getString("paramPosition");
// Get the URL from the UI's text field.
}
}
public void setPageContent(String thePageContent) {
System.out.println("Got: " + thePageContent);
String jsonFromReddit = thePageContent;
//ArrayList<String> posts = RedditPostHelper.getRedditPostsFromJSON(jsonFromReddit);
// Posts_Array_List.addAll(posts);
Posts_Array_List.add(thePageContent);
System.out.println("result==="+thePageContent);
PostsAdaptor.notifyDataSetChanged();
}
}
DownloadAsyncTask.java
public class DownloadAsyncTask extends AsyncTask<Void,Void,String>{
private Context context;
private String url;
DownloadAsyncTask(Context mContext, String stringUrl)
{
super();
this.context=mContext;
this.url=stringUrl;
}
#Override
protected String doInBackground(Void... voids) {
String result="testing";
return result;
}
#Override
protected void onPostExecute(String result) {
if (!result.isEmpty() && result !=null){
PostListActivity pla = (PostListActivity) context;
pla.setPageContent(result);
}
}
Output:
}
There would be some changes to be made to the code but for inter class communication you can use an interface and use its functions as callbacks

Passing a variable between functions

I'm new to android studio and Java. My app uses jsoup to pass the contents of a website into an array where each element gets displayed on swipable flashcards (like tinder)
I've got a problem where my app crashes when I try to pass the result of the variable 'words' from onPostExecute() (line 123) to String num on line 49. I want to take the output of the function in onPostExcecute and set it as String num but I'm not sure how to do it.
public class AppHome extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
TextView texx;
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
String words;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_home);
texx= findViewById(R.id.text1);
new doit().execute();
String num = words;
String str[] = num.split(",");
final ArrayList al = new ArrayList<String>(Arrays.asList(str));
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al );
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
registerForContextMenu(flingContainer);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(AppHome.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(AppHome.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
}
public class doit extends AsyncTask<Void,Void,Void> {
//String words;
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words=doc.text();
}catch(Exception e){e.printStackTrace();}
return null;
}
#Override
public void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
}
public class doit extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... voids) {
String words = "";
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words = doc.text();
} catch(Exception e) {
e.printStackTrace();
}
return words;
}
#Override
public void onPostExecute(String words) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
It should be fine now.
The problem is, you are not returning anything from the doInBackground method and hence you are not getting anything in the onPostExecute function.
You might consider checking the documentation for AsyncTask here.
In doInBackgroud() return the string(make sure it never beacome null) you want to use it on PostExecute()
also changed the data type of Parameter in onPostExecute method
onPostExecute(String Strs)
Then pass it to supper.OnPostExecute().
then u can use it.

How to resolve ClassCastException: java.lang.String cannot be cast exception

I need help. I have two methods of shared preference. They are getList and setList.
This is setList()
public static void setList(Application activity, List<tcmb> mValuesList) {
StringBuilder valuesBuilder = new StringBuilder();
/*Log.d(TAG, "List Size ------ \t: " + mValuesList.size());*/
for (tcmb s : mValuesList) {
valuesBuilder.append(s);
valuesBuilder.append(",");
Log.d(TAG, "setValuestcmb: " + valuesBuilder.toString());
}
SharedPreferences values = activity.getSharedPreferences("dd", MODE_PRIVATE);
SharedPreferences.Editor editor = values.edit();
editor.putString("ss", valuesBuilder.toString());
editor.apply();
}
This is getList()
public static List<tcmb> getList(Activity a) {
SharedPreferences values = a.getSharedPreferences("dd", MODE_PRIVATE);
String wordsString = values.getString("ss", "");
/* Log.d(TAG, "wordsString \t:" + wordsString);*/
String[] itemWords = wordsString.split(",");
List<String> itemList = new ArrayList<String>();
itemList.addAll(Arrays.asList(itemWords));
dovizList = (List)itemsList;
Log.d(TAG, "getValuestcmb: " + dovizList.size());
return dovizList;
}
For the values I got, I run the setList method in the asyncTask class of Main Activity that assigns to shared preference.
Then for I get to values, I run the getList method in the asyncTask class of Fragment.
And I get the object values.namely, I can see the values I get from the logcat.
[com.example.lscodex.ddddd.Model.tcmb#4ff695, com.example.lscodex.ddddd.Model.tcmb#b6b93aa, com.example.lscodex.ddddd.Model.tcmb#347db9b, com.example.lscodex.ddddd.Model.tcmb#f63eb38, com.example.lscodex.ddddd.Model.tcmb#4866711, com.example.lscodex.ddddd.Model.tcmb#8c74076, com.example.lscodex.ddddd.Model.tcmb#3be9677, com.example.lscodex.ddddd.Model.tcmb#10882e4, com.example.lscodex.ddddd.Model.tcmb#8d9634d, com.example.lscodex.ddddd.Model.tcmb#b5eee02, com.example.lscodex.ddddd.Model.tcmb#b7c2313, com.example.lscodex.ddddd.Model.tcmb#a3ce950, com.example.lscodex.ddddd.Model.tcmb#ee5e749, com.example.lscodex.ddddd.Model.tcmb#fd1e84e, com.example.lscodex.ddddd.Model.tcmb#b7bdd6f, com.example.lscodex.ddddd.Model.tcmb#40f4a7c, com.example.lscodex.ddddd.Model.tcmb#b1caf05, com.example.lscodex.ddddd.Model.tcmb#b683b5a, com.example.lscodex.ddddd.Model.tcmb#f12e18b]
totally 19 values.
But when I cast values to recylerView's bindHolder in the fragment class, I get an error is that
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.lscodex.ddddd.Model.tcmb
This is asyncTask from fragment
private class DownloadXmlTask extends AsyncTask<Void, Integer, List<tcmb>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected List<tcmb> doInBackground(Void... voids) {
return SharedPreferenceValues.getList(getActivity());
}
#Override
protected void onPostExecute(List<tcmb> tcmb) {
if (tcmb.size() == 0) {
mtcmbList = tcmb;
setupAdapter();
mRecyclerViewAnim.runLayoutAnimation(getContext(), mRecyclerView);
mProgressBar.setVisibility(View.INVISIBLE);
} else if (mRecyclerView != null) {
mtcmbList.addAll(tcmb);
Log.d(TAG, "onPostExecute: " + mtcmbList.size());
mRecyclerView.getAdapter().notifyDataSetChanged();
dateUpdate();
mRecyclerViewAnim.runLayoutAnimation(getContext(), mRecyclerView);
mProgressBar.setVisibility(View.INVISIBLE);
mSwipeRefreshLayout.setRefreshing(false);
}
}
}
and the place where I got the error.
#Override
public void onBindViewHolder(tcmbHolder holder, int position) {
tcmb tcmb= mtcmbList.get(position); ---- the error here
holder.bindTcmb(tcmb);
I don't know why?
EDIT
I try it with the shared preferences, I get XML list data from splash screen and import it into other activity.
private class splashTask extends AsyncTask<Void, Integer, List<tcmb>> {
private Activity mContext;
public splashTask(Activity c){
this.mContext = c;
}
#Override
protected void onPreExecute() {
mSplashProgressBar.setProgress(0);
}
#Override
protected List<tcmbDoviz> doInBackground(Void... voids) {
List<tcmb> tcmbList = new ConnectionXmlParser().getXmlFile(getApplicationContext());
try {
int getvalues = ConnectionXmlParser.howLong();
Log.d(TAG, "doInBackground: " +getvalues);
for (int i=0;i<getvalues;i++){
Log.d(TAG, "doInBackground: " +i);
publishProgress(((int)i*100)/getvalues);
Log.d(TAG, "Publishing " + ((int)i*100/getvalues));
}
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return tcmbList;
}
#Override
protected void onPostExecute(List<tcmbDoviz> list) {
mtcmbList.addAll(list);
SharedPreferenceValues.setValuesList(getApplication(),mtcmbList);
splashScreen();
mSplashProgressBar.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(Integer... values) {
mSplashProgressBar.setProgress(values[0]);
super.onProgressUpdate(values);
}
You are trying to change List<String> to List<tcmb> and problem lies here
public static List<tcmb> getList(Activity a){
// your code
//
List<String> itemList = new ArrayList<String>();
itemList.addAll(Arrays.asList(itemWords));
dovizList = (List)itemsList;
Log.d(TAG, "getValuestcmb: " + dovizList.size());
return dovizList;
Also, I don't understand, what exactly you are trying to achieve here.
List<String> itemsList = new ArrayList<String>();
dovizList = (List)itemsList;
But, as per code shared, you need to change
List<String> itemsList = new ArrayList<String>();
to
List<tcmb> itemsList = new ArrayList<tcmb>();
And, you don't need
dovizList = (List)itemsList;
I found how to do it.
to save XML List object with Shared Preferences in splashscreen.activity
public static void setValues(Context context, List<tcmb> curProduct){
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(curProduct);
SharedPreferences sharedPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("dd", jsonCurProduct);
editor.apply();
Log.d(TAG, "setValues: " + jsonCurProduct);
}
then, to get the List object with Shared Preferences in the fragment
public static List<tcmb> getValuesAltın(Context context){
Gson gson = new Gson();
List<tcmbDoviz> productFromShared = new ArrayList<>();
SharedPreferences sharedPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
String jsonPreferences = sharedPref.getString("dd", "");
Type type = new TypeToken<List<tcmb>>() {}.getType();
productFromShared = gson.fromJson(jsonPreferences, type);
return productFromShared;
}
finally, Thanks, Ravi.

start AsyncTask from one activity, get result in another

I'm new to Android programming, and I'd like to create a central database service class which will take care of user data exchange with an external database. For this, I created a service which is started after successful login. I created another class that extends AsyncTask to do the data retrieval.
Now, I wanted the methods for the data retrieval to be stored in the service. I would fire intents to the service from different activities, and with .setAction() I would determine which method to call, or which data to retrieve.
I also created an interface class for handling the AsyncTask results.
Now, from this question I thought that it would be possible to have multiple listeners to one and the same AsyncTask result. But now this seems impossible to achieve: I'd like to retrieve the AsyncTask results in the MainMenuActivity, but I can't create an instance of AsyncUserData there as a delegate for the UserData class. In my example below, the missing piece is a valid instance of AsyncUserData for the UserData class to work with. How could I do it?
Here's the example:
MainMenuActivity
public class MainMenuActivity extends ActionBarActivity implements AsyncUserData {
TextView tvUsername;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
tvUsername =
(TextView) findViewById(R.id.tvUsername);
TelephonyManager tManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();
getDataFromUserSessionService(this, uid);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void retrieveResult(String result) throws JSONException {
JSONObject jsonObject = new JSONObject(result);
String joName;
joName = jsonObject.getJSONObject("name").toString();
user.setName(joName);
tvUsername.setText(joName);
}
public void getDataFromUserSessionService(Context context, String uid) {
Intent intent = new Intent(context, UserSession.class);
intent.setAction(UserSession.ACTION_FETCH_USER_DATA);
intent.putExtra(UserSession.UID, uid);
context.startService(intent);
}
UserSession Service
public class UserSession extends IntentService {
public static final String ACTION_FETCH_USER_DATA = "com.example.blahblah.services.action.read_user_data";
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
utils = new Utils(this);
final String action = intent.getAction();
uid = intent.getStringExtra(UID);
if (ACTION_FETCH_USER_DATA.equals(action)) {
handleUserDataFetch(uid);
}
}
}
private void handleUserDataFetch(String uid) {
String[] parameters = new String[2];
parameters[0] = uid;
parameters[1] = Constants.USER_DATA_FETCH;
UserData userData = new UserData(this);
userData.execute(parameters);
}
UserData AsyncTask Class (the Utils class just has another post method):
public class UserData extends AsyncTask < String, Void, String > {
public AsyncUserData delegate = null;
private Context myContext;
public UserData(Context context) {
myContext = context;
}
#Override
protected String doInBackground(String...params) {
String serverResponse = "";
String uid = params[0];
Utils utils = new Utils(myContext);
String phpName = params[1];
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
nameValuePairs.add(new BasicNameValuePair("uid", uid));
try {
serverResponse = utils.passDataToServer(phpName, nameValuePairs);
} catch (IOException e) {
e.printStackTrace();
}
return serverResponse;
}
protected void onPostExecute(String result) {
try {
delegate.retrieveResult(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
And the AsyncUserData interface:
public interface AsyncUserData {
void retrieveResult(String result) throws JSONException;
}
You can use a Singleton that stores a reference to the activity
public class ServiceToActivity
{
public ActionBarActivity mainactivity = null;
private static ServiceToActivity singleton = null;
public Class<?> cl = null;
private ServiceToActivity()
{
}
public static ActionBarActivity getSingleton()
{
if(singleton==null)
return null;
return singleton.mainactivity;
}
public static Class<?> getSingletonClass()
{
if(singleton==null)
return null;
return singleton.cl;
}
public static void setSingleton(ActionBarActivity mainactivity, Class<?> cl)
{
if(singleton==null)
singleton = new ServiceToActivity();
singleton.mainactivity = mainactivity;
singleton.cl = cl;
}
}
Then create the singleton before the service is started
public void getDataFromUserSessionService(Context context, String uid) {
Intent intent = new Intent(context, UserSession.class);
intent.setAction(UserSession.ACTION_FETCH_USER_DATA);
intent.putExtra(UserSession.UID, uid);
ServiceToActivity.setSingleton(this,this.getClass()); //create Singleton to store a reference to the activity
context.startService(intent);
}
In UserData retrieve data to the main activity by:
protected void onPostExecute(String result) {
try {
Class<?> cl = ServiceToActivity.getSingletonClass();
Method met = cl.getMethod("retrieveResult", String); //String because result is of type String: you can use result.getClass() instead
met.invoke(cl.cast(ServiceToActivity.getSingleton()), result); // compare it to this ServiceToActivity.getSingleton().retrieveResult(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
It sounds like you might want to use an event bus such as otto

Categories