Null pointer exception android array - java

I am making an app that has 2 java classes: MainActivity and SecondActivity. MainActivity initiates the SecondActivity by using an onClick method.
The SecondActivity has 2 arrays stored in the strings.xml file. The SecondActivity class wants to store all the array variables from strings.xml to itself, in order to use it for some methods. I think i am doing it the wrong way, as i tried storing the arrays directly in the SecondActivity and it worked but when i am storing the arrays in strings.xml it gives a NullPointerException.
Here is the SecondActivity code:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SecondActivity extends Activity {
private final String CLASS_NAME = "SecondActivity";
String [] Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
String [] meanings = getResources().getStringArray(R.array.meanings_array);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}
public void onStart(){
super.onStart();
Log.d( CLASS_NAME, "onStart invoked!" );
}
public void onPause(){
super.onPause();
Log.d( CLASS_NAME, "onPause invoked!!" );
}
public void onResume(){
super.onResume();
Log.d( CLASS_NAME, "onResume invoked!!" );
}
public void onStop(){
super.onStop();
Log.d( CLASS_NAME, "onStop invoked!!!" );
}
public void onDestroy(){
super.onDestroy();
Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
}
public void onRestart(){
super.onRestart();
Log.d( CLASS_NAME, "onRestart invoked!!" );
}
// event handler for the button
public void onClick(View view) {
Intent data = new Intent();
EditText usr =
(EditText) findViewById(R.id.vocabularies); // get user input
// set the data part (an URI reference) of an intent
data.setData(Uri.parse(usr.getText().toString()));
String s = data.getData().toString();
int flag = 0;
for(int i=0; i<Vocabularies.length;i++)
{
if(s.equals(Vocabularies[i]))
{
flag = i;
}
}
Toast.makeText(this, "YOU'VE ENTERED: " + s, Toast.LENGTH_LONG ).show();
String m = meanings[flag];
String disp = "Vocabulary: " + s + "\n" + "Meaning: " + m;
TextView textViewObj1 = (TextView) findViewById(R.id.meaning);
textViewObj1.setText(disp);
//finish(); //--- close the activity AND RETURN CONTROL TO THE REQUESTING ACTIVITY
//EditText txt_username = (EditText) findViewById(R.id.txt_username);
} // end onClick
}
Here is the MainActivity code:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String CLASS_NAME = "FirstActiviy";
private int request_Code = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d( CLASS_NAME, "onCreate invoked!" );
}
public void onStart(){
super.onStart();
Log.d( CLASS_NAME, "onStart invoked!" );
}
public void onPause(){
super.onPause();
Log.d( CLASS_NAME, "onPause invoked!!" );
}
public void onResume(){
super.onResume();
Log.d( CLASS_NAME, "onResume invoked!!" );
}
public void onStop(){
super.onStop();
Log.d( CLASS_NAME, "onStop invoked!!!" );
}
public void onDestroy(){
super.onDestroy();
Log.d( CLASS_NAME, "onDestroy INVOKED!!!" );
}
public void onRestart(){
super.onRestart();
Log.d( CLASS_NAME, "onRestart invoked!!" );
}
// event handler for the button (activity 2)
public void onClick(View view) {
startActivityForResult( new Intent(
"com.android.ict.seneca.androidpocketguide.second"), // declared by an intent filter
request_Code); // (requesting) activity ID
Log.d( CLASS_NAME, "after startActivityForResult" );
//intent.setData(Uri.parse("com.seneca.lab2b.abbas"));
//startActivity(intent);
}
/*
public void onActivityResult( int requestCode, // used to match the REQUESTING activity ID
int resultCode, // result code set by the sender (i.e. the TARGET activity)
Intent data ) // an intent passed by the sender (i.e. the TARGET activity)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
//TextToSpeech(data.getData().toString());
Intent intent = getIntent();
String s = data.getData().toString();
TextView textViewObj1 = (TextView) findViewById(R.id.line);
textViewObj1.setText(s);
Toast.makeText(
this,
"MESSAGE RECEIVED: " + s, // retrieve data from the intent
// API Question: What is the return type of getData()?
Toast.LENGTH_LONG ).show();
}
}
Log.d( CLASS_NAME, "onActivityResult: what is next?" );
}
// event handler for a button (activity 3)
public void onClick3(View view) {
Intent dataIntent = new Intent( this, ThirdActivity.class );//"com.seneca.lab2b.third"); // explicit intent
// the putExtra( ) method
dataIntent.putExtra( "greeting", "Good morning Android!" );
dataIntent.putExtra( "number", 123 );
// create a Bundle object
Bundle bundle = new Bundle();
bundle.putString( "My name", "Abbas Zoeb" );
bundle.putInt( "Student ID", 56789 );
// putExtras( ): store the bundle in the intent
dataIntent.putExtras( bundle );
// launch the third activity
startActivity( dataIntent );
//startActivity( new Intent( this, ThirdActivity.class ) );
}
*/
}
Here is the error log:
09-21 23:43:19.907 26183-26183/com.android.ict.seneca.androidpocketguide E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.ict.seneca.androidpocketguide, PID: 26183
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.android.ict.seneca.androidpocketguide/com.android.ict.seneca.androidpocketguide.SecondActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at com.android.ict.seneca.androidpocketguide.SecondActivity.(SecondActivity.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Here is the string.xml file:
<resources>
<string name="app_name">Android Pocket Guide</string>
<string-array name="Vocabularies_array">
<item>activity</item>
<item>AVD</item>
<item>ART</item>
<item>Dalvik</item>
<item>intent</item>
<item>intent filter</item>
<item>explicit intent</item>
<item>implicit intent</item>
<item>LogCat</item>
<item>bundle</item>
<item>Gradle</item>
<item>Android Device Monitor</item>
<item>SDK manager</item>
<item>minSdkVersion</item>
</string-array>
<string-array name="meanings_array">
<item>An activity represents a single screen with a user interface just like window or frame of Java</item>
<item>An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual device by defining hardware and software options to be emulated by the Android Emulator.</item>
<item>Android Runtime (ART) is an application runtime environment used by the Android operating system.</item>
<item>Dalvik is a part of the software stack that makes up the Android platform.</item>
<item>Intent can be defined as a simple message objects which is used to communicate from 1 activity to another.</item>
<item>Specifies the types of intents that an activity, service, or broadcast receiver can respond to</item>
<item>An explicit intent is one that you use to launch a specific app component, such as a particular activity or service in your app</item>
<item>Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.</item>
<item>Logcat is a command-line tool that dumps a log of system messages, including stack traces when the device throws an error and messages that you have written from your app with the Log class.</item>
<item>A Bundle is a set of key/value pairs, where it implements an interface called Parcelable.</item>
<item>Gradle is a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.</item>
<item>Android Device Monitor is a standalone tool that provides a UI for several Android application debugging and analysis tools.</item>
<item>A software development kit that enables developers to create applications for the Android platform.</item>
<item>An integer designating the minimum API Level required for the application to run.</item>
</string-array>
</resources>

Try this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
meanings = getResources().getStringArray(R.array.meanings_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}

Try declaring your arrays in the global context, then assigning them some value during one of the activity's lifecycle stages (i.e. onCreate(), onResume(), etc.).
The issue you're having is with getResources(). I would create a global variable of type Context. Then, what I would do in onCreate() is this:
context = this;
vocabularies = context.getResources().getStringArray(R.array.Vocabularies_array);
meanings = context.getResources().getStringArray(R.array.meanings_array);
Hope that helps!

These variable initializations...
String [] Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
String [] meanings = getResources().getStringArray(R.array.meanings_array);
...probably need to go in a constructor, or even more likely in onCreate(...), specifically after
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

Initialization of the variables in some method like oncreate/onPostcreated e.g.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vocabularies = getResources().getStringArray(R.array.Vocabularies_array);
meanings = getResources().getStringArray(R.array.meanings_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_dropdown_item_1line, Vocabularies);
//ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, meanings);
AutoCompleteTextView textView =
(AutoCompleteTextView) findViewById(R.id.vocabularies);
textView.setThreshold(2); // minimum number of characters to be typed
textView.setAdapter(adapter); // connect the list of suggestions to the View object
}

