当我运行以下内容时,我收到NullPointerException
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)
at com.example.amirtau.helloworld.app.MainActivity$PlaceholderFragment.<init>(MainActivity.java:69)
(以下代码中提到第69行)
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
String[] data = {
"Mon 6/23 - Sunny - 31/17",
"Tue 6/24 - Foggy - 21/8",
"Wed 6/25 - Cloudy - 22/17",
"Thurs 6/26 - Rainy - 18/11",
"Fri 6/27 - Foggy - 21/10",
"Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
"Sun 6/29 - Sunny - 20/7"
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
//line 69
ArrayAdapter<String> forecastAdapter =
new ArrayAdapter<String>(
getActivity(), // The current context (this activity)
R.layout.list_item_forecast, // The name of the layout ID.
R.id.list_item_forecast_textview, // The ID of the textview to populate.
weekForecast);
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(forecastAdapter);
return rootView;
}
}
}
但是当我将:data,weekForecast,forecastAdapter插入onCreateView函数时,一切正常。
请帮我弄清楚代码行为不同的原因。
答案 0 :(得分:2)
getActivity()
会返回null
。 ArrayAdapter正在构造函数中实例化(当指定了赋值的成员变量时),此时片段尚未附加到Activity。
您可以声明 ArrayAdapter并等待在onCreateView
或onActivityCreated
答案 1 :(得分:0)
我通常喜欢在onAttach上做类似的事情(即片段完全附加到视图时):
@public void onAttach(Activity activity)
{
super.onAttach(activity);
//save an activity instance for use later
this.mActivity = activity;
//instantiate your array adapter and even pass values here
.............
}
这确保了当您到达onCreateView时,您已准备好数据!您也可以使用您的活动,不再像上述问题那样为空。
我希望这会有所帮助。