I actually did part of this code on a normal activity but when I want to make it into a fragment class, I encountered some problem I did what I can to convert the code into a fragment class.
this is the fragment code
/**
* A simple {@link Fragment} subclass.
*/
public class ShoppingLstFragment extends Fragment {
public ShoppingLstFragment() {
// Required empty public constructor
}
private ArrayList<String> arraylisttodo;
private ArrayAdapter<String> arrayadaptertodo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_shopping_lst, container, false);
arraylisttodo = new ArrayList<String>();
arrayadaptertodo = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_activated_1 , arraylisttodo);
ListView listViewtodo = (ListView) view.findViewById(R.id.listviewtodo);
listViewtodo.setAdapter(arrayadaptertodo);
registerForContextMenu(listViewtodo);
try {
Log.i("ON CREATE", "on create has occured");
Scanner scanner = new Scanner(getContext().openFileInput("todo.txt"));
while (scanner.hasNextLine()){
String todo = scanner.nextLine();
arrayadaptertodo.add(todo);
}
scanner.close();
}catch (Exception e){
Log.i("ON CREATE", e.getMessage());
}
return view;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId() != R.id.listviewtodo) {
return;
}
menu.setHeaderTitle("What would you like to do?");
String[] options = {"Delete Product", "Return"};
for (String option : options) {
menu.add(option);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int selectedIndex = info.position;
if (item.getTitle().equals("Delete Product")) {
arraylisttodo.remove(selectedIndex);
arrayadaptertodo.notifyDataSetChanged();
}
return true;
}
public void onBackPressed() {
try {
Log.i("ON BACK PRESSED", "On back is pressed");
PrintWriter pw = new PrintWriter(getContext().openFileOutput("todo.txt", Context.MODE_PRIVATE));
for(String todo : arraylisttodo){
pw.println(todo);
}
pw.close();
} catch(Exception e) {
Log.i("ON BACK PRESSED", e.getMessage());
} getActivity().onBackPressed();
}
public void buttonaddClick(View v){
EditText todo = (EditText)getView().findViewById(R.id.todo);
String toDo = todo.getText().toString().trim();
if (toDo.isEmpty()) {
arrayadaptertodo.add(toDo);
todo.setText("");
}
}}
these methods onBackPressed()
and buttonaddclick()
is being said not used.
I'm new to android and java. how do you solve this error?