ViewPager & crash, after rotation and swipe, due to a nullpointerexception - java

So I have a lengthy example, I created just for stack overflow. I can't seem to figure it out. I'm not a native Java programmer so that contributes to some confusion. But, this example requires 10 files, and is not just a code dump.
I've tried debugging this for numerous hours and as a last resort have created as concise of an example as I could of the issue, and have come here for help.
The following are the files, and at the bottom the stack trace. I'm really out of ideas of what to try. It's due to a nullpointerexception, that happens after I rotate the screen then try to slide in the ViewPager. I think should be an easy fix, but it hasn't been so for me.
Below are the java, and xml files, and stack trace. I think they are all necessary because they all are intertwined.
Here is a zip of the files too, if that's useful: https://www.dropbox.com/s/sbv4irar727tp1x/CrashExample.zip?dl=0
main.java
package me.spencernusbaum.crashexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import java.util.List;
import java.util.Vector;
/**
* Created by Spencer on 4/26/2015.
*/
public class main extends FragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
final List<Fragment> fragments = new Vector<Fragment>();
Fragment f2 = new fragment_view();
Fragment f1 = fragment_menu.newInstance(f2, pager);
fragments.add(f1);
fragments.add(f2);
pager.setAdapter(new FragmentPagerAdapter(this.getSupportFragmentManager()) {
#Override
public Fragment getItem(int i) {
return fragments.get(i);
}
#Override
public int getCount() {
return fragments.size();
}
});
}
}
fragment_menu.java
package me.spencernusbaum.crashexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Spencer on 4/26/2015.
*/
public class fragment_menu extends Fragment {
Fragment fragment;
ViewPager viewPager;
public static final fragment_menu newInstance(Fragment f, ViewPager p) {
fragment_menu result = new fragment_menu();
result.fragment = f;
result.viewPager = p;
return result;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_menu, null);
result.findViewById(R.id.button1).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
((fragment_view)fragment).setView(new fragment1());
return false;
}
});
result.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((fragment_view)fragment).setView(new fragment1());
viewPager.setCurrentItem(1, true);
}
});
result.findViewById(R.id.button2).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
((fragment_view)fragment).setView(new fragment2());
return false;
}
});
result.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((fragment_view)fragment).setView(new fragment2());
viewPager.setCurrentItem(1, true);
}
});
return result;
}
}
fragment_view.java
package me.spencernusbaum.crashexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Spencer on 4/26/2015.
*/
public class fragment_view extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_view, null);
}
public void setView(Fragment f) {
getFragmentManager().beginTransaction().replace(R.id.fragment, f).commit();
}
}
fragment1.java
package me.spencernusbaum.crashexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Spencer on 4/26/2015.
*/
public class fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, null);
}
}
fragment2.java
package me.spencernusbaum.crashexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Spencer on 4/26/2015.
*/
public class fragment2 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, null);
}
}
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Fragment1"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
</LinearLayout>
fragment_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button1"
android:text="Fragment 1"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp" />
<Button
android:id="#+id/button2"
android:text="Fragment 2"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
fragment_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
viewpager.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
The Stack Trace:
04-26 12:38:32.368 7635-7635/me.spencernusbaum.crashexample E/InputEventReceiver﹕ Exception dispatching input event.
04-26 12:38:32.368 7635-7635/me.spencernusbaum.crashexample E/MessageQueue-JNI﹕ Exception in MessageQueue callback: handleReceiveCallback
04-26 12:38:32.370 7635-7635/me.spencernusbaum.crashexample E/MessageQueue-JNI﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void me.spencernusbaum.crashexample.fragment_view.setView(android.support.v4.app.Fragment)' on a null object reference
at me.spencernusbaum.crashexample.fragment_menu$1.onTouch(fragment_menu.java:32)
at android.view.View.dispatchTouchEvent(View.java:8382)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2314)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1692)
at android.app.Activity.dispatchTouchEvent(Activity.java:2739)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2275)
at android.view.View.dispatchPointerEvent(View.java:8578)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4021)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3887)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5701)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5675)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5646)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5791)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-26 12:38:32.370 7635-7635/me.spencernusbaum.crashexample D/AndroidRuntime﹕ Shutting down VM
04-26 12:38:32.371 7635-7635/me.spencernusbaum.crashexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: me.spencernusbaum.crashexample, PID: 7635
java.lang.NullPointerException: Attempt to invoke virtual method 'void me.spencernusbaum.crashexample.fragment_view.setView(android.support.v4.app.Fragment)' on a null object reference
at me.spencernusbaum.crashexample.fragment_menu$1.onTouch(fragment_menu.java:32)
at android.view.View.dispatchTouchEvent(View.java:8382)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2430)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2119)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2314)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1692)
at android.app.Activity.dispatchTouchEvent(Activity.java:2739)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2275)
at android.view.View.dispatchPointerEvent(View.java:8578)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4021)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3887)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3468)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3476)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3449)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5701)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5675)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5646)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5791)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

