Runtime Exception on recyclerview - java

I am trying to open an activity which has recyclerView in it on the click of recyclerView of first activity. But now when I'm clicking the recyclerView app is crashing with the following message.
10-18 09:30:49.912 13018-13018/in.mumbaitravellers.mtleaders
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.mumbaitravellers.mtleaders, PID: 13018
java.lang.RuntimeException: Unable to start activity
ComponentInfo{in.mumbaitravellers.mtleaders/in.mumbaitravellers.mtleaders.activity.DetailActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a
null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a
null object reference
at
in.mumbaitravellers.mtleaders.activity.DetailActivity.setupRecycler(DetailActivity.java:120)
at
in.mumbaitravellers.mtleaders.activity.DetailActivity.onCreate(DetailActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6245)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 
10-18 09:31:13.376 1801-2412/? E/native: do suspend false
The java code is as follows:
public class DetailActivity extends AppCompatActivity {
private ExpenseAdapter adapter;
private Realm realm;
private LayoutInflater inflater;
private FloatingActionButton fab;
private RecyclerView recycler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
fab = (FloatingActionButton) findViewById(R.id.fab);
recycler = (RecyclerView) findViewById(R.id.recycler);
//get realm instance
this.realm = RealmController.with(this).getRealm();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*String event = getIntent().getStringExtra("eventName");
TextView tv = (TextView) findViewById(R.id.txt_EventName);
tv.setText(event);*/
setupRecycler();
if (!Prefs.with(this).getPreLoad()) {
setRealmData();
}
// refresh the realm instance
RealmController.with(this).refresh();
// get all persisted objects
// create the helper adapter and notify data set changes
// changes will be reflected automatically
setRealmAdapter(RealmController.with(this).getExpenses());
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inflater = DetailActivity.this.getLayoutInflater();
View content = inflater.inflate(R.layout.activity_add_new_expense, null);
final EditText editExpense = (EditText) content.findViewById(R.id.edtxt_expense);
final EditText editDescription = (EditText) content.findViewById(R.id.edtxt_description);
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
builder.setView(content)
.setTitle("Add Expense")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Expense expense = new Expense();
expense.setId((int) (RealmController.getInstance().getExpenses().size() + System.currentTimeMillis()));
expense.setAmount(editExpense.getText().toString());
expense.setDescription(editDescription.getText().toString());
realm.beginTransaction();
realm.copyToRealm(expense);
realm.commitTransaction();
adapter.notifyDataSetChanged();
// scroll the recycler view to bottom
recycler.scrollToPosition(RealmController.getInstance().getExpenses().size() - 1);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
public void setRealmAdapter(RealmResults<Expense> expenses) {
RealmExpenseAdapter realmExpenseAdapter = new RealmExpenseAdapter(this.getApplicationContext(), expenses, true);
adapter.setRealmAdapter(realmExpenseAdapter);
adapter.notifyDataSetChanged();
}
private void setupRecycler() {
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recycler.setHasFixedSize(true);
// use a linear layout manager since the cards are vertically scrollable
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
// create an empty adapter and add it to the recycler view
adapter = new ExpenseAdapter(this);
recycler.setAdapter(adapter);
}
private void setRealmData() {
ArrayList<Expense> expenses = new ArrayList<>();
for (Expense e : expenses) {
// Persist your data easily
realm.beginTransaction();
realm.copyToRealm(e);
realm.commitTransaction();
}
Prefs.with(this).setPreLoad(true);
}
}
And the xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_detail" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_action_add" />
</android.support.design.widget.CoordinatorLayout>
Recycler View Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_expense"
style="#style/AppTheme.Card.Margins"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/text_amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_small"
android:paddingBottom="#dimen/margin_normal"
android:paddingLeft="#dimen/margin_large"
android:paddingRight="#dimen/margin_large"
android:paddingTop="#dimen/margin_large"
android:textColor="#555555"
android:text="\u20B9"
android:textSize="40dp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="25dp"
android:id="#+id/text_description"
android:textSize="20dp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Content Detail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recyclerExpense"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_detail"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
What is wrong in code, please help.
Thanks in advance!

Your problem lies in incorrect search of RecyclerView
Change your code:
recycler = (RecyclerView) findViewById(R.id.recycler);
to
recycler = (RecyclerView) findViewById(R.id.recyclerExpense);

Related

Empty Exposed Dropdown menu when placed inside a custom dialog layout

I'm trying to implement an Exposed Dropdown menu on an AlertDialog with a custom layout defined in dialog_main_createremote.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_marginTop="10dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/dialog_main_textinput"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Category">
<AutoCompleteTextView
android:id="#+id/dialog_main_dropdown"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:inputType="none"/>
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
As per Material Design Guidelines, items need a layout for the dropdown menu to appear, so I created the following in the dropdown_item.xml file:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?attr/textAppearanceSubtitle1" />
Finally, I started to generate the AlertDialog with a MaterialAlertDialogBuilder, then defined and instantiated a LayoutInflater which I used to get dialog's custom view and get access to the setAdapter method, but after setting the adapter and showing the dialog all I can get is an Outlined TextInputLayout without any dropdown menu.
So that's it, thanks in advance for any suggestions/solutions, also, as you may have noticed, I'm new to android development, so, if possible and of course, if you have time in your hands, elaborate your answer or point to a specific resource where I could get more info.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private RemoteListViewModel remoteListViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.main_recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final RemoteAdapter adapter = new RemoteAdapter();
recyclerView.setAdapter(adapter);
remoteListViewModel = new ViewModelProvider(this).get(RemoteListViewModel.class);
remoteListViewModel.getAllRemotes().observe(this, new Observer<List<Remote>>() {
#Override
public void onChanged(#Nullable List<Remote> remotes) {
adapter.setRemotes(remotes);
}
});
ExtendedFloatingActionButton createButton = findViewById(R.id.create_efab);
createButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(MainActivity.this);
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
final View inflatedView = inflater.inflate(R.layout.dialog_main_createremote, null);
AutoCompleteTextView actv = inflatedView.findViewById(R.id.dialog_main_dropdown);
String categories[] = getResources().getStringArray(R.array.categories);
actv.setAdapter(new ArrayAdapter(MainActivity.this, R.layout.dropdown_item, categories));
builder.setView(R.layout.dialog_main_createremote);
builder.setTitle("Set control params");
builder.setNegativeButton("Nope", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("Okey", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
});
}
}

