app crashes in landscape mode? - android

I have a problem with my application. It crashes each time whenever I
launch my app on an Emulator and I switch to landscape mode. But it work
fine in portrait mode. Please what can i do to solve this. Thanks in
advance!
I put "android:configChanges="orientation|screenSize|keyboardHidden" in the
activity declaration in my manifest but still crash.
This is the error:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a1697759.projetintra/com.example.a1697759.projetintra.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
This is my java code:
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import static com.example.a1697759.projetintra.R.id.etTotalPrix;
public class MainActivity extends AppCompatActivity {
Button btnInscription;
EditText etQuantite;
Spinner spinner;
Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInscription = (Button) findViewById(R.id.btnInscription);
etQuantite = (EditText) findViewById(R.id.etQuantite);
EditText etTotalPrix;
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
// Use a TextWatcher to disable/enable button
etQuantite.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int
arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {}
#Override
public void afterTextChanged(Editable string) {
if(string.length() > 0) {
btnInscription.setEnabled(true);
} else {
btnInscription.setEnabled(false);
}
}
});
btnInscription.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//Demarrer le nouvelle activite
Intent intent = new Intent(MainActivity.this,
ResumeActivity.class);
//Spinner 1
Bundle b = new Bundle();
b.putString("name", spinner.getSelectedItem().toString());
intent.putExtras(b);
//Spinner 2
Bundle b2 = new Bundle();
b2.putString("name2", spinner2.getSelectedItem().toString());
intent.putExtras(b2);
//EditText Quantite
Bundle q = new Bundle();
q.putString("name3", etQuantite.getText().toString());
intent.putExtras(q);
//Reset spinner and editText
spinner.setSelection(0);
spinner2.setSelection(0);
etQuantite.setText("");
Toast.makeText(MainActivity.this, "Vous avez fait votre
commande",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a1697759.projetintra, PID: 21317
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a1697759.projetintra/com.example.a1697759.projetintra.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4974)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.a1697759.projetintra.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4974) 
at android.app.ActivityThread.-wrap21(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6688) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358) 

You have to create a landscape layout for that.
Just go to the design tab in your xml file
click on the Layout Variants button.
Select the Create Landscape Variation
a landscape layout will be created. Then you are free to change the layout according to your requirements.

Related

Android Studio: Issue with OnResume and SharedPreferences: Fatal Error at Runtime

All,
Just want to be straight with everyone that I have no idea what I am doing lol. But I am having an issue implementing SharedPreferences onPause\onResume in this project, and I am wondering if someone can tell me where I am going wrong.
Error details:
`E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.androidlabs, PID: 2260
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androidlabs/com.example.androidlabs.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:744)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.androidlabs.MainActivity.<init>(MainActivity.java:19)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
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:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) `
Here is my main activity code. I can tell that the issue is coming from onResume (I think!) but no clue why!
`package com.example.androidlabs;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
//initializing variables
Button next = (Button) findViewById(R.id.next);
EditText name = (EditText) findViewById(R.id.name); //initializing variables
public static final String SHARED_PREF = "sharedprefs";
public static final String TEXT = "text";
private String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sh.edit();
editor.putString("name", name.getText().toString());
editor.apply();
openNameActivity();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String savedName = sh.getString("name",null);
if (savedName != null){
name.setText(savedName);
}
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
//save the users name in My Shared Pref
SharedPreferences.Editor editor = sh.edit();
editor.putString("name", name.getText().toString());
editor.apply();
}
public void openNameActivity(){
EditText name = (EditText) findViewById(R.id.name);
String nameText = name.getText().toString();
Intent intent = new Intent(MainActivity.this, NameActivity.class);
intent.putExtra("name", nameText);
startActivityForResult(intent, 1);
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
int result = data.getIntExtra("namePref", 0);
if(result == 0){
Toast.makeText(MainActivity.this,"Choose a new name", Toast.LENGTH_LONG).show();
}else{
finishAndRemoveTask();
}
}
if(resultCode == RESULT_CANCELED){
Toast.makeText(MainActivity.this,"Something went wrong", Toast.LENGTH_LONG).show();
}
}
}
}`
Your app is crashing when you open your app?
It looks like you are doing initialisation of your button and editText at wrong place
can you move below mentioned code to onCreate method and place it below of setContentView method
next = (Button) findViewById(R.id.next);
name = (EditText) findViewById(R.id.name);
and also you will need to declare next and name both variable