When the display is rotated, android (by default) destroys the current activity, including all fragments (the current state of attached fragments and the activity is saved via onSaveInstanceState()).
After the rotate, the activity and attached fragments are re-created (again: by default) and previously saved state is restored (passed as Bundle to onCreate()).
For fragments the android runtime invokes their default, no-arguments constructor.
The newInstance() method of your fragment is never invoked for the re-created fragment, hence your fields are not properly initialized and thus null.

Related

I am getting an runtime error (Null Pointer Exception) while using ListView in Android Studio

I am making a Task Manager app using ListView to Show all the tasks.But I am getting this error
Process: com.example.taskmanager, PID: 29293
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.taskmanager/com.example.taskmanager.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.access$900(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5318)
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:922)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:717)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.taskmanager.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6024)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2426) 
at android.app.ActivityThread.access$900(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5318) 
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:922) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:717) 
what I think the error is that, I am sending wrong context in my custom adapter in MainActivity.java file
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.example.taskmanager.Model.DataClass;
import com.example.taskmanager.MyAdapter.MyAdapter;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List<DataClass> datalist= new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
DataClass data1 = new DataClass();
data1.setId(1);
data1.setStatus(0);
data1.setTask("yo yo yo");
datalist.add(data1);
datalist.add(data1);
datalist.add(data1);
datalist.add(data1);
datalist.add(data1);
ListView taskListView = findViewById(R.id.listView);
MyAdapter myadapter = new MyAdapter(getApplicationContext(),R.layout.new_task_layout,datalist);
taskListView.setAdapter(myadapter);
}
}
My custom Adapter is
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.taskmanager.Model.DataClass;
import com.example.taskmanager.R;
import java.util.List;
public class MyAdapter extends ArrayAdapter<DataClass> {
Context mcontext;
int lytresourceId;
List<DataClass> data;
public MyAdapter(#NonNull Context context, int resource, #NonNull List<DataClass> objects) {
super(context, resource, objects);
this.mcontext=context;
this.lytresourceId=resource;
this.data=objects;
}
#Nullable
#Override
public DataClass getItem(int position) {
return super.getItem(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View row, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mcontext);
row = inflater.inflate(lytresourceId,parent,false);
CheckBox checkbox;
checkbox=row.findViewById(R.id.checkBox);
DataClass mdata = data.get(position);
checkbox.setText(mdata.getTask());
return row;
}
}
My Xml file for activity Main is
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/TaskText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:text="Task"
android:textColor="#000000"
android:textSize="40sp"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/LinearLayout1"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="30dp"
android:layout_marginRight="20dp"
app:srcCompat="#android:drawable/ic_input_add" />
</RelativeLayout>
My custom layout file is
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="3dp"
app:cardCornerRadius="8dp"
android:layout_marginHorizontal="4dp"
android:layout_marginVertical="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="task1"
android:padding="4dp"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
My Data class is
package com.example.taskmanager.Model;
public class DataClass {
private int id,status;
private String task;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
}
I am also using a Splash Screen but, I don't think that is a problem because my app is crashing after the splash screen is over, and when the intent goes to MainActivity.
Can someone please tell me the error
Also, I don't think there are any Dependencies missing from my File.
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
You are getting this error because setContentView(R.layout.layoutname) is missing in MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is missing in your class
setContentView(R.layout.activity_main);
}
I think you are missing the setContentView(R.layout.activity_main) in the onCreate of MainActivity. Assuming activity_main is the xml file name. If not, replace it with actual name.
Due to this, your layout is never inflated and hence you should be getting null from findViewById(R.id.listView).