why setOnClickListener doesnt work in my view pager?

I have a view pager and cardview in my activity
and define lottie animation for my favorite btn
but the code of setOnClickListener didnt work and app did crash when i go to this activity
when i comment the setOnClickListener code, it will ok
and also the code is working well in another activity
this is my java activity code
public class MainActivity3 extends AppCompatActivity {
ImageView imageView;
String[] money;
boolean switchIsOn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
//favorite animation button
final LottieAnimationView animatedSwitchButton =(LottieAnimationView) findViewById(R.id.fav_lot);
animatedSwitchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (switchIsOn){
animatedSwitchButton.setSpeed(-1);
animatedSwitchButton.playAnimation();
switchIsOn = false;
}else {
animatedSwitchButton.setSpeed(1);
animatedSwitchButton.playAnimation();
switchIsOn = true;
}
}
});
money = getResources().getStringArray(R.array.money);
ViewPager mViewPager = findViewById(R.id.viewPager);
CardPagerAdapters mCardAdapter = new CardPagerAdapters();
for (String s : money) {
mCardAdapter.addCardItem(new CardItemString(s));
}
mViewPager.setAdapter(mCardAdapter);
mViewPager.setOffscreenPageLimit(3);
}
}
and the adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardView"
android:layout_width="250dp"
android:layout_height="320dp"
app:cardCornerRadius="20dp"
android:layout_gravity="center"
android:backgroundTint="#00FFFFFF">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#6FCDDC39"
android:padding="15dp">
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif-black"
android:gravity="center_horizontal"
android:text="#string/app_name"
android:textColor="#075AFF"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/fav_lot"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.533"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/titleTextView"
app:lottie_rawRes="#raw/fav" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
the logcat error is
2020-11-24 16:47:40.817 11330-11330/com.paradise.myapplication4 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.paradise.myapplication4, PID: 11330
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paradise.myapplication4/com.paradise.myapplication4.MainActivity3}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setOnClickListener(android.view.View$OnClickListener)' 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:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.paradise.myapplication4.MainActivity3.onCreate(MainActivity3.java:26)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
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:440) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
mainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:overScrollMode="never"
android:paddingVertical="100dp"
android:paddingHorizontal="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"/>
</RelativeLayout>
cardIPagerAdapter java code
public class CardPagerAdapters extends PagerAdapter {
private final List<CardView> mViews;
private final List<CardItemString> mData;
private float mBaseElevation;
public CardPagerAdapters() {
mData = new ArrayList<>();
mViews = new ArrayList<>();
}
public void addCardItem(CardItemString item) {
mViews.add(null);
mData.add(item);
}
public int getCount() {
return mData.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.adapter, container, false);
container.addView(view);
bind(mData.get(position), view);
CardView cardView = view.findViewById(R.id.cardView);
if (mBaseElevation == 0) {
mBaseElevation = cardView.getCardElevation();
}
cardView.setMaxCardElevation(mBaseElevation * 1);
mViews.set(position, cardView);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
mViews.set(position, null);
}
private void bind(CardItemString item, View view) {
TextView titleTextView = view.findViewById(R.id.titleTextView);
titleTextView.setText(item.getTitle());
}
}
Your animatedSwitchButton is null because you use findViewById() on your current object, which is your MainActivity3. This Activity doesn't contain the View with the ID fav_lot in adapter.xml though, since its layout-file is set to activity_main3.xml.
So you need to use findViewById() on the object you attached your adapter.xml to. This could be mViewPager.findViewById(R.id.fav_lot) for example, although I am not sure what your adapter.xml is actually attached to.

