android.content.Context.getPackageName()' on a null object reference - android

I am begineer in android and having problems
Above error showing while i'm trying to open main activity from login button on login activity.
when pressing the login button suddenly app stops and following error is showing
following error is showing in android monitor
10-20 18:47:23.314 13432-13432/com.antherx.prasenjit.ihdfbachatgat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antherx.prasenjit.ihdfbachatgat, PID: 13432
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.antherx.prasenjit.ihdfbachatgat/com.antherx.prasenjit.ihdfbachatgat.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2460)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2629)
at android.app.ActivityThread.access$800(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1474)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5706)
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:1033)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4358)
at com.antherx.prasenjit.ihdfbachatgat.MainActivity.<init>(MainActivity.java:26)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2629)
at android.app.ActivityThread.access$800(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1474)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5706)
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:1033)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
this is login activity code is their any problem in this code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Please do not
Email = (EditText)findViewById(R.id.email);
Password = (EditText)findViewById(R.id.password);
String wel_on_login = "Welcome On IHDF Bachat Gat app";
Toast welcome = Toast.makeText(getApplicationContext(),wel_on_login,Toast.LENGTH_LONG);
welcome.show();
final Button signIn = (Button)findViewById(R.id.email_sign_in_button);
final Button register = (Button)findViewById(R.id.registration) ;
final Intent main_trans = new Intent(this, MainActivity.class);
final Intent reg_trans = new Intent(this, register.class);
signIn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
startActivity(main_trans);
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(reg_trans);
}
});
this is main activity codes is their any problem in here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.home_toolbar);
setSupportActionBar(toolbar);
newMember = (MenuItem)findViewById(R.id.new_member);
newProfile = (MenuItem)findViewById(R.id.profile) ;
Drawer =(DrawerLayout)findViewById(R.id.drawerLayout);
sToggle = new ActionBarDrawerToggle(this,Drawer,R.string.open,R.string.close);
Grp_ico = (ImageView)findViewById(R.id.grp_ico);
Drawer.addDrawerListener(sToggle);
sToggle.syncState();
getSupportActionBar();
String wel_on_main = "You are successfully on Main Home";
Toast welcome = Toast.makeText(getApplicationContext(),wel_on_main,Toast.LENGTH_LONG);
welcome.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.new_member :
startActivity(new_new_member);
case R.id.profile :
startActivity(new_new_profile);
case R.id.setting :
startActivity(new_new_setting);
case R.id.meeting :
startActivity(new_new_meeting);
default:
return super.onOptionsItemSelected(item);
}
}

for me i was trying to use the application with no base context accidently.
so i had in my application override:
#Override
protected void attachBaseContext(Context newBase) {
}
//instead of calling its super:
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);}

Change your getApplicationContext() from
Toast welcome = Toast.makeText(getApplicationContext(),wel_on_main,Toast.LENGTH_LONG);
to either getBaseContext() or preferably this

Related

Blank Screen showing up after Image Selected from Gallery

I am trying to get an image into the ImageView but whenever I click a picture on the Gallery the app shows a blank screen and closes down.
This ImageView is in a fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_auction_add, container, false);
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
dateTimeAction(v);
return v;
}
private void imageSelectAction(View v) {
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_image = v.findViewById(R.id.auction_add_imageView);
choosePicture();
}
private void choosePicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
if (data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
auction_add_image.setImageURI(selectedImageUri);
}
}
}
}
The Inital Declaration
public class auction_add extends Fragment {
private static final int SELECT_PICTURE = 10;
private static final int PERMISSION_CODE = 11;
ImageButton auction_add_imageViewButton;
//References to all Auction Add Page EditText
EditText auction_add_itemNameTxt;
EditText auction_add_descriptionTxt;
EditText auction_add_initialPriceTxt;
EditText auction_add_startTimeTxt;
EditText auction_add_endTimeTxt;
//Reference to ImageView
private ImageView auction_add_image;
final Calendar myCalendar = Calendar.getInstance();
Would Appreciate the help thanks!
Edit:
Followed is the error on the Run tab of Android Studio
W/System: A resource failed to call close.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.projectcrest, PID: 5618
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=242868079, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:31 flg=0x1 }} to activity {com.example.projectcrest/com.example.projectcrest.pages.LandingPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
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 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at com.example.projectcrest.fragments.auction_add.onActivityResult(auction_add.java:155)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2905)
at androidx.fragment.app.FragmentManager$9.onActivityResult(FragmentManager.java:2885)
at androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:377)
at androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:336)
at androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:624)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at android.app.Activity.dispatchActivityResult(Activity.java:8310)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5008)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5056) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
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: 5618 SIG: 9
By looking into the exception it seems that the App is crashing in #onActivityResult function at line auction_add_image.setImageURI(selectedImageUri); due to NPE (Null Pointer Exception). This expection/crash is caused since the auction_add_image object has null value instead of an ImageView.
After taking an close look into your code, I think the issue has occured due to following code:
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageSelectAction(v);
}
});
Note that in #onClick function you are passing view v on which you are going to perform the #findViewById operation. Here the passed view v refers to the auction_add_imageViewButton instead of the v you have captured above.
I would suggest to modify the code as below (just rename the v variable in #onClick function):
auction_add_imageViewButton = v.findViewById(R.id.auction_add_imageView_button);
auction_add_imageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View buttonView) {
imageSelectAction(v);
}
});
This way the variable name collision could be avoided and the error would be resolved.
Also, in case this does not solve your problem, then please check whether the #findViewById is returning an ImageView instead of null. In case the Id provided to #findViewById is not present on the screen or in the child views of view (on which the #findViewById) is being performed then the #findViewById will return null value.
Also, check whether you have assigned null value to auction_add_image in anywhere your code.