Related

How to move reusable functionalities to a generic class and invoke another activity from there?

I am new to Android development and I am facing an issue in invoking an activity from a generic class where I have a reusable function.
I have MainActivity where I need to check if the application has Network connectivity and then check if the user is already signed in.
If the user is signed in I need to open the Rate activity otherwise I will open the Login activity.
I thought I can keep the logic that checks the Network connectivity and shows the popup reusable and move it to a Global class as below
public class Global extends AppCompatActivity {
public static boolean hasConnectivity = false;
public static boolean userSignedIn = false;
String TAG = "Debug Log - Helper";
Context context;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
context = this;
}
private void networkConnectionErrorDialog(final Context context, final Class targetClass){
Log.d(TAG, "Show Alert Dialog");
new AlertDialog.Builder(context)
.setTitle(R.string.connection_error_title)
.setMessage(R.string.connection_error_message)
.setIcon(R.drawable.warning)
.setPositiveButton(
R.string.try_again,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "Trying Again");
isNetworkAvailable(context, targetClass);
}
}).show();
}
protected void isNetworkAvailable(Context context, Class targetClass) {
if(NetworkUtil.isConnected(context)){
Log.d(TAG, "Has connectivity");
if(targetClass != null){
Log.d(TAG, targetClass.toString());
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
}
hasConnectivity = true;
return;
}else{
Log.d(TAG, "Has no connectivity");
hasConnectivity = false;
networkConnectionErrorDialog(context, targetClass);
}
}
}
I pass in the targetClass as Login.class or Rate.class (based on user signed in state) from the MainActivity where isNetworkAvailable() is invoked.
I am getting the following error. Could someone help me fix the issue and help me understand if my approach needs improvement?
java.lang.RuntimeException: Unable to resume activity {com.solitontech.dayatsoliton/com.solitontech.dayatsoliton.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3581)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4488)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4445)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4806)
at android.app.Activity.startActivity(Activity.java:4774)
at com.solitontech.dayatsoliton.Global.isNetworkAvailable(Global.java:50)
at com.solitontech.dayatsoliton.MainActivity.onResume(MainActivity.java:68)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1355)
at android.app.Activity.performResume(Activity.java:7117)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3556)
It looks like your application is experiencing a null pointer exception in your activity's onResume method. If you had called startActivityForResult, make sure that the data in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{..}
is non null before processing it.
As for your question about starting an activity from your helper class Global, you can define a function like this.
private static void goToActivity(Context context, Class<?> activityClass){
Intent intent = new Intent(context, activityClass);
context.startActivity(intent);
}
You can call this method as below.
goToActivity(context,TargetActivity.class);
Good luck.
Intent targetIntent = new Intent(context, targetClass);
startActivity(targetIntent);
above code is wrong. You should pass your current activity and target activity here.
Intent intent = new Intent(CurrentActivity.this, TargetingActivity.class);
startActivity(intent);
As a example :
If you want to start ActivtyB form ActivtyA
Intent intent = new Intent(ActivityA.this, ActivityD.class);
startActivity(intent);
1st try to correct this error. then you can find some others.

