How to call one Fragment Method from another Fragment in android - java

In my application I want 2 fragments in a Activity. and for showing these 2 fragments I use ViewPager.
In Fragment two I have one method, and I want call this method from Fragment one!
My method in Fragment two :
public void getComments() {
JsonObject requestBean = new JsonObject();
requestBean.addProperty("entityType", 4);
requestBean.addProperty("reviewType", 5);
requestBean.addProperty("reviewUserType", 2);
requestBean.addProperty("entityID", serialID);
requestBean.addProperty("celebrityId", 0);
requestBean.addProperty("pageIndex", 1);
requestBean.addProperty("pageSize", 10);
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<CommentResponse> call = api.getComments(token, requestBean);
call.enqueue(new Callback<CommentResponse>() {
#Override
public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
if (response.body().getData() != null) {
if (response.body().getData().size() > 0) {
reviewSerialFrag_NoComment.setText("");
} else {
reviewSerialFrag_NoComment.setText(context.getResources().getString(R.string.noReviews));
}
commentModel.clear();
commentModel.addAll(response.body().getData());
commentsListAdapter.notifyDataSetChanged();
reviewSerialFrag_newsCommentsRecyclerView.setAdapter(commentsListAdapter);
reviewSerialFrag_newsCommentsUserTypeText.setText(userTypeStr);
reviewSerialFrag_newsCommentsReviewTypeText.setText(reviewTypeStr);
reviewSerialFrag_Progress.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<CommentResponse> call, Throwable t) {
reviewSerialFrag_Progress.setVisibility(View.GONE);
}
});
}
And call this method with below codes from Fragment one :
InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
Call<SendCommentResponse> call = api.getSendComment(token, sendData);
showView(loadProgress);
goneView(sendBtn);
call.enqueue(new Callback<SendCommentResponse>() {
#Override
public void onResponse(Call<SendCommentResponse> call, Response<SendCommentResponse> response) {
if (response.body().getData()) {
Alerter.create(getActivity())
.setText(context.getResources().getString(R.string.successSendComment))
.setDuration(2000)
.setIcon(R.drawable.ic_tick_new)
.setBackgroundColorRes(R.color.colorPrimary)
.enableSwipeToDismiss()
.enableProgress(true)
.setOnShowListener(new OnShowAlertListener() {
#Override
public void onShow() {
watchlistDialog.dismiss();
goneView(loadProgress);
showView(sendBtn);
}
})
.setOnHideListener(new OnHideAlertListener() {
#Override
public void onHide() {
infoEpisodeFrag_addWatchList.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_eye_white));
infoEpisodeFrag_addWatchList.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#1da8b9")));
getData();
new EpisodeDetail_ReviewFrag().getComments();
}
})
.setProgressColorRes(R.color.whiteMe)
.show();
}
}
#Override
public void onFailure(Call<SendCommentResponse> call, Throwable t) {
}
});
But show me this error in LogCat :
FATAL EXCEPTION: main
Process: com.example.app, PID: 11978
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.support.v4.app.FragmentActivity.getResources()' on a null object reference
at com.example.app.Fragments.EpisodeDetailFrags.EpisodeDetail_ReviewFrag$6.onResponse(EpisodeDetail_ReviewFrag.java:305)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5349)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Show me error for this line in Fragment two :
reviewSerialFrag_NoComment.setText(context.getResources().getString(R.string.noReviews));
How can I fix it? Please help me

It is really a bad idea to use Fragments like regular classes. Even when you want to pass simple data around you'd use and instance or use the bundle.
If your method does not rely on the fragment itself, create a separate utility class that both fragments share. Just pass it a context so it can resolve some of the variables in it.
Separate the UI manipulation in a separate class within your fragments. Create a listener to this utility class and change the visual state in your fragment.

No need to call getResources() method. Just getString(R.string.noReviews) works.

Get the instance of fragment
ExampleFrag frag=(ExampleFrag)getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment2);
Then call any method
frag.myMethod();

Related

Change TextView text from another class using interface