Getting error after after installing app on emulator, Builds/Installs fine

I am trying to build this game from GitHub which i migrated to android studio at my best. After all done and this is the error i get after installing on emulator. It builds fine without any problem and installs the app on emulator but nothing happens on emulator. When i see the emulator i see the app is there but if i open it it closes after a blank screen. I got the logcat below. Since i didn't code this project i don't really understand most of it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.puzzles, PID: 3722
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.puzzles/com.example.puzzles.PuzzleActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
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:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.puzzles.PuzzleActivity.decodeGameSizeFromIntent(PuzzleActivity.java:128)
at com.example.puzzles.PuzzleActivity.onCreate(PuzzleActivity.java:97)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
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:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 3722 SIG: 9
Here is the PuzzleActivity.java file code....
package com.example.puzzles;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ViewSwitcher;
import com.example.puzzles.R;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class PuzzleActivity extends Activity {
public static final int DIALOG_PAUSED_ID = 44;
GameBoard board;
int screenOrientation;
Bitmap sourceImage;
ViewSwitcher inGameViewSwitcher;
private class PauseDialog extends Dialog implements View.OnClickListener{
public PauseDialog(){
super(PuzzleActivity.this, R.style.PauseMenuStyle);
this.setContentView(R.layout.pause_menu);
Button resumeButton = (Button) findViewById(R.id.pausemenu_resumeButton);
resumeButton.setOnClickListener(this);
Button quitButton = (Button) findViewById(R.id.pausemenu_quitButton);
quitButton.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.pausemenu_resumeButton:
this.dismiss();
break;
case R.id.pausemenu_quitButton:
// Intent intent = new Intent(this.getContext(), MainMenuActivity.class);
// startActivity(intent);
finish();
break;
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
screenOrientation = getIntent().getIntExtra(MainMenuActivity.EXTRA_BOARD_ORIENTATION, 1);
// String str = screenOrientation == 0 ? "PORTRAIT" : "HORIZONTAL";
// Log.d("KAMIL", "Orientation recorded by puzzleactivity: " + str);
//locking the app in needed position
if(screenOrientation == GameBoard.ORIENTATION_PORTRAIT)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//making the app full screen
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_puzzle);
//Setting backgrounds to black.
((RelativeLayout) findViewById(R.id.centerLayout)).setBackgroundColor(Color.BLACK);
((FrameLayout) findViewById(R.id.backgroundLayout)).setBackgroundColor(Color.BLACK);
inGameViewSwitcher = (ViewSwitcher) findViewById(R.id.inGameViewSwitcher);
//now the fun begins :>
//Crating a game board.
board = new GameBoard(decodeGameSizeFromIntent(),
(RelativeLayout) findViewById(R.id.centerLayout),
screenOrientation, this);
sourceImage = loadBitmapFromIntent();
ImageView preview = (ImageView) findViewById(R.id.previewImageView);
preview.setImageBitmap(sourceImage);
PuzzleCreator creator = new PuzzleCreator(sourceImage, board);
board.loadTiles(creator.createPuzzle());
board.drawBoard();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_puzzle, menu);
return true;
}
private com.example.puzzles.Dimension decodeGameSizeFromIntent(){
com.example.puzzles.Dimension size = null;
String str = getIntent().getStringExtra(MainMenuActivity.EXTRA_GAMESIZE);
String[] gameSizes = getResources().getStringArray(R.array.gamesizes);
if(str.equals(gameSizes[0])) size = new com.example.puzzles.Dimension(2,3);
else if(str.equals(gameSizes[1])) size = new com.example.puzzles.Dimension(3,5);
else if(str.equals(gameSizes[2])) size = new com.example.puzzles.Dimension(4,7);
else if(str.equals(gameSizes[3])) size = new com.example.puzzles.Dimension(6,10);
else
throw new RuntimeException("Decoding game size from intent failed. String does not match.");
return size;
}
private Bitmap loadBitmapFromIntent(){
Bitmap selectedImage = null;
Uri imgUri = (Uri) getIntent().getParcelableExtra(MainMenuActivity.EXTRA_IMGURI);
try{
InputStream imageStream = getContentResolver().openInputStream(imgUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
}catch(FileNotFoundException ex){
Log.e("LOADING ERROR", "Cannot load picture from the URI given", ex);
}
/*
if(selectedImage.getWidth()>selectedImage.getHeight()){
selectedImage = BitmapOperator.rotateBitmap(selectedImage, 90);
}*/
return selectedImage;
}
#Override
protected void onRestart() {
super.onRestart();
//Intent intent = new Intent(this, MainMenuActivity.class);
//startActivity(intent);
showDialog(DIALOG_PAUSED_ID);
}
#Override
protected Dialog onCreateDialog(int id) {
PauseDialog dialog = new PauseDialog();
if(id == DIALOG_PAUSED_ID){
// dialog.setContentView(R.layout.pause_menu);
}
return dialog;
}
#Override
public void onBackPressed() {
showDialog(DIALOG_PAUSED_ID);
}
public void inGameButtonsOnClick(View view){
switch(view.getId()){
case R.id.previewButton:
inGameViewSwitcher.showNext();
break;
case R.id.backToGameButton:
inGameViewSwitcher.showPrevious();
break;
}
}
}
Help is much appreciated. Thanks
The log tells you that in this line:
if(str.equals(gameSizes[0])) size = new com.example.puzzles.Dimension(2,3);
str Or gameSizes[0] is null, you need to debug this code and check why you getting null
Null is legit so it's not effect your build

