I want to measure the time between first button click and third button click. The code itself works fine, bur when I click the Button the 3rd time on my device, I'm getting a nullpointerexception.
why?
here's the code:
public class Game extends Activity implements OnClickListener{
Button start_time;
int i = 0;
TextView textview1;
Button RelativeLayout;
Button gameover;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// RelativeLayout.setClickable(true);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
gameover = (Button) findViewById(R.id.gameover);
gameover.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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);
}
#Override
public void onClick(View v) {
textview1 = (TextView) findViewById(R.id.textView1);
Random r = new Random();
RelativeLayout decorView = (RelativeLayout) start_time.getParent();
int screenWidth = decorView.getWidth();
int screenHeight = decorView.getHeight();
long startTime = SystemClock.elapsedRealtime();
i++;
if (i == 1 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 2 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 3 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 4 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 5 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 6 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
else if (i == 7) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// textview1.setText(intent.getStringExtra("time"));
// textview1.setText(String.valueOf(difference));
finish();
}
}
}
and the mainactivity :
public class MainScreen extends Activity implements OnClickListener {
Button btn_start;
TextView textview1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
btn_start = (Button) findViewById(R.id.btn_start);
btn_start.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
}
#Override
public void onClick(View v) {
startActivityForResult(new Intent(this,Game.class), 0);
textview1.setText(getIntent().getStringExtra("time"));
}
}
logcat:
03-09 16:08:10.760: E/AndroidRuntime(6372): FATAL EXCEPTION: main
03-09 16:08:10.760: E/AndroidRuntime(6372): Process: ch.frozensparks.asdf, PID: 6372
03-09 16:08:10.760: E/AndroidRuntime(6372): java.lang.NullPointerException
03-09 16:08:10.760: E/AndroidRuntime(6372): at ch.frozensparks.bftjh.Game.onClick(Game.java:118)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.view.View.performClick(View.java:4470)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.view.View$PerformClick.run(View.java:18593)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.os.Handler.handleCallback(Handler.java:733)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.os.Handler.dispatchMessage(Handler.java:95)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.os.Looper.loop(Looper.java:157)
The exception is occuring on this line
textview1.setText(getIntent().getStringExtra("time"));
You are trying to getIntent from the current activity but passing to new intent object here
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
(First of all, I'm assuming that the code at the top of your post is part of Game.class.)
Ok I think you're misunderstanding how intents function.
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time", difference);
Here you're creating a new intent (called 'intent') and putting the value 'difference' with the key 'time' inside it.
Then
textview1.setText(getIntent().getStringExtra("time"));
Here you're trying to access that value -- but you're actually accessing a completely different intent object. By using getIntent() you're accessing the intent object used to start the current activity, not the one you defined above it. (Also you're attempting to get a String extra from the intent, but you're storing a long.)
If you want to access that intent object, simply use:
intent.getStringExtra("time");
So your line would be:
textview1.setText(intent.getStringExtra("time"));
But instead I would just do this:
textview1.setText(String.valueOf(difference));
Last thing, I can't be sure where you're defining textview1 in the top chunk of code, but if you're trying to refer to the textview1 that is a part of MainScreen that could be causing your problem, so you may have to make it public or pass the difference variable back and set the text in MainScreen.
You need to finish yoir MainScreen Activity when navigating to Game.
MainScreen.this.finish(); in onClick method of MainScreen.
Also you need to start the activity in onclick of game activity
startActivity(intent)
Related
I am trying to use intents to set an edittext on my main activity equal to a textview on my second activity. The second activity has a button that when pressed starts a timer counting down from 10 seconds, and counts each time the button is pressed. After the 10 seconds are up, I want to take the value of the textview (set by how many times the button was pressed), set the edittext on the main activity equal to it, and go back to the main activity.
The idea is that you can manually enter a count on the main activity, or use the built in timer to help you count.
My app is crashing upon opening, I have tried multiple ways to do this to no avail. I think the problem may be stemming from the onCreate on the main activity "looking for" the intent, but it's not there since it is running when the button on the second activity is pressed.
Main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
qtyInput = (EditText) findViewById(R.id.qtyInput);
valueInput = (EditText) findViewById(R.id.valueInput);
resultText = (TextView) findViewById(R.id.resultText);
Intent intent = getIntent();
String clickCount = intent.getExtras().getString("clickCount");
qtyInput.setText(clickCount);
Button calcButton = (Button) findViewById(R.id.calcButton);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float qty = Float.parseFloat(qtyInput.getText().toString());
float value = Float.parseFloat(valueInput.getText().toString());
float total = qty * value * 60;
String stringTotal = String.format("%.0f", total);
resultText.setText(stringTotal);
}
});
Button countButton = (Button) findViewById(R.id.countButton);
countButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CountActivity.class));
}
});
}
Second activity
final TextView countdownTimer = (TextView) findViewById(R.id.countdownTimer);
final CountDownTimer timer = new CountDownTimer(10000,1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
countdownTimer.setText("Time left: " + millisUntilFinished / 1000);
}
public void onFinish() {
String clickCount = countDisplay.getText().toString();
final Intent passCount = new Intent(CountActivity.this, MainActivity.class);
passCount.putExtra("clickCount", clickCount);
startActivity(passCount);
}
};
final TextView countDisplay = (TextView) findViewById(R.id.countDisplay);
int count;
Button countOneButton = (Button) findViewById(R.id.countOneButton);
countOneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
if (clickcount==0) {
timer.start();
clickcount++;
countDisplay.setText("Count: " + clickcount);
}
else {
clickcount++;
countDisplay.setText("Count: " + clickcount);
}
}
});
}
I want to take the value of the textview (set by how many times the
button was pressed), set the edittext on the main activity equal to
it, and go back to the main activity.
Two ways to get data back in MainActivity from CountActivity :
1. With current code call MainActivity.this.finish() after starting CountActivity Activity.
startActivity(new Intent(MainActivity.this, CountActivity.class));
MainActivity.this.finish();
2. Start CountActivity Activity using startActivityForResult instead of startActivity and override onActivityResult in MainActivity get data back from CountActivity. to send data call setResult method before finishing CountActivity Activity.
Intent passCount = new Intent();
passCount.putExtra("clickCount", clickCount);
CountActivity.this.setResult(Activity.RESULT_OK,passCount);
CountActivity.this.finish();
I searched everywhere for a solution to my problem, but couldn't get one.So, the problem is I want to launch another activity called FifthActivity from my MainActivity via the button but my activity keeps crashing. I checked the logcat and found this -
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Below is my mainActivity java file.
package com.example.india.chemistry;
public class MainActivity extends AppCompatActivity {
private static boolean isRunning = false;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isRunning)
{
isRunning = true;
startActivity(new Intent(this, Intro.class));//Play your video here
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void part_a( View View){
Intent intent1 = new Intent("com.example.india.chemistry.Second_Activity");
startActivity(intent1);
}
public void part_b( View View) {
Intent intent2 = new Intent("com.example.india.chemistry.ThirdActivity");
startActivity(intent2);
}
public void formulas( View View) {
Intent intent4 = new Intent(this,FifthActivity.class);
startActivity(intent4);
}
}
Below is my FifthActivity.java file.
package com.example.india.chemistry;
public class FifthActivity extends ActionBarActivity {
final Animation shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
final Animation bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fifth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void nernst(View View) {
Intent intentf1 = new Intent("com.example.india.chemistry.nernst_activity");
startActivity(intentf1);
}
public void waterhardness(View View) {
Intent intentf2 = new Intent("com.example.india.chemistry.WaterHardness");
startActivity(intentf2);
}
public void determinationOfCao(View view) {
Intent intentf3 = new Intent("com.example.india.chemistry.CementCao");
startActivity(intentf3);
}
public void COD_waste_water(View view) {
Intent intentf4 = new Intent("com.example.india.chemistry.COD");
startActivity(intentf4);
}
public void C_in_B(View view) {
Intent intentf5 = new Intent("com.example.india.chemistry.Copper_in_Brass");
startActivity(intentf5);
}
public void alkalinity(View view) {
Intent intentf6 = new Intent("com.example.india.chemistry.Alkalinity");
startActivity(intentf6);
}
public void haematite_ore(View view) {
Intent intentf7 = new Intent("com.example.india.chemistry.HaemetiteOre");
startActivity(intentf7);
}
public void colourimetry_copper(View view) {
Intent intentf8 = new Intent("com.example.india.chemistry.Colourimetric_Copper");
startActivity(intentf8);
}
public void potentiometry_fas(View view) {
Intent intentf9 = new Intent("com.example.india.chemistry.Potentiometry_fas");
startActivity(intentf9);
}
public void conductometry(View view) {
Intent intentf10 = new Intent("com.example.india.chemistry.Conductometry");
startActivity(intentf10);
}
public void pka(View view) {
Intent intentf11 = new Intent("com.example.india.chemistry.pka");
startActivity(intentf11);
}
}
Below is the logcat.
10-14 17:13:58.145 15430-15430/com.example.india.chemistry E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.india.chemistry, PID: 15430 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.india.chemistry/com.example.india.chemistry.FifthActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.example.india.chemistry.FifthActivity.<init>(FifthActivity.java:21)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1085)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2410)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2569)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Please help me.
You can't call getApplicationContext(result in null) before oncreate because activity has not been created properly yet so you need to call this once your oncreate has been executed or after the super call .
The super call of onCreate fetches the application context for your activity.
Solution :
So either put your code inside oncreate or create a function and call it from inside oncreate after the super call.
Note : you will have to avoid final to make your identifiers global because the lazy initialization with final only works with constructors but don't worry , onCreate gets executed once when your activity is created or recreated.
Try this and let me know if problem solved or not.....
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
You need to add the activity in your manifest file, under application. Whenever you create a new activity add it to manifest file.
<application
...
<activity
android:name=". FifthActivity"
android:label="Fifth" />
...
</application>
Hope this helps.
try this:
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
Your view has not yet been created, move :
shake = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
To your oncreate method.
stack trace's first line gives Detailed information : getApplicationContext()' on a null object reference.Means Activity was not created,it's return null Context. You make a both animation's Object Globally. try to edit your code this way.
public class FifthActivity extends ActionBarActivity {
Animation shake,bounce;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fifth);
shake = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.shake);
bounce = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.bounce);
}
}
I'm trying to make a To Do app in android studio. But as soon as I click on add-button (+ in top right corner) the app crashes. I am very new to java and android studio but I think the problem may lay in "saveListInfo()" but I can't figure out how to fix it...
Code from EditedActivity.java:
public class EditedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edited);
String name;
name = getIntent().getStringExtra("theName");
EditText editList = (EditText) findViewById(R.id.editText);
editList.setText(name);
}
private void saveListInfo() {
EditText editList = (EditText) findViewById(R.id.editText);
String name = editList.getText().toString();
Bundle listBundle = new Bundle();
listBundle.putString("name", name);
Intent finalIntent = new Intent(this, MainActivity.class);
finalIntent.putExtras(listBundle);
setResult(RESULT_OK, finalIntent);
}
Button addBtn = (Button) findViewById(R.id.add_btn);
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
}
Code from MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_task:
saveTodoInfo();
}
return true;
}
private void saveTodoInfo(){
TextView nameView = (TextView) findViewById(R.id.action_add_task);
String name = nameView.getText().toString();
Intent myIntent = new Intent(this, EditedActivity.class);
myIntent.putExtra("theName", name);
startActivityForResult(myIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0){
if(resultCode == RESULT_OK){
Bundle ListBundle = data.getExtras();
String name = ListBundle.getString("theName");
updateToDo(name);
}
}
}
private void updateToDo(String name){
TextView nameView = (TextView) findViewById(R.id.action_add_task);
nameView.setText(name);
}
}
This is the error I get when clicking the add-button:
02-12 16:07:40.553 1410-1410/com.carpe_diem.anitas_todolist
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.carpe_diem.anitas_todolist, PID: 1410
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.carpe_diem.anitas_todolist/com.carpe_diem.anitas_todolist.EditedActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.Window.findViewById(int)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.View android.view.Window.findViewById(int)' on a
null object reference
at android.app.Activity.findViewById(Activity.java:2090)
at
com.carpe_diem.anitas_todolist.EditedActivity.(EditedActivity.java:40)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
By the logs, we can see that you crash is happening in following line:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference at
android.app.Activity.findViewById(Activity.java:2090) at
com.carpe_diem.anitas_todolist.EditedActivity.(EditedActivity.java:40)
...
After checking your code, I can find in line 40 (EditedActivity.java:40) that following code is outside of any method or function.
Button addBtn = (Button) findViewById(R.id.add_btn);
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
So, you have to move the lines above to onCreate() method.
EditedActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edited);
String name;
name = getIntent().getStringExtra("theName");
EditText editList = (EditText) findViewById(R.id.editText);
editList.setText(name);
Button addBtn = (Button) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
Root Cause
If you leave the line below outside of any method, it will run during object instantiation.
Button addBtn = (Button) findViewById(R.id.add_btn);
However, during object creation, the view was not created yet. So, findViewById wont find anything and will return null. Thus, that CRASH (or Force Close) will happen.
Solution
So, make sure to add findViewById() inside a method which is called after the view was already created (otherwise, it will never find the view).
As you can see, I suggested to add at onCreate() method after setContentView(R.layout.activity_edited) (which is responsible to add the objects to VIEW).
After that line, findViewById() will be able to find the views (if you add them in the layout, of course).
Remove the brackets around this code
{
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
}
Should look like this
Button addBtn = (Button) findViewById(R.id.add_btn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveListInfo();
}
});
If you want to know why the crash happened, you can read more about What is an initialization block?
This question already has answers here:
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
(12 answers)
Closed 8 years ago.
I'm trying to create my own custom AlertDialog in a DialogFragment for a simple alarm clock application, and the code for the onCreateDialog method is below.
public class CreateAlarmSetting extends DialogFragment implements View.OnClickListener, AlertDialog.OnClickListener, TimePicker.OnTimeChangedListener, NumberPicker.OnValueChangeListener {
/*
the isEdit variable is set to true when an existing alarm time is clicked, this will add the
"delete" button to the dialog, to possibly delete the item from the listview
*/
private boolean isEdit = false;
public static final String ISEDIT_PARAM = "isEdit";
public static final String ALARMSETTING_PARAM = "AlarmSetting";
public AlarmSetting alarmSetting;
private TimePicker timePicker;
private NumberPicker numberPicker;
//private Button cancelButton, createButton, deleteButton;
//View of the dialog layout that will be inflated
private View main;
private OnFragmentInteractionListener mListener;
public CreateAlarmSetting() {
}
/*
Below are a few of the Fragment lifecycle methods
*/
public void setArguments(Bundle bundle) {
isEdit = bundle.getBoolean(ISEDIT_PARAM);
alarmSetting = (AlarmSetting) bundle.get(ALARMSETTING_PARAM);
}
#Override
public void onCreate(Bundle savedInstanceState) {
getActivity().requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
/*
Not doing anything yet, because findViewById() doesn't work at this point in the lifecycle
*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO: check if this is to edit a current alarmSetting and add the save button and delete button
main = inflater.inflate(R.layout.fragment_create_alarm_setting, null);
//Initialize views and their listeners
timePicker = (TimePicker) main.findViewById(R.id.alarm_fragment_dialog_timepicker);
numberPicker = (NumberPicker) main.findViewById(R.id.alarm_fragment_dialog_numberpicker);
// cancelButton = (Button) main.findViewById(R.id.alarm_fragment_dialog_cancel_button);
// createButton = (Button) main.findViewById(R.id.alarm_fragment_dialog_create_button);
timePicker.setOnTimeChangedListener(this);
numberPicker.setOnValueChangedListener(this);
//cancelButton.setOnClickListener(this);
//createButton.setOnClickListener(this);
numberPicker.setMaxValue(45);
numberPicker.setMinValue(0);
//create display based on given parameters
/*
if (isEdit) {
// ViewGroup parent= (ViewGroup) main.findViewById(R.id.alarm_fragment_dialog_button_container);
deleteButton= (Button) main.findViewById(R.id.alarm_fragment_dialog_delete_button);
deleteButton.setText("Delete");
deleteButton.getLayoutParams().height= LinearLayout.LayoutParams.WRAP_CONTENT;
deleteButton.getLayoutParams().width= LinearLayout.LayoutParams.WRAP_CONTENT;
deleteButton.setOnClickListener(this);
createButton.setText("Save");
//TODO: Set Display Settings to current alarm settings, includes having cancel, delete, save buttons
timePicker.setCurrentHour(alarmSetting.getHours());
timePicker.setCurrentMinute(alarmSetting.getMinutes());
//Replace create button with the save add the delete button
ViewGroup parent= (ViewGroup) main.findViewById(R.id.alarm_fragment_dialog_button_container);
ViewGroup v=(ViewGroup) edit.findViewById(R.id.miscellaneous_items_container);
//v.removeView(edit.findViewById(R.id.alarm_fragment_dialog_delete_button));
parent.addView(edit.findViewById(R.id.alarm_fragment_dialog_delete_button), 1);
//Replace create button with save button
parent = (ViewGroup) createButton.getParent();
int index = parent.indexOfChild(createButton);
parent.removeView(createButton);
parent.addView(parent.findViewById(R.id.alarm_fragment_dialog_save_button), index);
}*/
return main;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
if (main == null) {
main = getActivity().getLayoutInflater().inflate(R.layout.fragment_create_alarm_setting, null);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(main);
builder.setNegativeButton("Cancel", this);
builder.setPositiveButton("Create", this);
builder.setTitle("Create a new Alarm Setting");
AlertDialog alertDialog=builder.create();
//show or create?
return alertDialog;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/*
Below are listeners for the actions in the dialog
*/
#Override
public void onClick(DialogInterface dialogInterface, int id) {
switch (id) {
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEUTRAL:
case DialogInterface.BUTTON_POSITIVE:
}
}
#Override
public void onValueChange(NumberPicker picker, int val, int num) {
//Do something
}
#Override
public void onTimeChanged(TimePicker picker, int hours, int minutes) {
if (alarmSetting != null) {
alarmSetting.setHours(hours);
alarmSetting.setMinutes(minutes);
} else alarmSetting = new AlarmSetting(hours, minutes, false);
}
#Override
public void onClick(View v) {
//do stuff for each button
switch (v.getId()) {
}
}
When I run this code in the emulator, I receive an exception saying
01-22 20:32:39.489 1883-1883/com.stanfordude.ryan.snooze E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:215)
at com.android.internal.app.AlertController.installContent(AlertController.java:234)
at android.app.AlertDialog.onCreate(AlertDialog.java:336)
at android.app.Dialog.dispatchOnCreate(Dialog.java:351)
at android.app.Dialog.show(Dialog.java:256)
at android.app.DialogFragment.onStart(DialogFragment.java:490)
at android.app.Fragment.performStart(Fragment.java:1570)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:863)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
at android.app.BackStackRecord.run(BackStackRecord.java:635)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
How do I fix this?
Btw, sorry for my messy code and comments, I'm new to java
Its not the code as I can see from the error, its the requestWindowsFeature or something you have called before setContentView on the top. You should call the request before setting the contentView like this :
super.onCreate(savedInstanceState);
// Hiding title bar using code
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Hiding status bar using code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
I am quite new to Java and Android programming, and just working on my 3rd App - however I am encountering a Problem which I am not able to solve (I already tried and researched for days).
I have a list of Elements in a LinearLayout inside a Fragment - the Elements have a OnLongClickListener attached, with a popup showing up when the User long-presses the Element. That works fine. However, one of the Buttons in the Popup is "Edit", and when a user presses this Button, I want to start another Activity with Editing Options for this Element.
So there comes my Problem: when I want to start the new Activity with an Intent, I get following Error:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3370)
at android.app.Activity.startActivityForResult(Activity.java:3331)
at android.app.Activity.startActivity(Activity.java:3566)
at android.app.Activity.startActivity(Activity.java:3534)
at at.fekle.zipmanager.start.startzipinfo(start.java:299)
at at.fekle.zipmanager.start$2.onLongClick(start.java:277)
at android.view.View.performLongClick(View.java:4247)
at android.view.View$CheckForLongPress.run(View.java:17341)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
But, if i start the same Activity with the same Intent from a simple Button defined in the Layout, the Activity Starts fine without any Errors... weird, isn't it?
So, does anyone have an Idea how I can solve this problem?
Here are some extractions from my code:
The Creation of the Elements with the OnLongClickListener:
ScrollView parent = (ScrollView) maininflater.inflate(R.layout.start_ziplist_fragment_superwrapper, null, false);
inf = maininflater;
LinearLayout ll = (LinearLayout) maininflater.inflate(R.layout.start_ziplist_fragment_wrapper, parent, false);
for (Integer i = 0; i < count; i++) {
ArrayList<String> data = new DB(cont).getAllZips().get(i);
View custom = maininflater.inflate(R.layout.start_ziplist_fragment_inner, ll, false);
TextView tv = (TextView) custom.findViewById(R.id.ziplist_name);
TextView tv2 = (TextView) custom.findViewById(R.id.ziplist_text);
tv.setText(data.get(2));
tv2.setText(data.get(1));
Integer id = Integer.valueOf(data.get(0));
custom.setId(id);
custom.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Integer id = view.getId();
startzipinfo(id);
return true;
}
});
ll.addView(custom);
}
parent.addView(ll);
The void which starts the Activity:
public void startzipinfo(Integer id){
Intent in = new Intent(getApplicationContext(), zipinfo.class);
startActivity(in);
}
I'm looking forward to your Answers,
Felix
EDIT: This is the Activity which is about to be started:
package at.fekle.zipmanager;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by felix on 27.06.13.
*/
public class zipinfo extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zipinfo);
}
}
Try to use YourActivityName.this instead of getApplicationContext() :
public void startzipinfo(Integer id){
Intent in = new Intent(YourActivityName.this, zipinfo.class);
startActivity(in);
}
Check whether your new intent class is mentioned in android manifest file if it does not exists then type:<activity name=".YourClassName>
</activity>
I just solved the problem!
I had to start the activity from the parent Fragment (passed to the method by the FragmentManager) - now everything works like a charm :)
custom.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Integer id = view.getId();
id = 2;
Intent intent = new Intent(cont, zipinfo.class);
fragment.startActivity(intent);
return true;
}
});
Thanks for all answers!
Cheers,
Felix