I'm trying to make some utils functions to use in a bigger app later(download file from url, upload file to url etc)
So in MainActivity I have only 2 buttons that on click call static methods from Utils class.
However, I want on MainActivity to have some indicators of how things working on download/upload methods(connecting, connection success/fail, percent of download etc) so I put on MainActivity a TextView that will show that. I made an interface ICallback that contains void setConnectionStatus(String status) and from Utils class I use this to send to MainActivity the status.
Here are some parts of the code :
public class MainActivity extends AppCompatActivity implements ICallback {
Button btnDownloadDB, btnUploadDB, btnUploadPics;
TextView txtStatus;
ProgressBar pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize stuffs
initViews();
//Setting listeners
btnDownloadDB.setOnClickListener(v -> {
txtStatus.setText(R.string.connecting);
pb.setVisibility(View.VISIBLE);
Utils.downloadFile(DOWNLOAD_DB, DB_FILE_NAME);
});
}
#Override
public void setConnectionStatus(String status) {
Log.d("MIHAI", status);
txtStatus.setText(status);
}
The interface :
public interface ICallback {
void setConnectionStatus(String status); }
And the Utils class :
public class Utils {
static ICallback callback= new MainActivity();
public static void downloadFile(String downloadURL, String fileName) {
IFileTransferClient client = ServiceGenerator.createService(IFileTransferClient.class);
Call<ResponseBody> responseBodyCall = client.downloadFile(downloadURL);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("MIHAI", "connection ok");
callback.setConnectionStatus("Connection successful");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("MIHAI", "err...fail");
callback.setConnectionStatus("Connection failed. Check internet connection.");
}
});
}
The problem appear on MainActivity, when I try to set text of the txtStatus TextView getting a null reference error even if the txtStatus is initialized on initViews() method.
The Logs are working fine so I get the right status in MainActivity. I tried to initialize the TextView again in that function before seting the text and im getting : "java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:183)"
Is there any chance to make this work?
Thank you for reading.
Kind regards,
Mihai
There are multiple problems with your solution but the main one is this line:
static ICallback callback= new MainActivity();
First of all, never hold a static reference to Activity, Fragment, Context or any Context related classes. These classes are either bound to a Context or represent the Context itself. You may leak memory this way. But that is the other problem.
What is the actual problem in your code is that new MainActivity() in Utils class creates an absolutely different instance of MainActivity that has nothing to do with MainActivity that is responsible for displaying your UI in the runtime.
What you should do instead is pass an instance of ICallback to the function as an argument:
public static void downloadFile(String downloadURL, String fileName, ICallback callback) {
...
}
And remove static ICallback callback= new MainActivity();.
Note: when you pass a callback object to a function make sure when it is called your Activity is not in a finished state.

Null Pointer Exception thrown when calling .show() on MediaController

I found this question was marked as duplicate for one about how to prevent Null Pointer Exceptions. For clarification, the problem is that the library is throwing it. My variable isn't null. More specific help about the library is more helpful.
I am creating an app for playing music. I am trying to make use of the MediaController class to add controls to the song being played. However, when I run the .show() function, I get a Null Pointer Exception.
Here is the code for the MediaController:
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
MediaController timer = view.findViewById(R.id.song_progress);
timer.setMediaPlayer(new MediaController.MediaPlayerControl() {
#Override
public void start() {
MainActivity.playingSong.start();
}
#Override
public void pause() {
MainActivity.playingSong.pause();
}
#Override
public int getDuration() {
return MainActivity.playingSong.getDuration();
}
#Override
public int getCurrentPosition() {
return MainActivity.playingSong.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
MainActivity.playingSong.seekTo(pos);
}
#Override
public boolean isPlaying() {
return MainActivity.playingSong.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return MainActivity.playingSong.getAudioSessionId();
}
});
timer.setAnchorView(view);
timer.setEnabled(true);
timer.show();
}
Here is the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.luner.mobilemusic, PID: 2021
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.measure(int, int)' on a null object reference
at android.widget.MediaController.updateFloatingWindowLayout(MediaController.java:173)
at android.widget.MediaController.show(MediaController.java:363)
at android.widget.MediaController.show(MediaController.java:314)
at com.luner.mobilemusic.Playlist$Song$PlayFragment.onViewCreated(Playlist.java:271)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:892)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
Why is this happening? Is there a good way to fix this, or should I use a different class completely? I would very much appreciate any code examples you might have.
Also, I found that removing the setAnchorView(view) prevented the error, but then caused no MediaController to appear.
Edit
After doing a more thorough search, I found two things:
The line numbers aren't accurate for some reason; the line for updateFloatingWindowLayout appeared inside a different method.
The culprit is the mDecor variable, which while running the setAnchorView method is set to the view variable. However, the view variable can't be null, as that would have caused an exception before getting to the show function. Thus, I still can't quite figure out the source of this ... the mDecor variable must somewhere be set to null, but only when I add a custom anchor view.
Edit 2
I have made lots of changes to the program at this point, so I am unable to test if a solution works. However, feel free to post an answer to help anyone else with the issue. I will accept any answer with a good amount of upvotes, as the upvotes signify that the solution worked. Thanks to everyone who tried to help!

