App crashes when launching another activity - java

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);
}
}

Related

Android app crashes when activity is initialised from fragment [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am currently trying to create a calendar app in android studio. The app contains a calendar with different "Views" e.g. monthly view, weekly view, and daily view.
The app uses fragments as pages and each view is an activity.
This is the code for the fragment and buttons to initialise each view
public class CalendarFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_calendar, container, false);
Button btn1 = (Button) v.findViewById(R.id.openCalendar);
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(),CalendarActivity.class);
startActivity(intent);
}
});
Button btn2 = (Button) v.findViewById(R.id.openWeek);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), WeekViewActivity.class);
startActivity(intent);
}
});
return v;
}
The first button which displays the monthly view of the calendar called "CalendarActivity" in code works fine but when the second button is clicked which displays the weekly view of the calendar, causes the app to crash and gives the following error in the logcat
2022-05-13 14:44:59.642 15183-15183/com.example.finalyearproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.finalyearproject, PID: 15183
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalyearproject/com.example.finalyearproject.WeekViewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3685)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7842)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.time.LocalDate.format(java.time.format.DateTimeFormatter)' on a null object reference
at com.example.finalyearproject.CalendarUtils.monthYearFromDate(CalendarUtils.java:16)
at com.example.finalyearproject.WeekViewActivity.setWeekView(WeekViewActivity.java:40)
at com.example.finalyearproject.WeekViewActivity.onCreate(WeekViewActivity.java:29)
at android.app.Activity.performCreate(Activity.java:8054)
at android.app.Activity.performCreate(Activity.java:8034)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1341)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3842) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2252) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7842) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
I am not sure what the problem is as I have been following a tutorial and the other features work. I have also included the code for each activity below.
Monthly View
public class CalendarActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
initWidgets();
CalendarUtils.selectedDate = LocalDate.now();
setMonthView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setMonthView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> daysInMonth = daysInMonthArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void nextMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusMonths(1);
setMonthView();
}
public void previousMonth(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusMonths(1);
setMonthView();
}
Weekly View
public class WeekViewActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
private TextView monthYearText;
private RecyclerView calendarRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);
initWidgets();
setWeekView();
}
private void initWidgets()
{
calendarRecyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
private void setWeekView()
{
monthYearText.setText(monthYearFromDate(CalendarUtils.selectedDate));
ArrayList<LocalDate> days = daysInWeekArray(CalendarUtils.selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(days, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
public void previousWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.minusWeeks(1);
setWeekView();
}
public void nextWeek(View view)
{
CalendarUtils.selectedDate = CalendarUtils.selectedDate.plusWeeks(1);
setWeekView();
}
Any suggestions would be greatly appreciated.
My suggestions:
Firstly you didn't initialized CalendarUtils.selectedDate
Cover code with breakpoints for. debugging or with Log.d() messages to find, which variable is null

To Do app crash

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?

How to make an activity flash at the beginning of the app?

I am working on an app.In this,at the beginning of the app an activity will be displayed for 2 seconds and after that the app with start with the main activity.
This is how i tried to achieve this:
The activity_main.java file:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent i = new Intent(MainActivity.this,open.class);
startActivity(i);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#A6250F")));
bar.setSubtitle(R.string.title_sub);
}
}
The open.java file
public class open extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.open);
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#A6250F")));
}
protected void onStart(){
super.onStart();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finish();
}
}
The open.java file should be shown for 2 seconds at the beginning of the app and then the execution will continue from the activity_main.java
But what happens is a blank screen is displayed for a second and then the mainactivity is shown.Need help
You should re-design your flow so that :
open is the Activity that is created first, and 2 seconds after loads the MainActivity.
public class open extends Activity {
private Activity mActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open);
android.app.ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#A6250F")));
mActivity = this;
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
Intent i = new Intent(mActiviy, MainActivity.class);
startActivity(i);
}
}
handler.postDelayed(r, 2000);
}
}
Last thing is make sure you swap the Activities in your Manifest, making your application start with the open Activity

Create Custom AlertDialog requestFeature exception [duplicate]

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);

Display editText and a Button in Another Activity

I am using Linear Layout(Horizontal) for my Android application. I am using two buttons for my screen which I have called as Chat and Draw. I want to display a second activity on clicking on Chat button in which I have an area for editText and a corresponding button called as Enter for entering the text.
In the DisplayMessageActivity class which I am using for Chat button, I have created the layout for editText and Enter button too. But however, on clicking on Chat I am not being able to see the area for editText and the button Enter.
Code in MainActivity.java :
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.appfirst.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void chatMessage(View view) {
Intent intent_chat = new Intent(this, DisplayMessageActivity.class);
startActivity(intent_chat);
}
public void drawing(View view) {
Intent intent_draw = new Intent(this, DisplayMessageActivity.class);
startActivity(intent_draw);
}
}
code in DisplayMessageActivity.java :
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
What code should I write in the OnCreate function of DisplayMessageActivity class so that I am able to get the desired view ?
Can someone help me with the code. I am totally new to Android Development Framework. Thanks and Regards.
From your post i understand that u have 2 layouts 1 with 2 buttons "Chat" and "Draw".And when clicking chat u have to call another activity with Edittext and Enter button in it.If this is the case you simply call the Intent.
Intent intent=new Intent(this,yourclass.class);
startactivity(intent);
In Oncreate of your DisplayMessage do the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourXml.Xml);
}
In your second activity you need to put the following line setContentView(R.layout.whatEverYourLayoutIsCalled);, put it right after super.onCreate(...);
public class DisplayMessageActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityxml);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
For more information look the below example link

Categories