0

Someone marked this question as duplicate(What is a NullPointerException, and how do I fix it?), but that didn't help at all. I'm reposting the question.

//

I'm just learning myself and pretty new to android programming and java. I'm trying to get list from a txt file which is located in internal storage.

This is what I have done.

            try {
                path = getFilesDir().getAbsolutePath() ;
                FileInputStream inFs = new FileInputStream(new File(path.toString() + "/filesitem_" + Type + ".txt"));
                byte[] txt = new byte[inFs.available()];
                while (inFs.read(txt) != -1) {}
                String[] list_item = new String(txt).split(",");

                item_actv = (MultiAutoCompleteTextView) dlgView.findViewById(R.id.Item_AutoTxtView);
                ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, list_item);
                MultiAutoCompleteTextView.CommaTokenizer token = new MultiAutoCompleteTextView.CommaTokenizer();
                item_actv.setTokenizer(token);
                item_actv.setAdapter(adapter);
            } catch (IOException e) {
                Toast.makeText(Activity_list.this, "No item list.", Toast.LENGTH_SHORT).show();
            }

            itemQuant_np = (NumberPicker) dlgView.findViewById(R.id.ItemQuant_Np);
            itemQuant_np.setMinValue(1);
            itemQuant_np.setMaxValue(10);

            SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd", Locale.KOREA);
            Date current = new Date();
            date = formater.format(current);

            AlertDialog.Builder dlg2 = new AlertDialog.Builder(Activity_list.this)
                    .setTitle("New List")
                    .setView(dlgView)
                    .setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            try {
                                path = getFilesDir().getAbsolutePath() + "/" + Type + "_list";
                                FileOutputStream outFs = new FileOutputStream(new File(path + "/" + date + " list_" + Type + ".txt"), true);
                                listContent = item_actv.getText().toString() + "\t\t\t" + Integer.toString(itemQuant_np.getValue()) + "\n";
                                outFs.write(listContent.getBytes());
                                outFs.close();
                                Toast.makeText(Activity_list.this, "Saved.", Toast.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                Toast.makeText(Activity_list.this, "The file is already exist.", Toast.LENGTH_SHORT).show();
                            }
                        }
                    })
                    .setNegativeButton("Cancel", null);
            dlg2.show();

This dialog shows up when I click a item on a menu.

What it supposed to do is that the diglog would show up, and as I enter a name of item into MultiAutoCompleteTextView, it will show me available list which is from a txt file already saved in internal storage. In the txt file, there are list of items separated by comma(ex: apple,grape,orange). If I hit the Confirm button on the dialog after I fill MultiAutoCompleteTextView and set quantity of the item, it will create a new txt file into designated path.

The diglog shows up correctly, but the issues are

  1. the app stops when I hit "Confirm" button on the dialog (Unfortunately, the app has stopped)