Start Activity with parameters from FirebaseRecyclerAdapter

I need to start an activity with details of some data passing a parameter that I get from my Firebase DB on my Intent, but everytime I click an item on the Adapter my app crashes.
I have an activity like this:
And need to open something like this:
Here is my Adapter.setOnClickListener code:
viewHolder.eventCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent eventIntent = new Intent(getContext(), EventActivity.class);
eventIntent.putExtra("event_id", event.getName());
startActivity(eventIntent);
}
});
And here is my new activity code to get that parameter:
package br.com.ministeriosonhodedeus.sonhodedeus.activity;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import br.com.ministeriosonhodedeus.sonhodedeus.R;
import br.com.ministeriosonhodedeus.sonhodedeus.domain.Event;
import br.com.ministeriosonhodedeus.sonhodedeus.fragments.EventFragment;
public class EventActivity extends BaseActivity {
private Event e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
setUpToolbar();
e = getIntent().getParcelableExtra("event_id");
getSupportActionBar().setTitle(e.getName());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ImageView appBarImg = (ImageView) findViewById(R.id.appBarImg);
Picasso.with(getContext()).load(e.geturl_foto()).into(appBarImg);
if (savedInstanceState == null) {
EventFragment frag = new EventFragment();
frag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.EventFragment, frag).commit();
}
}
public void setTitle(String s) {
CollapsingToolbarLayout c = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
c.setTitle(s);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
ActivityCompat.finishAfterTransition(getActivity());
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my error logcat:
03-21 14:18:12.390 27190-27190/br.com.ministeriosonhodedeus.sonhodedeus E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.ministeriosonhodedeus.sonhodedeus, PID: 27190
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.ministeriosonhodedeus.sonhodedeus/br.com.ministeriosonhodedeus.sonhodedeus.activity.EventActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String br.com.ministeriosonhodedeus.sonhodedeus.domain.Event.getName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String br.com.ministeriosonhodedeus.sonhodedeus.domain.Event.getName()' on a null object reference
at br.com.ministeriosonhodedeus.sonhodedeus.activity.EventActivity.onCreate(EventActivity.java:30)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6123) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
Any idea of what went wrong? Thanks!
To solve this, please change this line of code:
e = getIntent().getParcelableExtra("event_id");
with
String event_id = (String) getIntent().getExtras().get("event_id");
and this:
getSupportActionBar().setTitle(e.getName());
with
getSupportActionBar().setTitle(event_id);

