I started with Android like 2 days ago and please forgive me if I have made a naive error.I am making the interface in Java instead of XML and the application crashes every time I launch it on the emulator.Here is the stack trace for the same:
03-01 21:08:46.941 7640-7640/com.example.prashant.wisdom E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.prashant.wisdom, PID: 7640
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.prashant.wisdom/com.example.prashant.wisdom.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
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 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.prashant.wisdom.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
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)
03-01 21:08:49.797 7640-7640/? I/Process: Sending signal. PID: 7640 SIG: 9
Here is MainActivity.java:
package com.example.prashant.wisdom;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout=new RelativeLayout(this); //layout
Button button=new Button(this); //button
button.setText("SignIn");
//giving ids to layout and button
button.setId(1);
layout.setId(2);
//rules for button positioning
RelativeLayout.LayoutParams buttonDetails=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
); //the above snippet is to be written for every widget in the activity.
// For example,we'll write one for EditText also.
buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);
EditText username=new EditText(this); //username input
username.setId(3);
RelativeLayout.LayoutParams usernameDetails=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
); //rules for the EditText details.
//now we've to place the EditText above the button that is already positioned in the center.
//the following snippet does that.
usernameDetails.addRule(RelativeLayout.ABOVE,button.getId());
usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL); //Rule for positioing in the center of the screen
usernameDetails.setMargins(0,0,0,50); //padding on all the sides.We're adding padding just to the bottom
//hence the rest are zero, but the bottom one is 50 pixels.
layout.addView(username); //EditText now positioned on the layout.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
setContentView(layout); //placement of layout itself
layout.addView(button, buttonDetails); //placement of buttons on the layout
}
#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) {
// 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.prashant.wisdom.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
You dont have a FAB defined in your xml so
findViewById(R.id.fab);
returns null and you get a simple NullpointerException accessing it
You have to call setContentView before you can find views in your layout (findViewById).
Also it seems like none of your xml files is actually used in code, so nothing defined in any xml will be accessible.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
this is what the android monitor is showing:
08-26 19:04:17.456 10081-10089/? E/art: Failed sending reply to debugger: Broken pipe 08-26 19:04:17.456 10081-10089/?
I/art: Debugger is no longer active 08-26 19:04:17.582 10081-10081/? I/InstantRun: starting instant run server: is main
process 08-26 19:04:17.628 10081-10081/? W/art: Before Android 4.1,
method android.graphics.PorterDuffColorFilter
android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter,
android.content.res.ColorStateList, android.graphics.PorterDuff$Mode)
would have incorrectly overridden the package-private method in
android.graphics.drawable.Drawable 08-26 19:04:17.736 10081-10081/?
D/AndroidRuntime: Shutting down VM 08-26 19:04:17.736 10081-10081/?
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sayandeep.notepad, PID: 10081
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.sayandeep.notepad/com.example.sayandeep.notepad.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.EditText.setText(java.lang.CharSequence)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.EditText.setText(java.lang.CharSequence)'
on a null object reference
at
com.example.sayandeep.notepad.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5990)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 08-26
19:04:26.858 10081-10081/com.example.sayandeep.notepad I/Process:
Sending signal. PID: 10081 SIG: 9
Main Activity
package com.example.sayandeep.notepad;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
EditText content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content=(EditText)findViewById(R.id.content);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Save("Note1.txt");
}
});
content.setText((Open("Note1.txt")));
}
public void Save(String filename) {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(filename, 0));
out.write(content.getText().toString());
out.close();
Toast.makeText(this, "Note saved!", Toast.LENGTH_SHORT).show();
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
}
public boolean FileExists(String filename) {
File file=getBaseContext().getFileStreamPath(filename);
return file.exists();
}
public String Open(String filename) {
String temp="";
if(FileExists(filename))
{
try
{
InputStream in=openFileInput(filename);
if(in!=null)
{
InputStreamReader tmp=new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
String str;
StringBuilder buf=new StringBuilder();
while((str=reader.readLine())!=null)
{buf.append(str+"\n");}in.close();
temp=buf.toString();
}
}catch(java.io.FileNotFoundException e){}catch(Throwable t){
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();}
}return temp;
}
#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) {
// 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
#Activity_main.xml#
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sayandeep.notepad.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_menu_save"
android:onClick="onClick"/>
</android.support.design.widget.CoordinatorLayout>
# Content_main.xml#
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.sayandeep.notepad.MainActivity"
tools:showIn="#layout/activity_main">
<EditText android:id="#+id/content"
android:layout_width="391dp"
android:layout_height="523dp"
android:hint="Type here..."
android:gravity="top"
android:inputType="textPersonName"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</android.support.constraint.ConstraintLayout>
You should include your content_main.xml on your main layout. Add this to your main layout before floating action button. Read here
<include layout="#layout/content_main"/>
Iam trying to set a text(data ) of Edittext widget obtained from a database,But iam getting the above error,Iam trying to resolve but not getting the actual idea,Please help me with this,Thanks in advance,
This is my MainActivity.java
package com.mycompany.newlogin;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btLogout;
EditText etName,etPhone,etEmail,etUsername;
private static String url = "jdbc:mysql://31.170.160.74:3306/a5582611_mane";
private static String user = "a5582611_nanu";
private static String password = "sonne0";
UserLocalStore userLocalStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName=(EditText)findViewById(R.id.etName);
etPhone=(EditText)findViewById(R.id.etPhone);
etEmail=(EditText)findViewById(R.id.etEmail);
etUsername=(EditText)findViewById(R.id.etUsername);
btLogout=(Button)findViewById(R.id.btLogout);
userLocalStore=new UserLocalStore(this);
btLogout.setOnClickListener(this);
}
#Override
protected void onStart(){
super.onStart();
if(authenticate()==true){
//go to your question window
displayUserDetails();
}else {
startActivity(new Intent(MainActivity.this,Login.class));
}
}
private void displayUserDetails(){
User user=userLocalStore.getLoggedInUser();
etName.setText(user.name);
etEmail.setText(user.email);
etUsername.setText(user.username);
}
private boolean authenticate(){
return userLocalStore.getUserLoggedIn();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btLogout:
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
startActivity(new Intent(this, Login.class));
break;
}
}
#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) {
// 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And my activity_xml file is like this,
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etName"
android:layout_marginBottom="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Email"
android:layout_marginBottom="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/etUsername"
android:layout_marginBottom="10dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btLogout"
android:text="Logout"
android:layout_gravity="center"/>
And here is my error details,
FATAL EXCEPTION: main
Process: com.mycompany.newlogin, PID: 2787
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.newlogin/com.mycompany.newlogin.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.mycompany.newlogin.MainActivity.displayUserDetails(MainActivity.java:51)
at com.mycompany.newlogin.MainActivity.onStart(MainActivity.java:42)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1243)
at android.app.Activity.performStart(Activity.java:5969)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2277)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please help me to resolve this
Your etEmail edit text is null:
In place of- etEmail=(EditText)findViewById(R.id.etEmail);
It should be-etEmail=(EditText)findViewById(R.id.Email);
Since your etEmail id is "Email" not "etEmail".
I'm trying to follow the following tutorial to create a tab view layout: http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html
Unfortunately, the app kept crashing before anything came up. After inserting debug logs into my code, I found that the problem resided in the line setSupportActionBar(toolbar) in MainActivity. I have no idea why this is happening. I have pasted my entire MainActivity file below.
package com.example.rkhaj.tabstest;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("icecream", "position 1");
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
Log.d("icecream", "position 1.5");
setSupportActionBar(toolbar);
Log.d("icecream", "position 2");
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
Log.d("icecream", "position 3");
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
Log.d("icecream", "position 4");
// Assinging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
Log.d("icecream", "position 5");
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
Log.d("icecream", "position 6");
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
Log.d("icecream", "position 7");
}
#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) {
// 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<com.example.rkhaj.tabstest.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
This is the logcat:
09-07 16:46:27.772 22833-22833/com.example.rkhaj.tabstest I/art﹕ Late-enabling -Xcheck:jni
09-07 16:46:27.772 22833-22833/com.example.rkhaj.tabstest I/art﹕ VMHOOK: rlim_cur : 0 pid:22833
09-07 16:46:27.812 22833-22833/com.example.rkhaj.tabstest E/Typeface﹕ SANS_LOC file not found.
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest D/icecream﹕ position 1
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest D/icecream﹕ position 1.5
09-07 16:46:27.882 22833-22833/com.example.rkhaj.tabstest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rkhaj.tabstest, PID: 22833
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rkhaj.tabstest/com.example.rkhaj.tabstest.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:197)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
at com.example.rkhaj.tabstest.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
09-07 16:46:39.442 22833-22833/com.example.rkhaj.tabstest D/Process﹕ killProcess, pid=22833
09-07 16:46:39.442 22833-22833/com.example.rkhaj.tabstest D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
Since you are using a Toolbar in your layout, you should use Theme.AppCompat.NoActionBar as your parent theme.
Otherwise you can use somenthing like:
<style name="MyTheme" parent="Theme.AppCompat">
...
</style>
<style name="MyTheme.NoActionBar">
<!-- Both of these are needed -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
You need to use an AppCompat theme for the activity. One like this, Theme.AppCompat.Light.NoActionBar
This comment helped me when copying code from into a a new project:
don't forget to add android:theme="#style/AppTheme.NoActionBar" to
your activity declaration in AndroidManifest.xml. I knew this
needed to be there but forgot to add it and I couldn't figure out why
my app was crashing at setupActionBar() in my Activity - This fixed
it. – DangerPaws
It should be a standalone answer :-)
I have an activity where it will display a ListView in a one of the 5 tabs. This is the MainActivity class:
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Courses","Jobs","Me","More"};
int Numboftabs =5;
MaterialTabHost tabHost;
ListView listView;
String[]me = new String[] {
"My Profile",
"My Bookmarks",
"My Application History"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assigning the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, me);
listView = (ListView)findViewById(R.id.listMe);
listView.setAdapter(adapter);
}
#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) {
// 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the activity_main XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
layout="#layout/tool_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<itp231.dba.sit.nyp.com.tab_2.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</LinearLayout>
This is the layout tab_4 XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listMe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/Me"
/>
</RelativeLayout>
When I attempt to run the app, the app crashes and displayed the following errors in the logcat:
06-30 01:39:24.105 1632-1632/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: itp231.dba.sit.nyp.com.tab_2, PID: 1632
java.lang.RuntimeException: Unable to start activity ComponentInfo{itp231.dba.sit.nyp.com.tab_2/itp231.dba.sit.nyp.com.tab_2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at itp231.dba.sit.nyp.com.tab_2.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
See here:
setContentView(R.layout.activity_main);
you are setting "activity_main" as Layout. But in your Layout xml file there is no ListView with id listMe.
So shift this code to activity_main:
<ListView
android:id="#+id/listMe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/Me"
/>
I hope it will work then.
I am mainly looking for clarification and advice on this. In the app I am working on I setup a fragment for handling some basic controls and text, and moved the necessary XML from the activities layout file into the fragments layout file, without making any changes. However now when I run the app I get a NULLPOINTEREXCEPTION and it seems to be caused at line 19 in my GameStart activty when I try to set the textView by its ID. I have not changed the ID, only moved it to the fragment layout file, so I have two questions:
1) What exactly is the reason this is happening, because something similar happened before that I resolved but I don't see the reason it was happening in the reference docs on Android Developers
2) Any advice on how to fix this
Below is the GameStart activity, LogCat with the error, and the XML files in question. Thanks in advance, I've spent 2 hours now trying to find this answer.
EDITED FILES/LOGCAT BELOW
LogCat:
12-04 13:48:06.322 826-826/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at com.saphiric.simproject.GameStart.<init>(GameStart.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Starting Activity (The error occurs when the app tries to start the GameStart activity):
package com.saphiric.simproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class TitleMenu extends ActionBarActivity {
public void startGame(View view){
Intent gameStart = new Intent(this, GameStart.class);
startActivity(gameStart);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
setContentView(R.layout.activity_main_menu);
}
}
Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Relative layout to handle main interaction area -->
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:background="#drawable/bg_text">
<TextView
android:id="#id/storyText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="#string/story_opening_one"
android:textColor="#color/black" />
<Button
android:id="#+id/advanceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/controlsFragment"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#drawable/button_advance"
android:onClick="advanceGame" />
<Button
android:id="#+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#id/advanceButton"
android:background="#drawable/menu_button" />
</RelativeLayout>
</RelativeLayout>
Fragment Class:
package com.saphiric.simproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Saphiric on 12/4/14.
*/
public class ControlsFragment extends Fragment {
/**
* Fragment Lifecycle Methods
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Inflates the layout resource for the fragment
return inflater.inflate(R.layout.controls_fragment, container, false);
}
#Override
public void onPause(){
}
}
GameStart activity:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity{
/**
* Necessary activity variables
*/
protected int clickCount = 0;
TextView storyText = (TextView) findViewById(R.id.storyText);
/**
* Sets up and alert dialogue builder for making decisions
* This will need to be revised during production
*/
AlertDialog.Builder decisionTime = new AlertDialog.Builder(getApplicationContext());
/**
* Handles advancing non character based conversations at the beginning
* of the story.
* If the player decides to investigate the scream, then the app loads the appropriate activity, and the same with the
* decision to leave the scene.
*/
public void advanceGame(View view){
clickCount = clickCount + 1; // Increments clickCount by 1 per click
if (clickCount == 1){
storyText.setText(R.string.story_opening_two);
} else if(clickCount == 2){
decisionTime.setTitle("Decision Time!"); // Sets the title for the decision box
decisionTime.setCancelable(false); // Sets it so that the decision can not be cancelled.
decisionTime.setPositiveButton("Investigate",new DialogInterface.OnClickListener() { // Sets up the positive button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
decisionTime.setNegativeButton("Leave the scene.",new DialogInterface.OnClickListener() { // Sets up the negative button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
}
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
}
}
GameStart Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_school_gate"
android:orientation="vertical">
<fragment
android:id="#+id/controlsFragment"
android:name="com.saphiric.simproject.ControlsFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="#layout/controls_fragment" />
</RelativeLayout>
No, you don't have any fragment here, read more on How to use fragments.
But that's not your problem it should work the way you did it.
The only problem is that you're calling findViewById in your constructor, or even before that.
findViewById only works if you have a UI, so you must do all UI initialization after setContentView in onCreate!
TextView storyText;
...
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
}
Also don't forget to call show() on decisionTime.
TextView storyText = (TextView) findViewById(R.id.storyText);
This should only be called after you set your contentview.
The final result should be:
TextView storyText;
And then on onCreate
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
1) The reason this is happening is that the view has not yet been instantiated at the time you are trying to get it's reference.
2) How to fix it: if you have a Fragment, then you should get a reference to it's View's in the Fragment.onCreateView() method. Then you can setup the Activity to talk to the Fragment to do whatever changes you need to the View.