Attempt to invoke virtual method error when using the Butterknife - java

I know this question has been asked multiple times, but none of those solved my problem. The stacktrace looks like this.
02-09 19:39:20.364 18846-18846/com.michael1011.tweetcomposer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.michael1011.tweetcomposer, PID: 18846
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.michael1011.tweetcomposer/com.michael1011.tweetcomposer.login}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.support.design.widget.Snackbar.setText(Snackbar.java:334)
at android.support.design.widget.Snackbar.make(Snackbar.java:210)
at com.michael1011.tweetcomposer.login.onCreate(login.java:43)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
And the adapter class looks similar to this
package com.example.babu.moviemanager;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
Context context;
List<Movie> movieList;
public CustomAdapter(Context context, List<Movie> movieList) {
this.context = context;
this.movieList = movieList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Movie movie=movieList.get(position);
holder.title.setText(movie.getTitle());
holder.overview.setText(movie.getOverview());
Picasso.with(getcontext()).load(movie.getPosterPath()).into(holder.poster);
}
#Override
public int getItemCount() {
return movieList.size();
}
public Context getcontext() {
return context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.imageContainer)
ImageView poster;
#BindView(R.id.titleContainer)
TextView title;
#BindView(R.id.overviewContainer)
TextView overview;
#BindView(R.id.card)
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(itemView);
}
}
}

According to the butterknife documentation, the bind method that you used in the viewholder must accept either view target bind(this) or view target and view source bind(this,view). In your case change the bind method to bind(this,itemView), it should work.

Changing the ButterKnife dependencies to the latest version solved it for me.
dependencies {
...
implementation 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
}

Related

how to fix android app crashing on startup? [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 4 months ago.
i'm a begginner developer and the app in question is a test app for an api, from jkutner's tutorial on github. it is crashing as soon as it opens, which is weird, because i've used this exact same code at least thrice and it used to work. i'll leave the code and the logcat below, thank you in advance for your help!
MainActivity
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity
{
final EditText isbnInput = (EditText) findViewById(R.id.isbnInput);
final TextView textView = (TextView) findViewById(R.id.textView);
final Button button = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://venusdove.herokuapp.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
final BookService service = retrofit.create(BookService.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Book book = new Book(isbnInput.getText().toString());
Call<Book> createCall = service.create(book);
createCall.enqueue(new Callback<Book>() {
#Override
public void onResponse(Call<Book> _, Response<Book> resp) {
Book newBook = resp.body();
textView.setText("Created Book with ISBN: " + newBook.isbn);
}
#Override
public void onFailure(Call<Book> _, Throwable t) {
t.printStackTrace();
textView.setText(t.getMessage());
}
});
}
});
}
}
Book class
package com.example.myapplication;
import com.google.gson.annotations.SerializedName;
public class Book
{
#SerializedName("id")
int id;
#SerializedName("isbn")
String isbn;
public Book(int id, String isbn) {
this.id = id;
this.isbn = isbn;
}
public Book(String isbn) {
this.isbn = isbn;
}
}
BookService class
package com.example.myapplication;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
public interface BookService
{
#GET("books")
Call<List<Book>> all();
#GET("books/{isbn}")
Call<Book> get(#Path("isbn") String isbn);
#POST("books/new")
Call<Book> create(#Body Book book);
}
logcat
2022-10-19 08:56:03.651 8041-8041/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 8041
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: 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:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:655)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:852)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:819)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:261)
at com.example.myapplication.MainActivity.<init>(MainActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1174)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
You need to "find" view after they are created.
EditText isbnInput;
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isbnInput = (EditText) findViewById(R.id.isbnInput);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
}
It is because of findViewById. You should call it inside OnCreate. Because it needs View that it is being called from to be initialized.
private EditText isbnInput;
private TextView textView;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState)
{
isbnInput = (EditText) findViewById(R.id.isbnInput);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);

Android Studio Activity doesn't start