RecyclerView has no LayoutManager android.support.v7.widget.RecyclerView

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.liliyu.easyresumebuilder, PID: 11145
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.liliyu.easyresumebuilder/com.example.liliyu.easyresumebuilder.MainActivity}: android.view.InflateException: Binary XML file line #10: RecyclerView has no LayoutManager android.support.v7.widget.RecyclerView{df7f7c9 VFED..... ......I. 0,0-0,0 #7f070061 app:id/main_activity1}, adapter:null, layout:null, context:com.example.liliyu.easyresumebuilder.MainActivity#2857d33
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_activity1"
tools:context="com.example.liliyu.easyresumebuilder.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/spacing_medium"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/user_name_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/spacing_small"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/user_picture"
android:gravity="center_vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/caption_text_size"
tools:text="Your name" />
</LinearLayout>
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/user_name_layout"
android:layout_toLeftOf="#+id/user_picture"
tools:text="Your email" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.RecyclerView>
MainActivity.java
#SuppressWarnings("ConstantConditions")
public class MainActivity extends AppCompatActivity {
private BasicInfo basicInfo;
private RecyclerView recyclerView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadData();
setupUI();
}
private void setupUI() {
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.main_activity1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
setupBasicInfo();
}
private void setupBasicInfo() {
((TextView) findViewById(R.id.name)).setText(TextUtils.isEmpty(basicInfo.name)
? "Your name"
: basicInfo.name);
((TextView) findViewById(R.id.email)).setText(TextUtils.isEmpty(basicInfo.email)
? "Your email"
: basicInfo.email);
ImageView userPicture = (ImageView) findViewById(R.id.user_picture);
if (basicInfo.imageUri != null) {
ImageUtils.loadImage(this, basicInfo.imageUri, userPicture);
} else {
userPicture.setImageResource(R.drawable.user_ghost);
}
findViewById(R.id.edit_basic_info).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BasicInfoEditActivity.class);
intent.putExtra(BasicInfoEditActivity.KEY_BASIC_INFO, basicInfo);
startActivityForResult(intent, REQ_CODE_EDIT_BASIC_INFO);
}
});
}
private void loadData() {
connectAndGetApiData();
basicInfo = basicInfo == null ? new BasicInfo() : basicInfo;
}
public void connectAndGetApiData() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
ResumeService resumeService=retrofit.create(ResumeService.class);
Call<Resume> call =resumeService.getResume();
try {
call.enqueue(new Callback<Resume>() {
#Override
public void onResponse(Call<Resume> call, Response<Resume> response) {
recyclerView.setAdapter(new ResumeAdapter(getApplicationContext(),response.body()));
}
#Override
public void onFailure(Call<Resume> call, Throwable throwable) {
System.out.println(throwable.toString());
}
});
}catch(Throwable e){
e.printStackTrace();
}
}
}
Add a parentLayout (could be LinearLayout) to your RecyclerView and remove child from your RecyclerView.
You can't put children inside a RecyclerView in XML. It looks like what you have there currently is what you want to be in your ViewHolder. That's not how to do it.
Make a new layout XML file and move what's wrapped in your RecyclerView into that file.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
//delete all elements
</android.support.v7.widget.RecyclerView
>