Application has stopped when close button clicked

I am developing an android app but my app is being stopped
Here is the steps I did: I ...
1. am using tabbed activity and there is a list view
2. Each element in listView is registered for context menu
3. First option is context menu is for editing info for the view
4. Once it is clicked, it opens another activity(intent is used)
And the error is when I click close button while the new activity is open, I am having error:"Unfortunately app has stopped"
Edit Class:
public class Editor extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
Intent intent = getIntent();
int position = intent.getIntExtra("POSITION", -1);
TextView t = (TextView)findViewById(R.id.intentResult);
t.setText(position+"");
}
}
Intent Call :
public boolean onContextItemSelected(MenuItem item) {
if(item.getItemId()==EDIT_ID){
}
else if(item.getItemId()==DELETE_ID){
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
Intent intent = new Intent(getContext(), Editor.class);
intent.putExtra("POSITION", acmi.position);
startActivity(intent);
}
return super.onContextItemSelected(item);
}
//acmi is just an integer
Error: 01-21 16:54:59.714 2820-2820/com.example.abu_bakr.darsjadvali
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abu_bakr.darsjadvali, PID: 2820
java.lang.RuntimeException: Unable to resume activity
{com.example.abu_bakr.darsjadvali/com.example.abu_bakr.darsjadvali.MainActivity}:
java.lang.IllegalStateException: trying to requery an already closed
cursor android.database.sqlite.SQLiteCursor#2e3a8e12
at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:3033)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3064)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.IllegalStateException: trying to requery an
already closed cursor android.database.sqlite.SQLiteCursor#2e3a8e12
at android.app.Activity.performRestart(Activity.java:6076)
at android.app.Activity.performResume(Activity.java:6099)
at
android.app.ActivityThread.performResumeActivity(ActivityThread.java:3022)
at
android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3064) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5356) 
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:908) 
at com
.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
As your error log says, it's a database exception.
Post the complete code of your MainActivity so we can understand what's going on

Getting NullPointerException in a BankList Activity when sending data from MainActivity using intent in android [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 trying to pass an arraylist between two activities, but my app crashes at the second activity. Can someone help me solve in this problem...
Here,
I have two parts of my MainActivity from where sending arraylist to another Activity which is BankList Activity
Part 1:
Intent intent = new Intent(MainActivity.this, BankList.class);
intent.putStringArrayListExtra("BANKLIST",bankListArrayList);
startActivity(intent);
Part 2:
Result<ArrayList<Bank>> banklist = (Result<ArrayList<Bank>>)data;
if(banklist.getCode().equals("00")){
Toast.makeText(this,"list Banks success",Toast.LENGTH_SHORT).show();
bankListArrayList = new ArrayList<>();
for(Bank bank :banklist.getData()){
bank.getIin();
bank.getLogo();
bank.getName();
b
ankListArrayList.add(bank.toString());
}
Log.d("BANK_ARRAYLIST","BANK_ARRAYLIST"+bankListArrayList);
Toast.makeText(this,"BANK_ARRAYLIST"+bankListArrayList,Toast.LENGTH_SHORT).show();
}
My Second Activity (BankList)
public class BankList extends AppCompatActivity {
ListView bankList;
ArrayList<String> bankdataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_list);
bankList = (ListView)findViewById(R.id.bankList);
Intent intent = getIntent();
intent.getStringArrayListExtra("BANKLIST");
bankdataList.add(intent.toString());
Toast.makeText(BankList.this,"bank list"+bankdataList,Toast.LENGTH_SHORT).show();
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item, bankdataList);
bankList.setAdapter(itemsAdapter);
}
}
And my Log is :-
11-09 12:58:01.548 1941-1941/com.example.rajdeeps.upi_integration E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rajdeeps.upi_integration, PID: 1941
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rajdeeps.upi_integration/com.example.rajdeeps.upi_integration.BankList}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' 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 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.example.rajdeeps.upi_integration.BankList.onCreate(BankList.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)
You forgot to initialize your bankdataList Arraylist just initialize it
ArrayList<String> bankdataList= new ArrayList();;
Sample code
public class BankList extends AppCompatActivity {
ListView bankList;
ArrayList<String> bankdataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_list);
bankdataList= new ArrayList();
bankList = (ListView)findViewById(R.id.bankList);
Intent intent = getIntent();
intent.getStringArrayListExtra("BANKLIST");
bankdataList.add(intent.toString());
Toast.makeText(BankList.this,"bank list"+bankdataList,Toast.LENGTH_SHORT).show();
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item, bankdataList);
bankList.setAdapter(itemsAdapter);
}
}
You have not initialize bankdataList before add items.
bankdataList = new ArrayList<String>();
bankdataList.add(intent.getStringArrayListExtra("BANKLIST"));