(java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.MultiAutoCompleteTextView.getText()' on a null object reference)

  1. seems like it is not getting auto completion list for MultiAutoCompleteTextView
  2. it creates new txt file, but the content is empty

I really need your help :(

+Activity.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Manage snacks");
        setContentView(R.layout.subactivity);

        Intent intent = getIntent();
        Type = intent.getStringExtra("Type");

        fileList = (ListView) findViewById(R.id.FileList);

        arFiles = new ArrayList<>();

        File file = new File(getFilesDir().getAbsolutePath() + "/" + Type + "_list");
        arFiles.addAll(Arrays.asList(file.list()));

        flAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arFiles);
        fileList.setAdapter(flAdapter);
        fileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String name = arFiles.get(i);
                Intent intent = new Intent(Activity_list.this, Activity_listspec.class);
                intent.putExtra("Type", Type);
                intent.putExtra("fileName", name);
                startActivity(intent);
            }
        });
    }

        @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, 1, 0, "Add new item");
        menu.add(0, 2, 0, "Add new list");

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                dlgView = View.inflate(Activity_list.this, R.layout.dlg_newitem, null);
                edtTxtNewItem = (EditText) dlgView.findViewById(R.id.EdtTxtNewItem);
                AlertDialog.Builder dlg1 = new AlertDialog.Builder(Activity_list.this)
                    .setTitle("New item")
                    .setView(dlgView)
                    .setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            try {
                                path = getFilesDir().getAbsolutePath();
                                FileOutputStream outFs = new FileOutputStream(new File(path + "item_" + Type + ".txt"), true);
                                itemList = edtTxtNewItem.getText().toString() + ",";
                                outFs.write(itemList.getBytes());
                                outFs.close();
                                Toast.makeText(getApplicationContext(), edtTxtNewItem.getText().toString() + " Item added.", 0).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                    .setNegativeButton("Cancel", null);
                dlg1.show();

                return true;

            case 2:
                dlgView = View.inflate(Activity_list.this, R.layout.dlg_newlist, null);

                try {
                    path = getFilesDir().getAbsolutePath() ;
                    FileInputStream inFs = new FileInputStream(new File(path.toString() + "/filesitem_" + Type + ".txt"));
                    byte[] txt = new byte[inFs.available()];
                    while (inFs.read(txt) != -1) {}
                    String[] list_item = new String(txt).split(",");

                    item_actv = (MultiAutoCompleteTextView) dlgView.findViewById(R.id.Item_AutoTxtView);
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, list_item);
                    MultiAutoCompleteTextView.CommaTokenizer token = new MultiAutoCompleteTextView.CommaTokenizer();
                    item_actv.setTokenizer(token);
                    item_actv.setAdapter(adapter);
                } catch (IOException e) {
                    Toast.makeText(Activity_list.this, "No existing list.", Toast.LENGTH_SHORT).show();
                }

                itemQuant_np = (NumberPicker) dlgView.findViewById(R.id.ItemQuant_Np);
                itemQuant_np.setMinValue(1);
                itemQuant_np.setMaxValue(10);

                SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd", Locale.KOREA);
                Date current = new Date();
                date = formater.format(current);

                AlertDialog.Builder dlg2 = new AlertDialog.Builder(Activity_list.this)
                        .setTitle("New List")
                        .setView(dlgView)
                        .setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                try {
                                    path = getFilesDir().getAbsolutePath() + "/" + Type + "_list";
                                    FileOutputStream outFs = new FileOutputStream(new File(path + "/" + date + " list_" + Type + ".txt"), true);
                                    listContent = item_actv.getText().toString() + "\t\t\t" + Integer.toString(itemQuant_np.getValue()) + "\n";
                                    outFs.write(listContent.getBytes());
                                    outFs.close();
                                    Toast.makeText(Activity_list.this, "Saved.", Toast.LENGTH_SHORT).show();
                                } catch (IOException e) {
                                    Toast.makeText(Activity_list.this, "The file is already exist.", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("Cancel", null);
                dlg2.show();

                return true;

        }

        return false;
    }
}

subactivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/FileList"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

</LinearLayout>

dlg_newitem.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <EditText
        android:id="@+id/EdtTxtNewItem"
        android:hint="상품명"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"/>

</LinearLayout>

dlg_newlist.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

        <MultiAutoCompleteTextView
            android:id="@+id/Item_AutoTxtView"
            android:hint="상품명"
            android:completionThreshold="3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"/>

        <NumberPicker
            android:id="@+id/ItemQuant_Np"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp">
        </NumberPicker>

</LinearLayout>
Community
  • 1
  • 1
NcGYBer
  • 1
  • 2

1 Answers1

0

try this

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.dlg_newitem, null);

    dialogBuilder.setView(dialogView);
    dialogBuilder.setTitle("New item");

    EditText edtTxtNewItem= (EditText) dialogView.findViewById(R.id.EdtTxtNewItem);
    editText.setText("");
    dialogBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            try {
                path = getFilesDir().getAbsolutePath();
                FileOutputStream outFs = new FileOutputStream(new File(path + "item_" + Type + ".txt"), true);
                itemList = edtTxtNewItem.getText().toString() + ",";
                outFs.write(itemList.getBytes());
                outFs.close();
                Toast.makeText(getApplicationContext(), edtTxtNewItem.getText().toString() + " Item added.", 0).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    dialogBuilder.setNegativeButton("Cancel", null);
    AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();
Nas
  • 2,158
  • 1
  • 21
  • 38
  • Hey, thanks a lot. That looks much better. Actually case 1 part worked okay for me, but case 2 has some problem that I have already mentioned in the post. Could you take a look at case 2 part as well? Thanks. – NcGYBer Dec 13 '15 at 09:45
  • have look at this tutorial for writing and reading content in file http://www.androidinterview.com/android-internal-storage-read-and-write-text-file-example/ – Nas Dec 13 '15 at 10:00