I have a dialog in which I use the list. It is required to read this list from the document.
There is a changeGroup method, where the array from the document will change. You need to pass this array to the DialogGroupSelection dialog. But using the group method from the Book class requires passing the Context . And here is the problem, I do not understand what exactly needs to be conveyed.
Lest I always try the same mistake:
Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets ()' on a null object reference.
At the same time, if you call the group method in MainActivity in onCreate , then there are no errors.
MainActivity:
public class MainActivity extends AppCompatActivity { DialogFragment dlg; Book book = new Book(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Создаем переменную типа Book String[] data = book.group(this); // Так работает нормально dlg = new DialogGroupSelection(); dlg.show(getFragmentManager(), "dlg"); } public String[] changeGroup(){ String[] dat = book.group(); // Какой Context передавать сюда? return dat; } public class Book{ // В переменную записываем имя файла String text = "list.xls"; InputStream fis; public String[] group(Context myContext){ try { //Открываем нужный документ AssetManager myAsset = myContext.getAssets(); fis = myAsset.open(text); // Создаем книгу Workbook wb = new HSSFWorkbook(fis); int number_sheets = wb.getNumberOfSheets()-1; //Создаем массив из перых ячеек каждого листа String[] group = new String[number_sheets]; for(int count_list = 0; count_list<number_sheets; count_list++) { group[count_list] = wb.getSheetAt(count_list).getRow(0).getCell(0).getStringCellValue(); } return group; } catch (IOException e){e.printStackTrace();} } } }
And the DialogGroupSelection dialog box. Code:
public class DialogGroupSelection extends DialogFragment implements DialogInterface.OnClickListener { MainActivity mainact = new MainActivity(); String[] list = mainact.changeGroup(); //String[] list = mainact.book.group(); Можно ли обращаться напрямую? И какой Context тогда использовать? int i=1; public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); adb.setTitle("Выберите свою группу") .setSingleChoiceItems(list, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { Toast.makeText(getActivity(), "Ваша группа: " + list[item], Toast.LENGTH_SHORT).show(); } }) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // User clicked OK, so save the mSelectedItems results somewhere // or return them to the component that opened the dialog } }); return adb.create(); } }