Values of a List don't change programmatically

I have an List called messages property in my Activity.In the synchronization(),I called getDateMessage(upadated_at) function.In this function value of messages has changed but when program go to synchronization messages list is empty.
private List<message_model> messages = new ArrayList<>();
private void synchronization() {
getDateMessage(upadated_at);
Log.e("MSDF",messages.toString()+" list tostring");
}
private void getDateMessage(String date) {
MessengerActivity.APIInterface apiInterface = app_net.getRetrofitInstance().create(MessengerActivity.APIInterface.class);
retrofit2.Call<List<message_model>> call = apiInterface.getMessageDate(Ptoken, date);
call.enqueue(new Callback<List<message_model>>() {
#Override
public void onResponse(Call<List<message_model>> call, Response<List<message_model>> response) {
if(response.isSuccessful()) {
messages.addAll(response.body());
Log.e("MSDF",response.body().toString()+" responsebody in call");
Log.e("MSDF",messages.toString()+" message in call");
Log.e("MESSAGE", "getDateMessage successful");
}
}
#Override
public void onFailure(Call<List<message_model>> call, Throwable t) {
Log.e("MESSAGE", "getDateMessage" + t.toString());
}
});
}
And This is my logcat.
09-30 14:34:53.714 10763-10763/idea.mahdi.bime E/MSDF: [] list tostring
09-30 14:34:54.104 10763-10763/idea.mahdi.bime E/MSDF: [message_model{id=33, thread_id=2, user_id=15, body='چطوری', created_at='2018-09-29 10:28:26', updated_at='2018-09-29 10:28:26', deleted_at='null'}, message_model{id=30, thread_id=2, user_id=15, body='سلام', created_at='2018-09-29 09:30:40', updated_at='2018-09-29 09:30:40', deleted_at='null'}, message_model{id=7, thread_id=2, user_id=15, body='hi', created_at='2018-09-24 09:55:46', updated_at='2018-09-24 09:55:46', deleted_at='null'}] responsebody in api
09-30 14:34:54.104 10763-10763/idea.mahdi.bime E/MSDF: [message_model{id=33, thread_id=2, user_id=15, body='چطوری', created_at='2018-09-29 10:28:26', updated_at='2018-09-29 10:28:26', deleted_at='null'}, message_model{id=30, thread_id=2, user_id=15, body='سلام', created_at='2018-09-29 09:30:40', updated_at='2018-09-29 09:30:40', deleted_at='null'}, message_model{id=7, thread_id=2, user_id=15, body='hi', created_at='2018-09-24 09:55:46', updated_at='2018-09-24 09:55:46', deleted_at='null'}] message in api
09-30 14:34:54.104 10763-10763/idea.mahdi.bime
E/MESSAGE: getDateMessage successful
The problem is that when you call getDataMessage() it performs an asynchronous call (the retrofit enqueue() method). The server will be called to get the messages in a backgroud thread, while the android application will keep in the main thread.
Therefore, Log.e("MSDF",messages.toString()+" list tostring"); is called before the retrofit call is made, hence, there is no current data available yet. You should make sure that you are doing something with the data after it is completed loaded.
private List<message_model> messages = new ArrayList<>();
private void synchronization() {
getDateMessage(upadated_at);
// Anything you put here will be called before the data (messages) is loaded.
// Do not work with your messages here, they'll be null.
}
private void getDateMessage(String date) {
MessengerActivity.APIInterface apiInterface = app_net.getRetrofitInstance().create(MessengerActivity.APIInterface.class);
retrofit2.Call<List<message_model>> call = apiInterface.getMessageDate(Ptoken, date);
call.enqueue(new Callback<List<message_model>>() {
#Override
public void onResponse(Call<List<message_model>> call, Response<List<message_model>> response) {
if(response.isSuccessful()) {
messages.addAll(response.body());
Log.e("MSDF",response.body().toString()+" responsebody in call");
Log.e("MSDF",messages.toString()+" message in call");
Log.e("MESSAGE", "getDateMessage successful");
// Anything you want to do with the messages should be placed here. When you are sure the data is completed.
Log.e("MSDF",messages.toString()+" list tostring");
}
}
#Override
public void onFailure(Call<List<message_model>> call, Throwable t) {
Log.e("MESSAGE", "getDateMessage" + t.toString());
}
});
}
It's worth checking if (response.body() != null) before doing something with it to avoid NPE.
EDIT
As it was asked in the comments. A good solution (Google recommends it) is to fetch the data using a view model as described in this android dev guide article.
ViewModel approach is good because:
The data persist during configuration changes (for example, if you rotate your device, your list of messages will be still in your app).
It does not cause memory leaks.
You separate view data ownership from UI controller logic.
You can see the other advantages in the article.
1 - Add the view model dependecies in your build.gradle(Module:app) file
dependencies {
def lifecycle_version = "1.1.1"
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
}
See here the latest version.
2 - Create a ViewModel class
MessageViewModel.java
public class MessagesViewModel extends ViewModel {
private MutableLiveData<List<message_model>> messagesList;
public LiveData<List<message_model>> getMessages() {
if (messagesList == null) {
messagesList = new MutableLiveData<List<message_model>>();
loadMessages();
}
return messagesList;
}
private void loadMessages() {
MessengerActivity.APIInterface apiInterface = app_net.getRetrofitInstance().create(MessengerActivity.APIInterface.class);
retrofit2.Call<List<message_model>> call = apiInterface.getMessageDate(Ptoken, date);
call.enqueue(new Callback<List<message_model>>() {
#Override
public void onResponse(Call<List<message_model>> call, Response<List<message_model>> response) {
if(response.isSuccessful()) {
if (response.body() != null) {
messagesList.setValue(response.body());
}
}
}
#Override
public void onFailure(Call<List<message_model>> call, Throwable t) {
// Handle failure
}
});
}
}
3 - Get the messages in your activity
public class MainActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
// Create a ViewModel the first time the system calls an activity's onCreate() method.
// Re-created activities receive the same MyViewModel instance created by the first activity.
MessagesViewModel model = ViewModelProviders.of(this).get(MessagesViewModel.class);
model.getMessages().observe(this, messagesList -> {
// Do whatever you want with the list of messages.
});
}
}
Look how clean your activity is now.
Then you can implement a SwipeRefreshLayout if you want to allow your users to refresh the data.
If it is not enough, you can check this ReposViewModel
Finally, if calling retrofit is the main core of your app that is going to be released to the public, you should introduce MVVM approach using Dagger 2 and RxJava, as described in this article. (This is advanced)