OneSignal Android NotificationOpenedHandler - start activity

Trying to migrate from Parse to OneSignal and I am stuck on how to start a new Activity after the user clicks on a push notification. My handler is working, the log shows the text, the issue seems to be how to gain access to the application context from within my push opened handler. The example code is vague, getApplicationContext() does not work without first doing something else.
One post I came upon, unrelated to OneSignal, suggests extending the Application class to gain access to the application context. This did not produce any syntax errors but my app crashes.
Code:
package com.linkedresponder.onesignal;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OneSignal;
import org.json.JSONObject;
class NotificationOpenHandler extends Application implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
private Context mContext;
#Override
public void onCreate() {
this.mContext = getApplicationContext();
}
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
String customKey;
if (data != null) {
customKey = data.optString("customkey", null);
if (customKey != null) {
Log.i("OneSignalExample", "customkey set with value: " + customKey);
} else {
Log.i("OneSignalExample", "No data");
}
}
if (actionType == OSNotificationAction.ActionType.ActionTaken)
Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);
Intent intent = new Intent(mContext, PushClicked.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Error:
er.onesignal E/AndroidRuntime: FATAL EXCEPTION: main Process: com.linkedresponder.onesignal, PID: 5680
java.lang.RuntimeException: Unable to start receiver com.onesignal.NotificationOpenedReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3018)
at android.app.ActivityThread.-wrap18(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1544)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
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)
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.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4868)
at com.linkedresponder.onesignal.NotificationOpenHandler.notificationOpened(NotificationOpenHandler.java:41)
at com.onesignal.OneSignal.fireNotificationOpenedHandler(OneSignal.java:1009)
at com.onesignal.OneSignal.runNotificationOpenedCallback(OneSignal.java:954)
at com.onesignal.OneSignal.handleNotificationOpen(OneSignal.java:1041)
at com.onesignal.NotificationOpenedProcessor.processIntent(NotificationOpenedProcessor.java:101)
at com.onesignal.NotificationOpenedProcessor.processFromActivity(NotificationOpenedProcessor.java:57)
at com.onesignal.NotificationOpenedReceiver.onReceive(NotificationOpenedReceiver.java:11)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3011)
at android.app.ActivityThread.-wrap18(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1544) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
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) 
Here's how I made it work:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
OneSignal.startInit(this)
.setNotificationOpenedHandler(new MyNotificationOpenedHandler(this))
.init();
}
}
The NotificationOpenedHandler custom class
public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
private Application application;
public MyNotificationOpenedHandler(Application application) {
this.application = application;
}
#Override
public void notificationOpened(OSNotificationOpenResult result) {
// Get custom datas from notification
JSONObject data = result.notification.payload.additionalData;
if (data != null) {
String myCustomData = data.optString("key", null);
}
// React to button pressed
OSNotificationAction.ActionType actionType = result.action.type;
if (actionType == OSNotificationAction.ActionType.ActionTaken)
Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);
// Launch new activity using Application object
startApp();
}
private void startApp() {
Intent intent = new Intent(application, MyActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
}
}
Don't forget to add this to your manifest:
<application ...>
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
</application>
The short answer to this issue is to include your handler for the push notification open within the same class where you initialize OneSignal:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Init OneSignal
OneSignal.startInit(this).setNotificationOpenedHandler(new NotificationOpenHandler()).init();
Toolbar mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new RecordingsFragment())
.commit();
}
}
class NotificationOpenHandler implements OneSignal.NotificationOpenedHandler {
// This fires when a notification is opened by tapping on it.
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
String stationName = data.optString("stationName");
String timestamp = data.optString("timestamp");
String filename = data.optString("filename");
String url = getString(R.string.callResourceUrl) + filename;
Intent intent = new Intent(getApplicationContext(), CallActivity.class);
intent.putExtra("stationName", stationName);
intent.putExtra("time", timestamp);
intent.putExtra("url", url);
// intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
Updated code in 2022
OneSignal.NotificationOpenedHandler replaced by OneSignal.OSNotificationOpenedHandler
and result.notification.payload.additionalData replaced by result.notification.additionalData
Full code
class OneSignalNotificationOpenHandler(private val context : Context) : OneSignal.OSNotificationOpenedHandler {
override fun notificationOpened(result: OSNotificationOpenedResult?) {
if (result == null) return
val type = result.action.type
val data = result.notification.additionalData
val name = data.optString("name")
val intent = Intent(context, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_NEW_TASK
intent.putExtra("name", name)
context.startActivity(intent)
}
}
Add it to OneSignel after OneSignal.initWithContext(this)
OneSignal.setNotificationOpenedHandler(OneSignalNotificationOpenHandler(applicationContext))
Don't forget to Add the following to your AndroidManifest.xml to prevent the launching of your main Activity
<application ...>
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
</application>

Photo by Camera Upload Exception (Firebase Storage)

I'm trying to upload an image taken by the camera in an android application to Firebase storage. The problem is that after I take the picture, in the confirmation activity, I pressed the confirm button and it says that "Unfortunately the application stopped".
This is the image when I press the check button, and the app crashes...
This is my code, the application has the option to upload pictures using the gallery and the camera.
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.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private Button selectImage;
private Button selectImageByCamera;
private ImageView imageView;
private StorageReference storageReference;
private ProgressDialog progressDialog;
private static final int CAMERA_REQUEST_CODE = 1;
private static final int GALLERY_INTENT= 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
storageReference=FirebaseStorage.getInstance().getReference();
/*
* Code section to upload an image using the Gallery.
*/
selectImage=(Button)findViewById(R.id.btn_uploadImg);
progressDialog = new ProgressDialog(this);
selectImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
/*
* Code section to upload an image using the Camera.
*/
selectImageByCamera=(Button)findViewById(R.id.btn_uploadImgCamera);
imageView=(ImageView)findViewById(R.id.imageView);
selectImageByCamera.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
//Upload the image to Firebase Update
if(requestCode==GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
});
}
//Code to upload image taken by the camera to firebase storage
if(requestCode==CAMERA_REQUEST_CODE && resultCode == RESULT_OK)
{
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri2 = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri2.getLastPathSegment());
filepath.putFile(uri2).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
{
Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
}
#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);
}
}
I have this USER PERMISSIONS in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
I have this Firebase dependencies in app/build.gradle
compile 'com.google.firebase:firebase-core:9.8.0'
compile 'com.google.firebase:firebase-database:9.8.0'
compile 'com.google.firebase:firebase-storage:9.8.0'
compile 'com.google.firebase:firebase-auth:9.8.0'
And finally this is the exception thrown when I run the app in my Moto G4 6.0.1 (The app has permissions to use Camera and Gallery)
FATAL EXCEPTION: main
Process: mx.com.jamba.jamba, PID: 16543
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {mx.com.jamba.jamba/mx.com.jamba.jamba.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3720)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at mx.com.jamba.jamba.MainActivity.onActivityResult(MainActivity.java:186)
at android.app.Activity.dispatchActivityResult(Activity.java:6470)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3716)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763) 
at android.app.ActivityThread.access$1400(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
I don't know what to do, it would be great if you guys to help me :)
Thank you!
The exception occurs because the Uri in onActivityResult() is null:
Uri uri = data.getData();
The documentation for capturing a camera image explains:
The Android Camera application saves a full-size photo if you give it
a file to save into. You must provide a fully qualified file name
where the camera app should save the photo.
Follow the example in the documentation to create a file Uri and add it to the intent for the camera app.
Please try this
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
Bitmap mImageUri = (Bitmap) data.getExtras().get("data");
select.setImageBitmap(mImageUri);
}
then start posting

