java.util.List com.example.cinemacgp.model.Response.getResults() - java

Process: com.example.cinemacgp, PID: 11977
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.cinemacgp.model.Response.getResults()' on a null object reference
at com.example.cinemacgp.activity.MainActivity$1.onResponse(MainActivity.java:52)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
My Code
public class MainActivity extends AppCompatActivity {
private void CallRetrofit() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<Response> call = apiInterface.getMovie(CATEGORY, API_KEY, LANGUAGE, PAGE);
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
//error
List<Result> mList = response.body().getResults();
adapter = new MovieAdapter(MainActivity.this, mList);
recyclerView.setAdapter(adapter);
Hello , sir . i get an error here. and I don't know how to solve it. I've been searching for hours. Can you help which part should I do. I've searched many ways, and do not know what to do
i think in Response.getResults()' on a null object reference
I've done the initialization earlier, and still the error
Help me to resolve errors. thankyou

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.

How to call one Fragment Method from another Fragment in android

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();

NullPointerException while use getter

Hello I have a problem with getter in my custom class, I don't know why it returns null every time. I'm setting value after response from server when it is without any errors. While I'm debugging, I see that response from server is OK and new instance of my object is created but when I try to get it in my activity there is a null. Here is couple lines of code where is a problem (in my opinion).
method from my custom class:
public void responseFromServer(){
showProgressDialog();
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
TitleInterface titleInterface = retrofit.create(TitleInterface.class);
Call<MovieResponse> call = titleInterface.getMovie(API_KEY,movie);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
List<Movie> movieList = response.body().getMovieList();
ItemAdapter itemAdapter = new ItemAdapter(context.getApplicationContext(),generateData(movieList));
setItemAdapter(itemAdapter);
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Toast.makeText(context, "ERROR", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
and here is my Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
movieListView = (ListView) findViewById(R.id.movieListView);
String movie = getIntent().getStringExtra(TAG);
presenter = new Presenter(this,movie);
presenter.responseFromServer();
item=presenter.getItemAdapter();
movieListView.setAdapter(presenter.getItemAdapter());
presenter.getItemAdapter().notifyDataSetChanged();
presenter.getProgressDialog().dismiss();
}
Thanks for any help.
It seems like your request haven't finished when the view is created. If you want to make your call synchronous use this:
Call<MovieResponse> call = titleInterface.getMovie(API_KEY,movie);
Response<MovieResponse> responseBody = call.execute();
List<Movie> movieList = response.body().getMovieList();
You are using asynchronous calls in your app, so try to replace all necessary methods for updating UI from onCreate() to onResponse(). It should help. If you want to use Retrofit synchronous calls, the best practice for that is Loaders.

Using getIdentifier() to Find ID of Image

I am trying to get id of an image by using following code.
public class MovieActivity extends ActionBarActivity {
private Context con;
String name = "test";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
con = MovieActivity.this;
setContentView(R.layout.activity_movie);
}
public void updateScreen(){
int imageResource = con.getResources().getIdentifier("drawable/" + name , null, con.getPackageName());
}
}
When I run it, I get exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
I thought the problem was Context so I added con variable which gets context when code runs. I made some researches and tried another methods but I got same exception every time. Can anyone help me?
EDIT: When I use the same code line in MainActivity, it works perfectly. But in another class, it fails.
public class SomeMovie extends MovieActivity { }
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
SomeMovie movie = new SomeMovie();
movie.updateScreen();
}
}
SomeMovie class is child of MovieActivity class. I call the method on that. I debugged the code and noticed that Context is null when code gets into updateScreen() method. Is it wrong to use inheritance on activity classes?
Change
int imageResource = con.getResources().getIdentifier("drawable/" + name , null, con.getPackageName());
to
int imageResource = getResources().getIdentifier("drawable/" + name , null, con.getPackageName());
You are already in an Activity's context, so use it. (No need to use the this keyword to refer to it)
EDIT:
You are not defining a layout for the SomeMovie Activity, so its context is always null.
You have to define the activity's layout in its onCreate method :
public class SomeMovie extends MovieActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.somemoviexml);
...
}
}

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