Inflating a fragment in main activity brings an error

I want to be able to swap between two fragments in my main activity class. But when inflating the fragment my application crashes. Below is my code:
This is the XML code where my fragment will be placed
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/rounded_dialog"
android:orientation="vertical"
app:behavior_hideable="false"
app:behavior_peekHeight="56dp"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
<fragment
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"/>
</LinearLayout>
This is the code for my Fragment
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.user.swim.AsyncTasks.GeoCodingTask;
public class SearchLocation extends Fragment {
private EditText destination;
private Button search;
private RecyclerView recyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_search_locatiom, null);
search = view.findViewById(R.id.search_destination);
destination = view.findViewById(R.id.destination);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
searchLocation(view);
return view;
}
Below is the code in my main activity to inflate the layout
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.fragment_place)!=null){
if (savedInstanceState != null) {
return;
}
SearchLocation fragment = new SearchLocation();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_place, fragment).commit();
}
I get the following errors in my logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.swim, PID: 20462
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.swim/com.example.user.swim.MainActivity}: android.view.InflateException: Binary XML file line #29: Binary XML file line #14: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #29: Binary XML file line #14: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class fragment
Caused by: java.lang.NullPointerException
at java.lang.VMClassLoader.findLoadedClass(Native Method)
at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.Fragment.instantiate(Fragment.java:617)
at android.app.FragmentContainer.instantiate(FragmentContainer.java:49)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3598)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:6182)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:338)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:783)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:866)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:827)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:995)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:862)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:827)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.example.user.swim.MainActivity.onCreate(MainActivity.java:87)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
This is the XML for fragment_search_locatiom
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_margin="10dp"
android:text="#string/where_would_you_like_to_go"
android:textAlignment="center" />
<EditText
android:id="#+id/destination"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="10dp"
android:drawablePadding="5dp"
android:drawableStart="#drawable/ic_search_black_24dp"
android:drawableLeft="#drawable/ic_search_black_24dp"
android:textSize="18sp"
android:inputType="text"
android:background="#drawable/rectangle"
android:hint="Search for destination"
android:maxLines="1"
android:imeOptions="actionDone"
android:textAlignment="textStart" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/search_destination"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/search_destination" />
</LinearLayout>
I don't want to add the name/class attribute in the XML for the fragment because when you look at the official documentation adding those attributes won't make it possible to change fragments at runtime.
Also i've tried changing the MainActivity class to extend ActivityFragment but after more research i've discovered that ActivityFragment is a subclass of AppCompatActivity.
i have copied your code and try to use it,when i use fragment in the SearchLocation it makes error so i changed it to Framlayout.
Can't realy tell what is wrong in your code but this worked after i made changes
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_place) != null) {
if (savedInstanceState != null) {
return;
}
SearchLocation fragment = new SearchLocation();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_place, fragment).commit();
}
}
SearchLocation java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class SearchLocation extends Fragment {
private EditText mSearch;
private Button mDestination;
private RecyclerView mRecyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search_location, null);
mSearch = view.findViewById(R.id.search_destination);
mDestination = view.findViewById(R.id.destination);
mSearch.setText("Hello world");
RecyclerView mRecyclerView = view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
/*searchLocation(view);*/
return view;
}
search_location xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".SearchLocation">
<EditText
android:id="#+id/search_destination"
android:layout_width="match_parent"
android:layout_height="0dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/destination"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/search_destination" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/destination" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can try with Framelayout instead of fragment like the following
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF" />

ViewPager and ListView in its layers

