Android应用程序已停止工作

时间:2014-06-17 19:31:14

标签: android

package com.example.tryjava;
    import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {
 static int counter = 0;
 static Button add;
 static Button sub;
 static TextView display;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        counter = 0;
        // this is how we refer from the xml
        add = (Button)getActivity().findViewById(R.id.bADD);
        sub = (Button)getActivity().findViewById(R.id.bSUBSTRACT);
        display = (TextView)getActivity().findViewById(R.id.tvDISPLAY);
        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter ++;
                display.setText("Your total is " + counter);
            }
        });

        sub.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter--;
                display.setText("Your total is " + counter);
            }
        });
        return rootView;
    }
}

}

它给我一个空指针异常。我第二次做这个代码而且没有用。我查看了错误及其nulll指针异常。我不知道。我一直困扰着他。有帮助吗?

1 个答案:

答案 0 :(得分:3)

在片段onCreateView()中,在您充气的根视图上调用findViewById(),而不是在活动上。 <>> 1}}中的片段布局还不是活动的一部分,将返回空值。

此外,在发布有关崩溃的问题时,请始终包含堆栈跟踪。