null pointer exception in captcha [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am implementing the captcha code in my form but I am getting a null pointer exception the method getImage().
I have two captcha codes in the project one is working fine but the other one is showing the following error. I don't know why it is not taking the captcha as a parameter.
I am providing the logcat and the mainactivity.java below.
Logcat
FATAL EXCEPTION: main
Process: com.mws.tms_application, PID: 6983
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mws.tms_application/com.mws.tms_application.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
at com.mws.tms_application.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6540) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
main activity.java
package com.mws.tms_application;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView Registerlink;
Button Submit_btn ,Reset_btn,Link_btn;
EditText Username,Usermob,UserAddress,Usermailid,Userpass,Usercapt;
ActionBar actionBar;
ImageView imageView1;
TextCaptcha textCaptcha1;
//#2eb82e
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Registerlink = (TextView) findViewById(R.id.loginlink);
Submit_btn=(Button)findViewById(R.id.Submit_btn);
Reset_btn=(Button)findViewById(R.id.Main_Reset_btn);
Username=(EditText)findViewById(R.id.username_edtext);
Usermob=(EditText)findViewById(R.id.usermob_no_edtext);
UserAddress=(EditText)findViewById(R.id.userAddresss_edtext);
Usermailid=(EditText)findViewById(R.id.usermailid_edtext);
Userpass=(EditText)findViewById(R.id.userpass_edtext);
Usercapt=(EditText)findViewById(R.id.usercapt_edtext);
Link_btn=(Button)findViewById(R.id.Link_btn);
imageView1=(ImageView)findViewById(R.id.register_capt_imageview);
imageView1.setImageBitmap(textCaptcha1.getImage());
actionBar=getSupportActionBar();
actionBar.show();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2eb82e")));
MainLogic();
}
private void MainLogic()
{ Link_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,Home_Navigation_Activity.class);
startActivity(i);
}
});
Submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isValidData();
}
});
Reset_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
claredata();
}
});
Registerlink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,Login_Activity.class);
startActivity(i);
}
});
}
/* Userid,Username,usermob,userAddress,usermailid,userpass,usercapt;*/
public boolean isValidData()
{
String id,name,mobile,address,email,password,captch;
name=Username.getText().toString();
mobile=Usermob.getText().toString();
address=UserAddress.getText().toString();
email=Usermailid.getText().toString();
password=Userpass.getText().toString();
/*captch=Usercapt.getText().toString();*/
if (!name.equals("")&&!mobile.equals("")&&mobile.length()>=10&&mobile.length()<=13&&!address.equals("")&&!email.equals("")&&!password.equals(""))
{
if (validEmail((email)))
{
return true;
}
else
{
AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
alt.setMessage("Invalid Email_Id");
alt.setCancelable(true);
alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog=alt.create();
alertDialog.show();
return false;
}
}
else
{
AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
alt.setMessage("Please fill all details");
alt.setCancelable(true);
alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog=alt.create();
alertDialog.show();
}
return false;
}
public boolean claredata()
{
Username.setText("");
Usermob.setText("");
UserAddress.setText("");
Usermailid.setText("");
Userpass.setText("");
/*captch=Usercapt.getText().toString();*/
return false;
}
private boolean validEmail(String email) {
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (email.trim().matches(emailPattern))
{
return true;
}
return false;
}
}
It is coming from
imageView1.setImageBitmap(textCaptcha1.getImage());
you are using textCaptcha1 but you have not initialized it anywhere

AsyncTaskLoader not initialized after screen rotation