getApplicationContext on a null reference in AppCompatActivity using Picasso

I'm loading a picture from a url into a bitmap. This code below worked on previous classes that extended Fragment. This time, I'm just copying the code and trying to use it in a class that extends AppCompatActivity. The only difference is how I'm getting context.
public void loadBitmap(String url) {
if (loadtarget == null) loadtarget = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
handleLoadedBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
mContext = MyActivity.this;
Picasso.with(mContext).load(url).into(loadtarget); //giving me null
}
In the original code, where I used it in a Fragment, I had it as
Picasso.with(getActivity()).load(url).into(loadtarget);
So now, since this class extends AppCompatActivity, I thought I could use "this" or MyActivity.this but that didn't work. I've tried initializing a Context variable "mContext" in onCreate and right before I load the image into the bitmap (like above) but neither worked. I've tried this.getApplicationContext() and I've also tried to pass mContext as a parameter in the loadBitmap() method but that didn't work either.
My URL string is correct. I'm just not sure how to tackle this problem after trying, what seems like, everything.
Last piece of information, the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:112)
at com.salty.seas.Driver.MyActivity.loadBitmap(MyActivity.java:144)
at com.salty.seas.Driver.MyActivity$1.onKeyEntered(MyActivity.java:61)
at com.firebase.geofire.GeoQuery$2.run(GeoQuery.java:126)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
In the comments to the question you said that the activity, the loadBitmap() belongs to, you actually instantiate yourself (in some other fragment) and use it as an utility class.
You should never create activites manually as they are managed by android and they have a lifecycle android maintains.
In your case the activity is not in a correct state (one of its internal fields is null), that's why you get NPE.
For utility methods create utility classes and call those from wherever you want.