java.lang.NullPointerException error in GridView making app crash

I created a 2x2 grid where the first 3 grids has three(Thingspeak) charts imported from GitHub(https://github.com/MacroYau/ThingSpeakAndroid)and the fourth grid will be implemented later so for the time being I just added a blank chart in it.
I have checked out all similar questions on stackoverflow and read their answers and I have understood the error in the logcat at line 60(chartView = (LineChartView) findViewById(R.id.chart);) means that this id is pointing to null but I don't know how to solve it as chart is present as an id in my activity_main.xml layout.
I have used the following files: activity_main.xml, main.xml, TempHumidity.java and GridViewAdapter.java
Code snippet from TempHumidity.java
public class TempHumidity extends AppCompatActivity {
private ThingSpeakChannel tsChannel, tsChannel1, tsChannel2;
private ThingSpeakLineChart tsChart, tsChart1, tsChart2;
private LineChartView chartView, chartView1, chartView2;
GridView simpleGrid;
int charts[] = {R.id.chart, R.id.chart1, R.id.chart2};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
simpleGrid = (GridView) findViewById(R.id.simpleGridView); // init GridView
// Create an object of CustomAdapter and set Adapter to GirdView
GridViewAdapter customAdapter = new GridViewAdapter(getApplicationContext(), charts);
simpleGrid.setAdapter(customAdapter);
// Connect to ThinkSpeak Channels
tsChannel = new ThingSpeakChannel(377467);
tsChannel1 = new ThingSpeakChannel(357670);
tsChannel2 = new ThingSpeakChannel(377509);
// Set listener for Channel feed update events
tsChannel.setChannelFeedUpdateListener(new ThingSpeakChannel.ChannelFeedUpdateListener() {
#Override
public void onChannelFeedUpdated(long channelId, String channelName, ChannelFeed channelFeed) {
// Show Channel ID and name on the Action Bar
getSupportActionBar().setTitle(channelName);
getSupportActionBar().setSubtitle("Channel " + channelId);
// Notify last update time of the Channel feed through a Toast message
Date lastUpdate = channelFeed.getChannel().getUpdatedAt();
Toast.makeText(TempHumidity.this, lastUpdate.toString(), Toast.LENGTH_LONG).show();
}
});
// Fetch the specific Channel feed
tsChannel.loadChannelFeed();
// Create a Calendar object dated 1 minutes ago
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, -1);
// Configure LineChartView
chartView = (LineChartView) findViewById(R.id.chart); //Logcat error points here
chartView.setZoomEnabled(false);
chartView.setValueSelectionEnabled(true);
GridViewAdapter.java
public class GridViewAdapter extends BaseAdapter {
private Context context;
private final int[] charts;
LayoutInflater inflter;
public GridViewAdapter(Context Appcontext, int[] charts) {
this.context = Appcontext;
this.charts = charts;
inflter = (LayoutInflater.from(Appcontext));
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_main, null); // inflate the layout
LineChartView cv = (LineChartView) view.findViewById(R.id.chart); // get the reference of ImageView
return view;
}
#Override
public int getCount() {
return charts.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--
-->
<GridView
android:id="#+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
android:padding="1dp"
android:numColumns="2" />
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Container LinearLayout -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Row 1 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<lecho.lib.hellocharts.view.LineChartView
android:id="#+id/chart"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<lecho.lib.hellocharts.view.LineChartView
android:id="#+id/chart1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
<!-- Row 2 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<lecho.lib.hellocharts.view.LineChartView
android:id="#+id/chart2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<lecho.lib.hellocharts.view.LineChartView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.macroyau.thingspeakandroid.demo/com.macroyau.thingspeakandroid.demo.TempHumidity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299)
at android.app.ActivityThread.access$700(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5283)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.macroyau.thingspeakandroid.demo.TempHumidity.onCreate(TempHumidity.java:60)
at android.app.Activity.performCreate(Activity.java:5283)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299) 
at android.app.ActivityThread.access$700(ActivityThread.java:150) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5283) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 
at dalvik.system.NativeStart.main(Native Method) 
01-14 17:11:28.007 23142-23146/com.macroyau.thingspeakandroid.demo
D/dalvikvm: GC_CONCURRENT freed 587K, 19% free 8887K/10932K, paused 4ms+22ms, total 114ms
When I run the codes(as it is in GitHub) without adding two similar charts in a GridView:
Currently my activity_main.xml layout looks like this:
As Mike M. in the comments pointed out that the chart id is not present in the main.xml file which is the reason why it pointing to null.
All I had to do is remove the main.xml file and set the layout to activity_main.xml in the onCreate method like this:
setContentView(R.layout.activity_main) (as I have already made a 2x2 layout in it activity_main.xml)
and remove the GridViewAdapter.java.