When starting my activity there is always an error message and the app does not open.
Error:
2022-05-11 23:18:12.470 17222-17222/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 17222
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myapplication/com.example.feuerwerkzndanlage.Biometric_Authentication}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8056)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
Caused by: 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:133)
at com.example.feuerwerkzndanlage.Biometric_Authentication.<init>(Biometric_Authentication.java:23)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1254)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3443)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3699) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:236) 
at android.app.ActivityThread.main(ActivityThread.java:8056) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967) 
Activity:
package com.example.feuerwerkzndanlage;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import java.util.concurrent.Executor;
public class Biometric_Authentication extends AppCompatActivity {
private TextView authStatusTv;
private BiometricPrompt biometricPrompt;
private BiometricPrompt.PromptInfo promptInfo;
Context context = getApplicationContext();
CharSequence error_txt = "Indentifizierung Fehlgeschlagen: ";
CharSequence suceed_txt = "Indentifizierung Erfolgreich";
CharSequence failed_txt = "Indentifizierung Fehlgeschlagen";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biometric_authentication);
authStatusTv = findViewById(R.id.authStatusTv);
Button btn_auth = findViewById(R.id.btn_auth);
Executor executor = ContextCompat.getMainExecutor(this);
biometricPrompt = new BiometricPrompt(Biometric_Authentication.this, executor, new BiometricPrompt.AuthenticationCallback() {
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
authStatusTv.setText("Indentifizierung Fehlgeschlagen: " + errString);
Toast.makeText(context, error_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationSucceeded(#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
authStatusTv.setText("Indentifizierung Erfolgreich");
Toast.makeText(context, suceed_txt, duration).show();
}
#SuppressLint("SetTextI18n")
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
authStatusTv.setText("Indentifizierung Fehlgeschlagen");
Toast.makeText(context, failed_txt, duration).show();
}
});
promptInfo = new BiometricPrompt.PromptInfo.Builder()
.setTitle("Biometrische Indentifizierung")
.setSubtitle("Login")
.setNegativeButtonText("Benutzer Passwort")
.build();
btn_auth.setOnClickListener(view -> biometricPrompt.authenticate(promptInfo));
}
}
Context context = getApplicationContext();
You can't do that at init time. You can't call any Context related functions, including getApplicationContect() until onCreate is called. This is because the framework hasn't fully initialized the activity before then. To make this work, you'd need to move this line into onCreate, and move any code that depends on this variable being set into onCreate or later as well.

MainActivity cannot be cast to Fragment

Im working on this project. When i run the program it have some runtime errors and app does not appears in emulator. it show the message app stopped. I think there is a error in OnAttach method. I tried many ways to solve the issue but nothing works.I'm new to Android development please help me to solve the issue.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.workout, PID: 26059
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.workout/com.example.user.workout.MainActivity}: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2534)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5643)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.example.user.workout.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java:6100)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5643) 
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:960) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: java.lang.ClassCastException: com.example.user.workout.MainActivity cannot be cast to com.example.user.workout.WorkoutListFragment$WorkoutListListener
at com.example.user.workout.WorkoutListFragment.onAttach(WorkoutListFragment.java:53)
at android.support.v4.app.Fragment.onAttach(Fragment.java:1340)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1372)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1659)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1905)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3715)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:114)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:374)
at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:39)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:68)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139) 
at com.example.user.workout.MainActivity.onCreate(MainActivity.java:14) 
at android.app.Activity.performCreate(Activity.java:6100) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2481) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5643) 
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:960) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
package com.example.user.workout;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class WorkoutListFragment extends ListFragment {
static interface WorkoutListListener{
void itemClicked(long id);
};
private WorkoutListListener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String [] names = new String[Workout.workouts.length];
for(int i =0; i < names.length;i++)
{
names[i] = Workout.workouts[i].getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
inflater.getContext(), android.R.layout.simple_list_item_1,names);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.listener = (WorkoutListListener)activity;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
if(listener!=null)
{
listener.itemClicked(id);
}
}
}
package com.example.user.workout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void itemClicked(long id)
{
WorkoutDetialFragment detials = new WorkoutDetialFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
detials.setWorkoutId(id);
ft.replace(R.id.fragment_container,detials);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
Your activity should implement *WorkoutListListener* interface and override its method itemClicked().
public class MainActivity extends AppCompatActivity implements WorkoutListListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void itemClicked(long id){
// handle your click here
}
}