Null pointer exception when calling method from a different class

When I attempt to call the method loadUserList() from another class, I get the following error:
Attempt to invoke virtual method android.content.res.Resources
android.content.Context.getResources() on a null object reference
This is my loadUserList method
public void loadUserList()
{
final ProgressDialog dia = ProgressDialog.show(this, null, getString(R.string.alert_loading));
ParseQuery<ParseObject> query = ParseQuery.getQuery("Chat_User");
query.whereEqualTo("receiver", ParseUser.getCurrentUser());
query.include("sender");
query.findInBackground(new FindCallback<ParseObject>()
{
#Override
public void done(List<ParseObject> li, ParseException e)
{
dia.dismiss();
if (li != null)
{
if (li.size() == 0)
Toast.makeText(com.yarnyard.UserList.this, R.string.msg_no_user_found,
Toast.LENGTH_SHORT).show();
uList = new ArrayList<ParseObject>(li);
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new UserAdapter());
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3)
{
loadUserList();
/*startActivity(new Intent(com.yarnyard.UserList.this, Chat.class)
.putExtra(Const.EXTRA_DATA, uList.get(pos).getUsername()));*/
}
});
}
else
{
Utils.showDialog(
com.yarnyard.UserList.this,
getString(R.string.err_users) + " "
+ e.getMessage());
e.printStackTrace();
}
}
});
}
This is how I am calling it
public void done(ParseException e)
{
UserList UserList = new UserList();
UserList.loadUserList();
}
My error log
07-30 14:14:56.219 13383-13383/com.anonimv2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.anonimv2, PID: 13383
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:85)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:74)
at android.content.Context.getString(Context.java:376)
at com.yarnyard.UserList.loadUserList(UserList.java:96)
at com.yarnyard.custom.CustomActivity.onOptionsItemSelected(CustomActivity.java:116)
at android.app.Activity.onMenuItemSelected(Activity.java:2882)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1131)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at android.widget.ActionMenuView.invokeItem(ActionMenuView.java:587)
at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:141)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5321)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
Any advice would be much appreciated.
Normal, non-static methods are called on objects, not on classes. This is a fine point that you really need to learn before using object oriented languages. Only then you will see, in practice, how you can connect objects by passing references.
The UserList objects that you construct in the done method is not the one you want to call, it's just an empty, uninitialized shell.
As I understand, you extend UserList from Context, right?
Then keep in mind that in Android never initial a Context object by yourself, it's framework's job..
In your case, because you create a context instance without attach to any baseContext, so when access to common resource, you got a NPE.
I guess that you are trying to move to a new Fragment or Actvity? Then read these link start activity switch fragment

Categories