I apologize in advance for my terrible English.
My app should have 6 pages, and each of them will have a ListView with its own text.
The list consists of two TextView, so I made my own adapter for it:
BoxAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class BoxAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Kek> objects;
BoxAdapter(Context context, ArrayList<Kek> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Kek p = getProduct(position);
((TextView) view.findViewById(R.id.textView1)).setText(p.pozic);
((TextView) view.findViewById(R.id.textView1_2)).setText(p.name);
return view;
}
Kek getProduct(int position) {
return ((Kek) getItem(position));
}
}
And auxiliary class for him:
Kek.java
public class Kek {
String name;
String pozic;
Kek(String _pozic,String _describe) {
pozic = _pozic;
name = _describe;
}
}
Next for * * ViewPager* * I also created my adapter:
SlideAdapter.java
package com.github.helpme;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import java.util.List;
public class SlideAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragmentList;
public SlideAdapter (FragmentManager fragmentManager, List<Fragment> fragmentList) {
super(fragmentManager);
this.fragmentList = fragmentList;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
So far I have created 2 test sheets:
Activity_main_1.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView222"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="15dp"
android:text="НУ РАБОТАЙ ЖЕ ТЫ"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ListView
android:id="#+id/lvMain_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="#null"></ListView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
and class
Layout_1.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Layout_1 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.activity_main_1, container,false);
return viewGroup;
}
}
On the same analogy created 2nd page:
Activity_main_2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView222"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="15dp"
android:text="ЧУХ_ЧУХ"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ListView
android:id="#+id/lvMain_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="#null"></ListView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
and class
Layout_2.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class Layout_2 extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.activity_main_2, container,false);
return viewGroup;
}
}
And finally the main activity:
MainActivity.java
package com.github.helpme;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private SlideAdapter slideAdapter;
private ListView lvMain;
private BoxAdapter boxAdapter;
ArrayList<Kek> products = new ArrayList<Kek>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> list = new ArrayList<>();
list.add(new Layout_1());
list.add(new Layout_2());
viewPager = findViewById(R.id.rader);
slideAdapter = new SlideAdapter(getSupportFragmentManager(),list);
viewPager.setAdapter(slideAdapter);
fillData();
boxAdapter = new BoxAdapter(this, products);
lvMain = (ListView) findViewById(R.id.lvMain_1);
lvMain.setAdapter(boxAdapter);
}
// генерируем данные для адаптера
void fillData() {
for (int i = 1; i <= 20; i++) {
products.add(new Kek (i + ")", "Product " + i));
}
}
}
If you now run the application it will not start, and in the logs you will see:
2019-08-18 09:26:53.879 7138-7138/com.github.helpme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.github.helpme, PID: 7138
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.github.helpme/com.github.helpme.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3260)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2009)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.github.helpme.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
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:2009) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7319) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934) 
When I saw this, I tried to move the loading of the list to the layer classes * * ViewPager**
private ListView lvMain;
private BoxAdapter boxAdapter;
ArrayList<Kek> products = new ArrayList<Kek>();
fillData();
boxAdapter = new BoxAdapter(this, products);
lvMain = (ListView) findViewById(R.id.lvMain_1);
lvMain.setAdapter(boxAdapter);
void fillData() {
for (int i = 1; i <= 20; i++) {
products.add(new Kek (i + ")", "Product " + i));
}
}
But the compiler directly in the code gave an error:
BoxAdapter (android.content.Context, ArrayList) in
BoxAdapter cannot be applied to (com.github.helpme.Layout_1,
ArrayList)
So we got to the essence of this post: How to make Pager sheets with your list inside and how to fill it all.
UDP:
new error:
08-11 15:21:02.956 3653-3653/? E/ActivityThread: Service
com.android.email.service.EmailBroadcastProcessorService has leaked
ServiceConnection com.android.emailcommon.service.am#92c8ab8 that was
originally bound here android.app.ServiceConnectionLeaked: Service
com.android.email.service.EmailBroadcastProcessorService has leaked
ServiceConnection com.android.emailcommon.service.am#92c8ab8 that was
originally bound here at
android.app.LoadedApk$ServiceDispatcher.(LoadedApk.java:1092) at
android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:986) at
android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1303) at
android.app.ContextImpl.bindService(ContextImpl.java:1286) at
android.content.ContextWrapper.bindService(ContextWrapper.java:604) at
com.android.emailcommon.service.ak.a(SourceFile:181) at
com.android.emailcommon.service.ak.e(SourceFile:224) at
com.android.email.service.n.c(SourceFile:177) at
com.android.email.provider.b.a(SourceFile:198) at
com.android.email.provider.b.a(SourceFile:142) at
com.android.email.service.EmailBroadcastProcessorService.c(SourceFile:349)
at
com.android.email.service.EmailBroadcastProcessorService.onHandleIntent(SourceFile:1334)
at
android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.os.HandlerThread.run(HandlerThread.java:61)

