Android应用程序已停止工作
它给了我一个空指针异常。我正在第二次编写这个代码,但它不起作用。我查看了这个错误,它是一个空指针异常。我不知道。我被困了一段时间。有任何帮助吗?在fragment onCreateView中,在您膨胀的根视图上调用findViewById,而不是在活动上。片段布局还不是onCreateView中活动的一部分,将返回nullAndroid应用程序已停止工作,android,Android,它给了我一个空指针异常。我正在第二次编写这个代码,但它不起作用。我查看了这个错误,它是一个空指针异常。我不知道。我被困了一段时间。有任何帮助吗?在fragment onCreateView中,在您膨胀的根视图上调用findViewById,而不是在活动上。片段布局还不是onCreateView中活动的一部分,将返回null 此外,在发布有关崩溃的问题时,请始终包含stacktrace。错误消息会告诉您错误发生的位置。非常感谢您的回复。你说的stacktrace是什么意思?那是日志吗?是的,来自l
此外,在发布有关崩溃的问题时,请始终包含stacktrace。错误消息会告诉您错误发生的位置。非常感谢您的回复。你说的stacktrace是什么意思?那是日志吗?是的,来自logcat的致命异常stacktrace。
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;
}
}
}