Я попытался получить активность context
от Fragment
onAttach()
метод.Получение контекста из фрагмента - исключение NullPointerException?
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity.getApplicationContext();
obj = new MySQLiteHelper(context);
...
}
Но, я все еще получаю NullPointerException
. Как мне структурировать код, чтобы избежать этого?
Вот мой фрагмент кода:
public class ListTab extends Fragment {
View view;
Context context ; // I just created reference here
MySQLiteHelper obj; // and initialised in onAttach()
String[][] table;
byte[][] images;
Bitmap[] bitmap;
String[] title = new String[10];
String[] init_price = new String[10];
String[] cur_price = new String[10];
int len,i;
private OnFragmentInteractionListener mListener;
public ListTab() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// not sure when this is called, so left this empty.
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_list_items, container, false);
obj.open(); //I'm getting an exception here - NullPointerException
obj.read();
table = obj.getTable();
images = obj.getImages();
len = obj.getLength();
...
//some code to inflate fragment with Listview
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity.getApplicationContext();
obj = new MySQLiteHelper(context);
...
//some code
}
...
// some other methods
}
Что является причиной этой проблемы? Может ли кто-нибудь объяснить мне, пожалуйста?
Всегда предоставляйте стек, если ваш вопрос включает отладку, упрощает процесс для читателей. – Marcus
Проблема не в контексте. Это было с растровым массивом в моем коде. Комментирование того, что сработало. Решить эту проблему сейчас. Спасибо за ваше время. – Nikhil