[英]Android App - Error Crashing - ListView SetAdapter
My app is crashing and it only crashes when I add the line "listView.setAdapter(adapter);"我的应用程序崩溃了,只有当我添加“listView.setAdapter(adapter);”行时它才会崩溃the app is just 2 fragments connected to 1 main activity I am learning how to communicate.该应用程序只是连接到我正在学习如何交流的 1 个主要活动的 2 个片段。 I will include all the code, the top fragment is a list view, and the bottom is just a textview, objective is to click/press an item in the listview and the text should change.我将包含所有代码,顶部片段是一个列表视图,底部只是一个 textview,目标是单击/按下列表视图中的一个项目,文本应该会改变。 Also looks like some of the methods were depreciated since these notes so I have tried to work around it moving from OnActivityCreated to OnCreate in the fragment classes, and added a FragmentContainer instead of a Fragment in the xml.看起来有些方法自这些注释以来已贬值,所以我试图解决它从片段类中的 OnActivityCreated 移动到 OnCreate,并在 xml 中添加了 FragmentContainer 而不是 Fragment。
Code: fragment_text.xml代码:fragment_text.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TextFragment_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextFragment">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="@string/text_box" />
</FrameLayout>
package com.example.tourguide;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
* Use the {@link TextFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TextFragment extends Fragment
{
private TextView textView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public TextFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TextFragment.
*/
// TODO: Rename and change types and number of parameters
public static TextFragment newInstance(String param1, String param2) {
TextFragment fragment = new TextFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
textView = (TextView)getActivity().findViewById(R.id.textView1);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_text, container, false);
}
public interface OnFragmentInteractionListener
{
public void onFragmentInteraction(Uri uri);
}
}
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ListFragment_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ListFragment">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
package com.example.tourguide;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.ListView;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ListFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ListFragment extends Fragment implements AdapterView.OnItemClickListener
{
private ListView listView;
private String[] array;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ListFragment.
*/
// TODO: Rename and change types and number of parameters
public static ListFragment newInstance(String param1, String param2) {
ListFragment fragment = new ListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
listView = (ListView)getActivity().findViewById(R.id.listView1);
//Resources res = getResources();
array = getResources().getStringArray(R.array.string_array_cities);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list, container, false);
}
public interface OnFragmentInteractionListener
{
public void onFragmentInteraction(Uri uri);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)
{
}
}
activity_main.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:id="@+id/LinearLayout_1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragmentContainerView1"
android:name="com.example.tourguide.ListFragment"
android:layout_width="wrap_content"
android:layout_height="357dp"
tools:layout="@layout/fragment_list" />
<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragmentContainerView2"
android:name="com.example.tourguide.TextFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="@layout/fragment_text" />
</LinearLayout>
package com.example.tourguide;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.net.Uri;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements TextFragment.OnFragmentInteractionListener, ListFragment.OnFragmentInteractionListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onFragmentInteraction(Uri uri)
{
}
}
strings.xml
<resources>
<string name="app_name">Tour Guide</string>
<string name="hello_blank_fragment">Hello blank fragment</string>
<string name="text_box">default</string>
<string-array name="string_array_cities">
<item>Richmond</item>
<item>Vancouver</item>
<item>Toronto</item>
<item>New West</item>
<item>Montreal</item>
<item>Aldergrove</item>
</string-array>
</resources>
Exception: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.tourguide, PID: 32432 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tourguide/com.example.tourguide.MainActivity}: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class androidx.fragment.app.FragmentContainerView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3264) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android. Exception: E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.tourguide, PID: 32432 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tourguide/com.example.tourguide.MainActivity}: android. view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class androidx.fragment.app.FragmentContainerView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121) at android.app.ActivityThread. handleLaunchActivity(ActivityThread.java:3264) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android. app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7078) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) at Z4D236D9A2D102C5FE app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955) at android .os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7078) at java.lang.reflect. Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) at Z4D236D9A2D102C5FE 6AD1C50DA4BEC50Z.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class androidx.fragment.app.FragmentContainerView Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class androidx.fragment.app.FragmentContainerView 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.tourguide.ListFragment.onCreate(List 6AD1C50DA4BEC50Z.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) Caused by: android.view.InflateException: Binary XML file line #11: Binary XML file line #11: Error inflating class androidx.fragment.app. FragmentContainerView Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class androidx.fragment.app.FragmentContainerView Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter (android.widget.ListAdapter)' 在 com.example.tourguide.ListFragment.onCreate(List Fragment.java:72) at androidx.fragment.app.Fragment.performCreate(Fragment.java:2949) at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:278) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106) at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1971) at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:311) at androidx.fragment.app.FragmentContainerView.(FragmentContainerView.java:180) at androidx.f Fragment.java:72) at androidx.fragment.app.Fragment.performCreate(Fragment.java:2949) at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475) at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:278) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106) at androidx.fragment.app.FragmentManager. execSingleAction(FragmentManager.java:1971) at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:311) at androidx.fragment.app.FragmentContainerView.(FragmentContainerView.java:180) at androidx.f ragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:52) at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135) at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319) at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:819) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769) at android.view.LayoutInflater.rInflate(LayoutInflater.java:902) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:863) at ZC ragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:52) at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135) at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319) at androidx .fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:819) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769) at android.view. LayoutInflater.rInflate(LayoutInflater.java:902) 在 android.view.LayoutInflater.rInflateChildren(LayoutInflater.Z93F725A076333FE1C846ZD:844) 31B32364CE19CA8FCD150A417ECCE58Z.view.LayoutInflater.inflate(LayoutInflater.java:554) at android.view.LayoutInflater.inflate(LayoutInflater.java:461) at android.view.LayoutInflater.inflate(LayoutInflater.java:383) at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195) at com.example.tourguide.MainActivity.onCreate(MainActivity.java:16) at android.app.Activity.performCreate(Activity.java:7327) at android.app.Activity.performCreate(Activity.java:7318) at android.ap 31B32364CE19CA8FCD150A417ECCE58Z.view.LayoutInflater.inflate(LayoutInflater.java:554) at android.view.LayoutInflater.inflate(LayoutInflater.java:461) at android.view.LayoutInflater.inflate(LayoutInflater.java:383) at androidx.appcompat.app .AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706) at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195) at com.example.tourguide.MainActivity.onCreate(MainActivity.java:16) at android.app. Activity.performCreate(Activity.java:7327) at android.app.Activity.performCreate(Activity.java:7318) at android.ap p.Instrumentation.callActivityOnCreate(Instrumentation.java:1275) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3101) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3264) E/AndroidRuntime: at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955) at android.o p.Instrumentation.callActivityOnCreate(Instrumentation.java:1275) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3101) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3264) E/AndroidRuntime: at android.app .servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android. app.ActivityThread$H.handleMessage(ActivityThread.java:1955) 在 android.o s.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7078) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964) s.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7078) at java.lang.reflect.Method .invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
Everything seems okay only a few lines of code need to be changed.一切似乎都很好,只需要更改几行代码。
Inside TextFragment you need to remove textView initialization from onCreate(...){} method to onCreateView(....) like as follows:在TextFragment 中,您需要将 textView 初始化从 onCreate(...){} 方法删除到 onCreateView(....) ,如下所示:
@Override
public void onCreate(....){
.......
.....
textView = (TextView)getActivity().findViewById(R.id.textView1); //remove this line of code.
}
@Override
public View onCreateView(......){
View view = inflater.inflate(R.layout.fragment_text, container, false);
textView = view.findViewById(R.id.textView1); //you need to initialize textview here.
return view;
}
And, Inside ListFragment you need to remove all code of initialization from onCreate(..){} to onCreateView(...){} like as follows:而且,在ListFragment 中,您需要从 onCreate(..){} 到 onCreateView(...){} 中删除所有初始化代码,如下所示:
@Override
public void onCreate(...){
.......
....
...
//remove all this code to another method.
/*listView = (ListView)getActivity().findViewById(R.id.listView1);
//Resources res = getResources();
array = getResources().getStringArray(R.array.string_array_cities);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);*/
}
@Override
public View onCreateView(.....){
View view = inflater.inflate(R.layout.fragment_list, container, false);
listView = view.findViewById(R.id.listView1);
array = getResources().getStringArray(R.array.string_array_cities);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
return view;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.