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"/>
Related
mainactivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private WebView mywebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebview=(WebView)findViewById(R.id.webView);
WebSettings webSettings=mywebview.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebview.loadUrl("file:///android_asset/myresource.html");
mywebview.setWebViewClient(new WebViewClient());
}
#Override
public void onBackPressed() {
if (mywebview.canGoBack()) {
mywebview.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
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);
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
tools:context=".MainActivity"
tools:ignore="ExtraText">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<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"
tools:context=".MainActivity">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/webView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>12/13 23:40:42: Launching 'app' on Physical Device.
Install successfully finished in 14 s 668 ms.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.SplashActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 25636 on device 'xiaomi-redmi_7a-2c5b9bbe0406'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/Perf: Connecting to perf service.
I/FeatureParser: can't find pine.xml in assets/device_features/,it may be in /system/etc/device_features
E/Perf: Fail to get file list com.example.myapplication
E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
Fail to get file list com.example.myapplication
getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 25636
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.SplashActivity}: android.content.res.Resources$NotFoundException: Drawable com.example.myapplication:drawable/background with resource ID #0x7f07005f
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3304)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2040)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:221)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: android.content.res.Resources$NotFoundException: Drawable com.example.myapplication:drawable/background with resource ID #0x7f07005f
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/background.xml from drawable resource ID #0x7f07005f
at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:898)
at android.content.res.ResourcesImpl.originalLoadDrawable(ResourcesImpl.java:679)
at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:586)
at android.content.res.MiuiResourcesImpl.loadDrawable(MiuiResourcesImpl.java:307)
at android.content.res.Resources.getDrawableForDensity(Resources.java:920)
at android.content.res.Resources.getDrawable(Resources.java:859)
at android.content.Context.getDrawable(Context.java:696)
at androidx.core.content.ContextCompat.getDrawable(ContextCompat.java:454)
at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:144)
at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:411)
at androidx.appcompat.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:86)
at androidx.appcompat.app.AppCompatDelegateImpl.attachToWindow(AppCompatDelegateImpl.java:647)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureWindow(AppCompatDelegateImpl.java:623)
at androidx.appcompat.app.AppCompatDelegateImpl.onCreate(AppCompatDelegateImpl.java:350)
at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:105)
at com.example.myapplication.SplashActivity.onCreate(SplashActivity.java:11)
at android.app.Activity.performCreate(Activity.java:7893)
at android.app.Activity.performCreate(Activity.java:7880)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3279)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3443)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2040)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:221)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
E/AndroidRuntime: Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #4: tag requires a 'drawable' attribute or child tag defining a drawable
at android.graphics.drawable.LayerDrawable.inflateLayers(LayerDrawable.java:278)
at android.graphics.drawable.LayerDrawable.inflate(LayerDrawable.java:199)
at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:144)
at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1402)
at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1361)
at android.content.res.ResourcesImpl.createFromXmlForDensity(ResourcesImpl.java:1615)
at android.content.res.ResourcesImpl.loadXmlDrawable(ResourcesImpl.java:963)
at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:882)
... 30 more
I/Process: Sending signal. PID: 25636 SIG: 9
**splashactivity.java**
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
I think you have problems in your splashActivity not the main activity look for drawables that you use for your splash xml file you must import them correctly in your
res->drawable folder of your project weather they are vectors or pngs. Just try to import them in the right place.If it doesnt solve the the problem please put your splash xml file so I can help you.
Update:
Look at your splashactivity it doesnt have any content view
You must create layout for your splash activity .
Go to your project packages expand res folder then right click on layout and create a layout resource then name it as you prefere for example splash with lowercase then in your splash activity under oncreate method add:
setContentView(R.layout.splash.xml);
Put this line right after super.onCreate(savedinstancestate)
Recently i added the "Sign in with google" button and worked fine, but now when i try to run the app this error pops up, and i don't know why.
Here's the full exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.miapp, PID: 26644
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.miapp/com.example.loginapp.HomeScreen}: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to androidx.drawerlayout.widget.DrawerLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3114)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to androidx.drawerlayout.widget.DrawerLayout
at com.example.loginapp.HomeScreen.onCreate(HomeScreen.java:31)
at android.app.Activity.performCreate(Activity.java:7327)
at android.app.Activity.performCreate(Activity.java:7318)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3094)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
The error is on this line it seems like:
dl = findViewById(R.id.dl);
Here's the MainActivity (HomeScreen Activity)
package com.example.loginapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class HomeScreen extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private DrawerLayout dl;
private ActionBarDrawerToggle abdt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
NavigationView nav_view = findViewById(R.id.nav_view);
dl = findViewById(R.id.dl);
abdt = new ActionBarDrawerToggle(this, dl,R.string.Open, R.string.Close);
abdt.setDrawerIndicatorEnabled(true);
firebaseAuth = FirebaseAuth.getInstance();
dl.addDrawerListener(abdt);
abdt.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.miPerfil){
startActivity(new Intent(HomeScreen.this, MiPerfil.class));
}
if (id == R.id.ayudaPerfil){
Toast.makeText(HomeScreen.this, "Ayuda", Toast.LENGTH_SHORT).show();
}
if (id == R.id.agregarLista){
startActivity(new Intent(HomeScreen.this, HomeActivity.class));
Toast.makeText(HomeScreen.this, "Añadir actividad", Toast.LENGTH_SHORT).show();
}
if (id == R.id.logoutMenu){
Toast.makeText(HomeScreen.this, "Cerrando sesión... ", Toast.LENGTH_SHORT).show();
Logout();
}
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.navigation_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return super.onOptionsItemSelected(item) || abdt.onOptionsItemSelected(item);
}
private void Logout(){
firebaseAuth.signOut();
finish();
startActivity(new Intent(HomeScreen.this, MainActivityy.class));
}
}
And here's the XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF"
android:orientation="vertical"
android:id="#+id/dl">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000">
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/nav_view"
android:layout_gravity="start"
android:background="#FFF"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu">
</com.google.android.material.navigation.NavigationView>
</RelativeLayout>
Please, if you can help I appreciate it.
Stack trace clearly indicate the problem. You are using RelativeLayout in your xml and try to cast it as DrawerLayout in your Activity code. Use androidx.drawerlayout.widget.DrawerLayout instead of RelativeLayout in your layout xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF"
android:fitsSystemWindows="true"
tools:openDrawer="start"
android:id="#+id/dl">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000">
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/nav_view"
android:layout_gravity="start"
android:background="#FFF"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu">
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
I am new in android. I am trying to make simple login activity but I am getting run time error when I click on Login button. I think I am not getting data correctly.I have check and there is a data in SQLite in corresponding to that PK.
logcat.
FATAL EXCEPTION: main
Process: com.example.champ.remindme, PID: 4043
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:289)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference
at com.example.champ.remindme.Login.LogIn(Login.java:45)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
java code.
package com.example.champ.remindme;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
EditText edtUsername, edtPass;
String Username,Password;
int counter=3;
Button LoginButton;
SQLiteDatabase db;
// TextView txtAttempts;
//private final int interval = 3000;
/*private Runnable runnable = new Runnable(){
public void run() {
LoginButton.setEnabled(true);
}
}; */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginButton= (Button)findViewById(R.id.LoginButton);
edtUsername=(EditText)findViewById(R.id.edtitem);
// Username=edtUsername.getText().toString();
edtPass=(EditText)findViewById(R.id.password);
}
public void LogIn(View v){
if((edtUsername.getText().toString().trim().length()==0)||(edtPass.getText().toString().trim().length()==0))
{
showMessage("Error", "Please enter the empty Text Box");
return;
}
Cursor c=db.rawQuery("SELECT * FROM User WHERE Username='"+ edtUsername.getText()+"'", null);
if(c.moveToFirst())
{
Username=c.getString(1);
Password=c.getString(2);
if (edtUsername.getText().toString().equals(Username) && edtPass.getText().toString().equals(Password)){
Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, Menu.class);
intent.putExtra("Username",Username);
startActivity(intent);
}
else {
Toast.makeText(Login.this, "Login Failed", Toast.LENGTH_LONG).show();
counter--;
}
// txtAttempts.setText("Attempts Left: " + counter);
if (counter == 0) {
LoginButton.setEnabled(false);
// new Timer().schedule((TimerTask) runnable,interval);
}
}
else
{
showMessage("Error", "Invalid Username");
}
/*-----------------------------------------------------------------*/
}
public void Signup(View v) {
Intent intent = new Intent(this, SignUp.class);
startActivity(intent);
}
public void showMessage(String title,String message)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
XML code.
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.champ.remindme.Login"
android:background="#drawable/back">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/remind_me_logo"
android:contentDescription="Logo" />
<EditText
android:id="#+id/edtitem"
android:layout_width="265dp"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="#drawable/username_rounded_edited_text"
android:inputType="text"
android:hint="Username"
android:textAlignment="center"
android:layout_marginTop="37dp"
android:layout_below="#+id/imageView2"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/password"
android:layout_width="265dp"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="#drawable/pass_rounded_edited_text"
android:inputType="text"
android:hint="Password"
android:textAlignment="center"
android:layout_below="#+id/edtitem"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/LoginButton"
android:background="#drawable/blue_botton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/login"
style="#style/ButtonText"
android:onClick="LogIn"
android:layout_below="#+id/password"
android:layout_alignLeft="#+id/password"
android:layout_alignStart="#+id/password"
android:layout_alignRight="#+id/password"
android:layout_alignEnd="#+id/password" />
<Button
android:id="#+id/txtSignup"
android:background="#drawable/blue_botton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Signup"
style="#style/ButtonText"
android:onClick="Signup"
android:layout_below="#+id/LoginButton"
android:layout_alignLeft="#+id/LoginButton"
android:layout_alignStart="#+id/LoginButton" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView3"
android:src="#drawable/fb_loging"
android:layout_alignBottom="#+id/txtSignup"
android:layout_toRightOf="#+id/txtSignup"
android:layout_toEndOf="#+id/txtSignup" />
</RelativeLayout>
You didn't initialize db before using it. Add this to your onCreate()..
SQLiteDatabase db = this.getWritableDatabase();
Nothing to do. Just in your XML file's Button attribute remove
android:onClick
And in your activity type:-
LoginButton.setOnClickListener(new OnClickListener(){
#Override
onClick(){
LogIn();
}
});
I also faced this problem. Yeah, I know that your process is also not wrong. But the truth is I just don't know why that process doesn't work (for me). But when I implement onClick method programmatically then it works like a charm. And I hope you will also get your code working
And also add onCreate method
db = getWritableDatabase();
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.
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".