I can't seem to get my fragment to load webview without crashing

So I'm making an app where the bottom navigation lets you click through different web pages and I've come across a problem. I can't seem to get it where the webview will function correctly inside the fragment class.
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="56dp">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_clever.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/clever_web"></WebView>
</RelativeLayout>
cleverfragment.java (the one im currently working with)
package com.port.schoool;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
webview.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("google.com");
return inflater.inflate(R.layout.fragment_clever, null);
}
}
mainactivity.java
package com.port.schoool;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
loadFragment(new ReadWorksFragment());
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fragment = new ReadWorksFragment();
break;
case R.id.navigation_dashboard:
fragment = new CleverFragment();
break;
case R.id.navigation_notifications:
fragment = new PortalFragment();
break;
}
return loadFragment(fragment);
}
}
Here is my logcat logs for the crashes:
2019-08-04 18:05:25.164 7425-7425/com.port.schoool E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.port.schoool, PID: 7425
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.webkit.WebView.findViewById(int)' on a null object reference
at com.port.schoool.CleverFragment.onCreateView(CleverFragment.java:20)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6960)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Replace your fragment with:
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_clever, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
webview = view.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("https://google.com");
}
}
Of note:
Your original code would not compile, as there is no findViewById() on Fragment
The right version of inflate() to use in onCreateView() is the one that takes the container and false as the second and third parameters
You configure your fragment's views in onViewCreated()
You need to call findViewById() on the inflated layout (view in onViewCreated()) and assign that to webview
You need to use a valid URL with loadUrl()
This sort of stuff should be covered in your book on Android app development.

I'm having problems with running the code on my device [duplicate]

This question already has answers here:
Explanation of ClassCastException in Java
(12 answers)
Closed 4 years ago.
Here is my problem. Below is my class (Events.java) below it is the error. I continue to run my code on my phone but continue to get that error. I don't know what exactly the problem is and I don't know how to fix it. I tried everything I looked up but kept getting errors. Please help I'm a noob obviously.
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public ListView onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(view.getContext(), AddEvent.class);
Uri currentVehicleUri = ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton) getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity context
EventContract.EventEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
This is the error
05-24 14:02:00.885 15627-15627/com.androidapp.restart E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 15627
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast
to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:47)
at com.androidapp.restart.Events.onCreateView(Events.java:31)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
This is the xml file (events.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/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.androidapp.restart.Events">
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/no_event_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="16dp"
android:gravity="center"
android:text="#string/no_cardetails"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
EDITED
Now I have change the xml to a Relative Layout, same issues, but here is another issue I found:
at android.app.Fragment.performCreateView(Fragment.java:2508)
Here is the section of the Fragment.java:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
This is an issue:
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
You try to inflate listview but inflater returns you a LinearLayout a parent of all views. You need inflate the LinearLayout instead of listview and this is causes to cast exception.
You are trying to cast a layout on a listview
add this #id into your LinearLayout and inflate it in your Activity
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#id/layout";
tools:context="com.delaroystudiuos.alarmreminder.MainActivity">
and then call it like this
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout, container, false);;
If you are trying to access your existing ListView item in the XML:
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
You will need to instead use:
View view = inflater.inflate(R.layout.nav_events, container, false);
eventListView = view.findViewById(R.id.list);

Categories

Resources