null pointer on floating button

I created floating action button for phone dial. tried to run the app but ended up error in my fab call.
I don't know what went wrong with floating action button.
can you show me how to fix it?
here it is my fab code
FloatingActionButton fabshare = (FloatingActionButton) findViewById(fab);
FloatingActionButton fabcall = (FloatingActionButton) findViewById(fab);
fabshare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
String shareSubject = String.valueOf(dataLaundry.getNama());
String shareBody = String.valueOf(dataLaundry.getAlamat());
i.putExtra(Intent.EXTRA_SUBJECT, "Laundrize - " + shareSubject);
i.putExtra(Intent.EXTRA_TEXT, shareSubject + "\n" + shareBody + "\n\n" +
"http://maps.google.com/?q="
+ alamat.getText().toString().toLowerCase().replaceAll(" ","+"));
startActivity(Intent.createChooser(i, "Share via"));
}
});
fabcall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent callIntent = new Intent (Intent.ACTION_DIAL, Uri.parse("tel:"+ noTelp));
startActivity(callIntent);
}
});\
and here the error
FATAL EXCEPTION: main
Process: com.example.rizkafs.laundrize, PID: 25885
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rizkafs.laundrize/com.example.rizkafs.laundrize.DetailsActivity}: 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:2660)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730)
at android.app.ActivityThread.access$800(ActivityThread.java:185)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5847)
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:1010)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
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.rizkafs.laundrize.DetailsActivity.onCreate(DetailsActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6117)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2613)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2730) 
at android.app.ActivityThread.access$800(ActivityThread.java:185) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5847) 
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:1010) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 
Define id of both Fab icons in activity.
FloatingActionButton fabshare = (FloatingActionButton) findViewById(R.id.fabshare);
FloatingActionButton fabcall = (FloatingActionButton) findViewById(R.id.fabcall);

Activity started from service visibility null

i am trying to have an activity launched from a service.
My problem is hiding/showing this activity.
The activity is started like so
overlay = new BubbleOverlay();
Intent intent = new Intent(this, overlay.getClass()).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Activity:
public class BubbleOverlay extends Activity {
private boolean active = false;
private View mainView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.overlay_layout);
mainView = findViewById(R.id.main_overlay_layout);
if(mainView == null)
Log.d("BubbleOverlay", "onCreate: MainView is null");
}
public void setActive(boolean value){
active = value;
}
public void hide(){
active = false;
mainView.setVisibility(View.INVISIBLE);
}
public void show(){
active = true;
mainView.setVisibility(View.VISIBLE);
}
I am trying to toggle the visibility of the mainView from the service.
Handler handler = new Handler();
Runnable runnable_longClick = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
overlay.hide();
}
};
handler.postDelayed(runnable_longClick, 5000);
this produces the following error:
07-28 05:51:56.549 21690-21690/com.derp.derp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.derp.derp, PID: 21690
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
at com.derp.derp.BubbleOverlay.hide(BubbleOverlay.java:37)
at com.derp.derp.BubbleService$4.run(BubbleService.java:181)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6044)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
The reason you're getting the Null Pointer Exception is the mainView has not been initialised before its use. This happens because the Activity's onCreate() method which holds the object's initialise statement has not been called (with respect to the overlay object you created inside your Service). The onCreate() method will only be called once the Activity is created.
In order to call the hide() method of the Activity from the Service you need to create a proper communication channel between the Activity and the Service i.e. you need to bind the Service to your Activity. I know, this approach requires a bit of coding efforts but its the best approach and it will guarantee you flawless and smooth functioning for your app.

Categories

Resources