I am using recyclerview which is getting its data from adapter which gets data trough AsyncTaskLoader. Everything runs fine until I rotate the screen from portrait to landscape. At that point I get nullpointer exception when using .forceLoad(); on my asyncTaskLoader
I have absolutelly no idea why is the fileLoader null when the same onCreate method is called regardless of orientation and it works on portrait and doesnt on landscape.
Here is the code:
package sk.tomus.filescoper;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
mport java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<File>> {
private android.support.v4.content.AsyncTaskLoader<List<File>> fileLoader;
private DirectoryManager directoryManager;
private RecyclerView recyclerView;
private FileRecyclerAdapter recyclerAdapter;
private RecyclerView.LayoutManager layoutManager;
private boolean isLandscape;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
directoryManager = new DirectoryManager(prefs.getString("PREFERENCE_EDIT_DEF_FOLDER", "/"));
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
isLandscape = getResources().getBoolean(R.bool.isLandscape);
if (isLandscape) {
layoutManager = new GridLayoutManager(this, 4);
} else {
layoutManager = new LinearLayoutManager(this);
}
recyclerView.setLayoutManager(layoutManager);
recyclerAdapter = new FileRecyclerAdapter(new ArrayList<File>());
getSupportLoaderManager().initLoader(0, null, this);
//below is line 51 where the code crashes
fileLoader.forceLoad();
recyclerView.setAdapter(recyclerAdapter);
}
#Override
protected void onResume() {
super.onResume();
recyclerAdapter.setOnItemClickListener(new FileRecyclerAdapter.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i("LOG", " Clicked on Item " + position);
}
});
}
private void onFileClicked(File file) {
if (file.isDirectory()) {
Log.i("opening directory", file.getAbsolutePath());
if (!file.canRead()) {
Toast.makeText(getApplicationContext(), "inaccessible", Toast.LENGTH_SHORT).show();
return;
}
directoryManager.setPreviousDir(directoryManager.getCurrentDir());
directoryManager.setCurrentDir(file);
if (fileLoader.isStarted()) {
fileLoader.onContentChanged();
}
} else {
openFile(Uri.fromFile(file));
}
}
private void openFile(Uri fileUri) {
String mimeType = directoryManager.getMimeType(fileUri);
if (mimeType != null) {
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(fileUri, mimeType);
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "file type recognized, but no apps to open it", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "unknown file type", Toast.LENGTH_LONG).show();
}
}
#Override
public Loader<List<File>> onCreateLoader(int i, Bundle bundle) {
fileLoader = new android.support.v4.content.AsyncTaskLoader<List<File>>(this) {
#Override
public List<File> loadInBackground() {
Log.i("loader loading:", directoryManager.getCurrentDir().toString());
return directoryManager.getAllFiles(directoryManager.getCurrentDir());
}
};
return fileLoader;
}
#Override
public void onLoadFinished(Loader<List<File>> loader, List<File> data) {
recyclerAdapter.setFiles(data);
}
#Override
public void onLoaderReset(Loader<List<File>> loader) {
}
}
here is the stacktrace:
08-29 00:50:21.176 16411-16411/sk.tomus.filescoper E/AndroidRuntime: FATAL EXCEPTION: main
Process: sk.tomus.filescoper, PID: 16411
java.lang.RuntimeException: Unable to start activity ComponentInfo{sk.tomus.filescoper/sk.tomus.filescoper.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.content.AsyncTaskLoader.forceLoad()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
at android.app.ActivityThread.access$900(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5389)
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:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.content.AsyncTaskLoader.forceLoad()' on a null object reference
at sk.tomus.filescoper.MainActivity.onCreate(MainActivity.java:51)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053) 
at android.app.ActivityThread.access$900(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:211) 
at android.app.ActivityThread.main(ActivityThread.java:5389) 
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:1020) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815) 
thanks in advance for any help
You shouldn't be calling forceLoad() in your onCreate() method at all - it won't be created until onCreateLoader() is called (which is after onCreate() finishes).
As per the Making Loading Data Lifecycle Aware blog post, you should instead be calling forceLoad() in your AsyncTaskLoader's onStartLoading method. This ensures that your Loader is created and ready to start loading before you call forceLoad().
fileLoader = new android.support.v4.content.AsyncTaskLoader<List<File>>(this) {
#Override
public void onStartLoading() {
forceLoad();
}
#Override
public List<File> loadInBackground() {
Log.i("loader loading:", directoryManager.getCurrentDir().toString());
return directoryManager.getAllFiles(directoryManager.getCurrentDir());
}
};

Categories

Resources