单击按钮时出现Android NullPointerError

时间:2013-11-26 08:04:26

标签: android csv android-fragments nullpointerexception

我试图通过在另一个片段中按下按钮时读取csv文件来获取我的一个片段来更新它的TextView内容,但我一直收到FATAL EXCEPTION: mainjava.lang.NullPointerException个错误第二个片段。这是我的代码:

public class AddFragment extends Fragment {

    static EditText spent,saved,coupons;
    Button writeExcelButton;
    String data = "";
    Spinner spinner;
    UpdateFile updateFile;
    //int thisTab = 1;

    public interface UpdateFile {
        public void onButtonClick(); //NullPointerException error here
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.add_layout, container, false);

        setSpinnerContent(view);

        spent = (EditText) view.findViewById(R.id.text_spent1);
        saved = (EditText) view.findViewById(R.id.text_saved1);
        coupons = (EditText) view.findViewById(R.id.text_coupons1);

        writeExcelButton = (Button) view.findViewById(R.id.button_addGroc);
        writeExcelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              updateFile();
              buttonClicked();
            }
        });
        return view;
    }

    private void setSpinnerContent (View view) {
        spinner = (Spinner) view.findViewById(R.id.groc_store);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.store1, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

    public void updateFile() {
        try {
            // This is the string that should be written to file
            String mySpin = spinner.getSelectedItem().toString();
            String mySpent = spent.getText().toString();
            String mySaved = saved.getText().toString();
            String myCoup = coupons.getText().toString();
            // This is the file that should be written to
            File myFile = new File(Environment.getExternalStorageDirectory(), "dir/savings.csv");
            if (!myFile.exists()) {
                 myFile.mkdirs();
                 myFile.createNewFile();
            }
            //write to file


            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   public void buttonClicked() {
        updateFile.onButtonClick(); //NullPointerException error here
    }
}

logcat的:

11-25 20:17:10.504: E/AndroidRuntime(10733): FATAL EXCEPTION: main
11-25 20:17:10.504: E/AndroidRuntime(10733): java.lang.NullPointerException
11-25 20:17:10.504: E/AndroidRuntime(10733):    at com.example.myfirstapp.AddFragment.buttonClicked(AddFragment.java:108)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at com.example.myfirstapp.AddFragment$1.onClick(AddFragment.java:54)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at android.view.View.performClick(View.java:4240)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at android.view.View$PerformClick.run(View.java:17721)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at android.os.Handler.handleCallback(Handler.java:730)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at android.os.Looper.loop(Looper.java:137)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at android.app.ActivityThread.main(ActivityThread.java:5103)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at java.lang.reflect.Method.invokeNative(Native Method)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at java.lang.reflect.Method.invoke(Method.java:525)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-25 20:17:10.504: E/AndroidRuntime(10733):    at dalvik.system.NativeStart.main(Native Method)

非常感谢任何帮助。

修改

我将此添加到上面的代码中:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
        try {
            updateFile = (UpdateFile) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement UpdateFile");
       }
 }

但是现在我得到了这个错误以及我得到的其他错误:

11-25 20:43:27.957: E/AndroidRuntime(25938):    at com.example.myfirstapp.MainActivity.onButtonClick(MainActivity.java:66)

以下是我在MainActivity中使用的方法:

public void onButtonClick() {
        HistoryFragment historyFragment = (HistoryFragment) getSupportFragmentManager().findFragmentById(R.id.tableLayout1);
        historyFragment.updateTable();
    }

这是我正在尝试更新的片段:

public class HistoryFragment extends Fragment {

    static TextView pos1, pos2, pos3, pos4, pos5, pos6, pos7, pos8, pos9, pos10, pos11, pos12;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.history_layout, container, false);

        pos1 = (TextView)view.findViewById(R.id.grocstore1);
        pos2 = (TextView)view.findViewById(R.id.grocspent1);
        pos3 = (TextView)view.findViewById(R.id.grocsaved1);
        pos4 = (TextView)view.findViewById(R.id.groccoupons1);
        pos5 = (TextView)view.findViewById(R.id.grocstore2);
        pos6 = (TextView)view.findViewById(R.id.grocspent2);
        pos7 = (TextView)view.findViewById(R.id.grocsaved2);
        pos8 = (TextView)view.findViewById(R.id.groccoupons2);
        pos9 = (TextView)view.findViewById(R.id.grocstore3);
        pos10 = (TextView)view.findViewById(R.id.grocspent3);
        pos11 = (TextView)view.findViewById(R.id.grocsaved3);
        pos12 = (TextView)view.findViewById(R.id.groccoupons3);

        return view;
    }

    public void updateTable() {
        File myFile = new File(Environment.getExternalStorageDirectory(), "dir/savings.csv");
        String line;
        ArrayList<String> savingList = new ArrayList<String>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(myFile));
            while((line = reader.readLine()) != null) { 
                String[] strings = line.split(",");
                for(String s : strings) {
                    savingList.add(1, s);
                    System.out.println(savingList.get(1));
                }
                pos1.setText(strings[1]);
                System.out.println(pos1);
                pos2.setText(strings[2]);
                pos3.setText(strings[3]);
                pos4.setText(strings[4]);
                pos5.setText(strings[5]);
                pos6.setText(strings[6]);
                pos7.setText(strings[7]);
                pos8.setText(strings[8]);
                pos9.setText(strings[9]);
                pos10.setText(strings[10]);
                pos11.setText(strings[11]);
                pos12.setText(strings[12]);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

对不起,我是新来的,现在我已经盯着这几个小时了。

4 个答案:

答案 0 :(得分:0)

您永远不会为updateFile分配任何值。它始终为空。

onCreate()(或其他位置),您应该将updateFile指定为其他片段。因此,当调用onButtonClick时,它将调用其他片段的方法。

答案 1 :(得分:0)

你必须实现你的界面:在你的onCreateView中,你可以做到

updateFile = new UpdateFile() {

  public void onButtonClick() {
  // put your logic inside 
  }       
};

或者你可以创建一个类:

class MyUpdateFile implements UpdateFile {
        public void onButtonClick() {
      // put your logic inside 
      }
}

并向updateFile = new MyUpdateFile();

致意

答案 2 :(得分:0)

您在代码中分配了哪些updateFile?

分配updateFile = new UpdateFile();

答案 3 :(得分:0)

想出来......

我需要在MainActivity中使用它:

public void onButtonClick() {
        android.support.v4.app.Fragment f = this.getSupportFragmentManager().findFragmentByTag(getFragmentTag(0));
        ((HistoryFragment) f).updateTable();
    }

    private String getFragmentTag(int pos){
        return "android:switcher:"+R.id.pager+":"+pos;
    }

我将onAttach方法添加到AddFragment后,我只需要找到HistoryFragment标记即可调用updateTable()方法。