Android Retrofit "Attempt to invoke virtual method on a null object reference"

Hi first of all i searched some similar questions like mine but unfortunately i couldn't find the similarity of my code to them so please here me out
I have a Main Activity Class
public class MainActivity extends AppCompatActivity {
public ProgressDialog loading;
public String[] itemer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RetrofitHandler handler = new RetrofitHandler();
handler.getContacts(MainActivity.this);
}
public void getter(String[] response, int size) {
String[] itemer;
itemer = new String[size];
if (response != null) {
itemer = response;
Toast.makeText(MainActivity.this, itemer[0], Toast.LENGTH_SHORT).show();
}
}
And a Handler for my result
public class RetrofitHandler {
public String[] item;
public static final String ROOT_URL = "http://api.androidhive.info";
public List<Contacts> contacts;
// final MainActivity main = new MainActivity();
public void getContacts(final Context context) {
final ProgressDialog loading = ProgressDialog.show(context, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
api.getContacts(new Callback<Contacts>() {
#Override
public void success(Contacts contacts, Response response) {
loading.dismiss();
MainActivity update = new MainActivity();
List<Contact> contactList = contacts.getContacts();
item = new String[contactList.size()];
int size = contactList.size();
for (int i = 0; i < contactList.size(); i++) {
item[i] = contactList.get(i).getName();
}
update.getter(item, size);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_LONG).show();
}
});
}
But I get an error on my response in the main activity here is my log
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:542)
at android.widget.Toast.<init>(Toast.java:102)
at android.widget.Toast.makeText(Toast.java:259)
at com.exist.kelvs.retrofit2.MainActivity.getter(MainActivity.java:55)
at com.exist.kelvs.retrofit2.RetrofitHandler$1.success(RetrofitHandler.java:41)
at com.exist.kelvs.retrofit2.RetrofitHandler$1.success(RetrofitHandler.java:28)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
I maked sure that the handler item where not null tested it with toast but when i pass it to getter it gives me the error where did i do wrong? :(
MainActivity update = new MainActivity();
Never instantiate activities with new. They are not initialized to be useful.
Instead, you can pass your activity as a reference where needed. Change
public void getContacts(final Context context)
to e.g.
public void getContacts(final MainActivity mainActivity)
and use mainActivity where you need an activity Context (such as with Dialogs) and when you need to invoke a method on MainActivity.
Note that generally passing activity references to async operations can be prone to significant memory leaks, and you need to take activity lifecycle into account - the activity might not be active when the async operation finishes.
try to delete the toast in your main activity or replace Mainactivity.this to getApplicationContext() .
from :
Toast.makeText(MainActivity.this, itemer[0], Toast.LENGTH_SHORT).show();
to :
Toast.makeText(getApplicationContext(), itemer[0], Toast.LENGTH_SHORT).show();

Android: No Activity found to handle Intent (trying to add an activity to exsisting app)

Ok so I am very new to the Android programming, I am starting week 2 of this class and cannot for the life of me figure out what is going wrong. I have read/watched tons of tutorials on adding new Activities and nothing works.
Assignment: Use the Activities app and add a fourth activity
My activity is simple, 3 buttons and an image. One button makes the image visible and the other makes it invisible. Third returns back to the main.
Note: I edited the original app to have buttons on Main Activity because it had me hitting center on the d-pad which I found dumb. Another note is that Activity 2 & 3 use the same layout and do basically the same thing from what I can tell
public class MainActivity extends Activity {
String tag = "Events";
int request_Code = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---hides the title bar---
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Log.d(tag, "In the onCreate() event");
Button act2Butt = (Button) findViewById(R.id.act2Butt);
Button act3Butt = (Button) findViewById(R.id.act3Butt);
Button act4Butt = (Button) findViewById(R.id.act4Butt);
act2Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.ACTIVITY2"), request_Code);
}
});
act3Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.ACTIVITY2"), request_Code);
}
});
act4Butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent("net.learn2develop.MYACTIVITY"), request_Code);
}
});
}
/*
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
//startActivity(new Intent("net.learn2develop.ACTIVITY2"));
//startActivity(new Intent(this, Activity2.class));
startActivityForResult(new Intent(
"net.learn2develop.ACTIVITY2"),
request_Code);
}
return false;
}
*/
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),
Toast.LENGTH_LONG).show();
}
}
}
public void onStart()
{
super.onStart();
Log.d(tag, "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag, "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
public class MyActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity4);
Button yesButt = (Button) findViewById(R.id.yesButton);
Button noButt = (Button) findViewById(R.id.noButton);
Button finButt = (Button) findViewById(R.id.finButton);
final ImageView img1 = (ImageView) findViewById(R.id.image1);
yesButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
img1.setVisibility(View.VISIBLE);
}
});
noButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
img1.setVisibility(View.INVISIBLE);
}
});
finButt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent data = new Intent();
data.setData(Uri.parse("OMG IT WORKS"));
setResult(RESULT_OK, data);
finish();
}
});
}
public class Activity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String defaultName="";
Bundle extras = getIntent().getExtras();
if (extras!=null)
{
defaultName = extras.getString("Name");
}
//---get the EditText view---
EditText txt_username =
(EditText) findViewById(R.id.txt_username);
txt_username.setHint(defaultName);
//---get the OK button---
Button btn = (Button) findViewById(R.id.btn_OK);
//---event handler for the OK button---
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =
(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(
txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
}
I have entered the code for Main Activity, My Activity (the one I made), and Activity 2. My Activity runs great and does exactly what I want it to but if I try to access it from main it dies.
928-928/net.learn2develop.Activities E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: net.learn2develop.Activities, PID: 928
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=net.learn2develop.MYACTIVITY }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1765)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3736)
at android.app.Activity.startActivityForResult(Activity.java:3697)
at net.learn2develop.Activities.MainActivity$3.onClick(MainActivity.java:48)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
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:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
This code is for my last attempt and making it work before throwing my hands up. Last thing I did was make My Activity act like the other and use startActivityForResult.
Any help would help greatly. I don't know if it matters or not but I do not have a .class for My Activity in the bin directory but there is one for all the others.
If you need any more info please just ask.
Like I said before I'm really new to the whole Android area.
Edit: Manifest
<activity android:name=".MyActivity"
android:label="My Activity">
<intent-filter>
<action android:name="net.learn2develop.MYACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
You may need to add the Activity to the manifest. If you are sure you have done this, I would recommend using an Intent slightly differently.
Try using an Intent the following way:
Intent intent = new Intent(MyActivity.this, SecondActivity.class);
startActivityForResult(intent, requestCode);
The first parameter of this Intent is the current Activity. The second parameter is theActivity you wish to navigate to. Handling an Intent this way prevents a small typo in the package name which would throw that exception. As long as the Activity you are trying to navigate to is in the manifest and you have set up your Intent like the code above, everything should work fine.
Good luck and happy coding!
you need to add your activity to your manifest
<activity
android:name=".MySecondActivity"
android:label="#string/title_second_activity">
</activity>
net.learn2develop.MYACTIVITY
Android is not finiding the above activity like other engineers said,add this activity in your manifest file so JVM can find which class you are referring to.

Categories