Navigation drawer header textview nullpointerexception

I have an 2 activity and a service, in first I have navigation drawer, and 2 textviews in its header, and I must change their text sometimes, in service there is some data that i need
On first run everything is perfect, but when I go to the first activity from second, I have nullpointerexception in textviews. What causes it, and how to fix?
//First
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Navigation drawer init
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarMain);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view_main);
navigationView.setNavigationItemSelectedListener(this);
intent = new Intent("playbackservice");
sConn = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(LOG_TAG, "MainActivity onServiceConnected");
service = ((PlaybackService.PlaybackServiceBinder) binder).getService();
bound = true;
prepareLayout();
}
public void onServiceDisconnected(ComponentName name) {
Log.d(LOG_TAG, "MainActivity onServiceDisconnected");
bound = false;
}
};
}
private void prepareLayout() {
Log.d(LOG_TAG, "prepareLayout: Running");
((TextView) findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
((TextView) findViewById(R.id.artistNavhead)).setText(currentSong.getArtist());
}
And
//Layout nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:gravity="bottom"
android:orientation="vertical"
android:background="#color/colorPrimaryDark"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/default_song_name"
android:id="#+id/songNameNavhead"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/default_artist"
android:id="#+id/artistNavhead"/>
</LinearLayout>
And
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view_main"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"/>
</android.support.v4.widget.DrawerLayout>
Error
05-12 19:34:05.001 11086-11086/iskandarovlev.myitschool.ru.lyricplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: iskandarovlev.myitschool.ru.lyricplayer, PID: 11086
java.lang.NullPointerException
//MainActivity.java:302 is
//((TextView) header.findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
//this line
at iskandarovlev.myitschool.ru.lyricplayer.MainActivity.prepareLayout(MainActivity.java:302)
at iskandarovlev.myitschool.ru.lyricplayer.MainActivity.access$700(MainActivity.java:48)
at iskandarovlev.myitschool.ru.lyricplayer.MainActivity$3.onServiceConnected(MainActivity.java:355)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1140)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1157)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5542)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:657)
at dalvik.system.NativeStart.main(Native Method)
To successfuly find any widget in Navigation Drawer's header, you need to obtain header view first. This can be achieved by using getHeaderView() method:
View header = ((NavigationView)findViewById(R.id.navigation_view)).getHeaderView(0);
Then, having header pointing to the right ViewGroup with our widgets in it, you can use findViewById() as usual:
TextView tv = header.findViewById(R.id.songNameNavhead);
tv.setText(currentSong.getName());
Or in more compact manner:
((TextView)header.findViewById(R.id.songNameNavhead))
.setText(currentSong.getName());
private void prepareLayout() {
Log.d(LOG_TAG, "prepareLayout: Running");
((TextView) findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
((TextView) findViewById(R.id.artistNavhead)).setText(currentSong.getArtist());
}
These need to use the navigationDrawer's view and then it's header, not your activity's view, so it should be
View header = navigationView.getHeaderView(0)
((TextView) navigationViewHeader.findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
((TextView) navigationViewHeader.findViewById(R.id.artistNavhead)).setText(currentSong.getArtist());

Categories

Resources