NullPointerException: Attempt to invoke virtual method setLayoutManager on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am doing a challenge from Treehouse and they have given some initial project files to follow along. The problem is they're 2 years old and a lot of the code is outdated. I changed as much as I could, but apparently there still are some problems.
I try to run this code and it says it can't invoke setLayoutManager() on a null object reference. How can the object be null if I initialise it right before?
private void populate() {
StaggeredGridLayoutManager lm = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mAlbumList.setLayoutManager(lm);
This is all the code in the file.
package com.teamtreehouse.albumcover;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class AlbumListActivity extends Activity {
#BindView(R.id.album_list) RecyclerView mAlbumList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_album_list);
initTransitions();
ButterKnife.bind(this);
populate();
}
private void initTransitions() {
getWindow().setExitTransition(null);
getWindow().setReenterTransition(null);
}
interface OnVHClickedListener {
void onVHClicked(AlbumVH vh);
}
static class AlbumVH extends RecyclerView.ViewHolder implements View.OnClickListener {
private final OnVHClickedListener mListener;
#BindView(R.id.album_art)
ImageView albumArt;
public AlbumVH(View itemView, OnVHClickedListener listener) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
mListener = listener;
}
#Override
public void onClick(View v) {
mListener.onVHClicked(this);
}
}
private void populate() {
StaggeredGridLayoutManager lm = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mAlbumList.setLayoutManager(lm);
final int[] albumArts = {
R.drawable.mean_something_kinder_than_wolves,
R.drawable.cylinders_chris_zabriskie,
R.drawable.broken_distance_sutro,
R.drawable.playing_with_scratches_ruckus_roboticus,
R.drawable.keep_it_together_guster,
R.drawable.the_carpenter_avett_brothers,
R.drawable.please_sondre_lerche,
R.drawable.direct_to_video_chris_zabriskie };
RecyclerView.Adapter adapter = new RecyclerView.Adapter<AlbumVH>() {
#Override
public AlbumVH onCreateViewHolder(ViewGroup parent, int viewType) {
View albumView = getLayoutInflater().inflate(R.layout.album_grid_item, parent, false);
return new AlbumVH(albumView, new OnVHClickedListener() {
#Override
public void onVHClicked(AlbumVH vh) {
int albumArtResId = albumArts[vh.getLayoutPosition() % albumArts.length];
Intent intent = new Intent(AlbumListActivity.this, AlbumDetailActivity.class);
intent.putExtra(AlbumDetailActivity.EXTRA_ALBUM_ART_RESID, albumArtResId);
startActivity(intent);
}
});
}
#Override
public void onBindViewHolder(AlbumVH holder, int position) {
holder.albumArt.setImageResource(albumArts[position % albumArts.length]);
}
#Override
public int getItemCount() {
return albumArts.length * 4;
}
};
mAlbumList.setAdapter(adapter);
}
}
This is the exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jimulabs.googlemusicmock, PID: 30956
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jimulabs.googlemusicmock/com.teamtreehouse.albumcover.AlbumListActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at com.teamtreehouse.albumcover.AlbumListActivity.populate(AlbumListActivity.java:59)
at com.teamtreehouse.albumcover.AlbumListActivity.onCreate(AlbumListActivity.java:27)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Just a simple solution to this problem is, init your mAlbumLayout and pass it as a parameter in the populate() method. This will prevent it from getting null.

Android error, Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

My app is crashing every time, I couldn't find any solution for the issue.
The code is:
package com.example.juan.sem4;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Registrarse extends AppCompatActivity {
EditText txtNom, txtCor, txtPas;
Button btnRegistrarse;
BD_Usuarios bd=new BD_Usuarios(this,"BD1",null,1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrarse);
txtNom=(EditText)findViewById(R.id.txtRegNom);
txtCor=(EditText)findViewById(R.id.txtRegCor);
txtPas=(EditText)findViewById(R.id.txtPas);
btnRegistrarse=(Button)findViewById(R.id.btnRegistrarse);
btnRegistrarse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bd.abrir();
bd.registrarUsu(txtNom.getText().toString(),txtCor.getText().toString(),txtPas.getText().toString());
bd.cerrar();
txtCor.setText("");
txtNom.setText("");
txtPas.setText("");
txtNom.findFocus();
Toast.makeText(getApplicationContext(),"Se registro con exito",Toast.LENGTH_LONG).show();
finish();
}
});
}
}
The LOGCAT shows the following problem:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.juan.sem4.Registrarse$1.onClick(Registrarse.java:32)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
It seems that the issue is on the line 32 which is:
bd.registrarUsu(txtNom.getText().toString(),txtCor.getText().toString(),txtPas.getText().toString());
But honestly I can't see the problem in it.

Categories