Null pointer exception when I pass data from another actitvty - java

I have a activity where you select a number in a spinner(dropdown-list in AndroidStudio) and sends it to a new activity/another class, before it is sent to a server. The array-adapter works fine, but using the getExtra Intent in the receiving activity is a lot of trouble for me.
The app crashes and logcat give this message:
NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference.
MainActivity.(MainActivity.java:76)
Line 76 in MainActivity String avd_nr= getIntent().getStringExtra("getData");
This is my code for passing the array value, and the line Log.i("data",avd); posts the spinner value(avd) in the logcat.
btnAvdeling.setOnClickListener(new View.OnClickListener()
{
final String avd = dropdown.getSelectedItem().toString();
#Override
public void onClick(View v)
{
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("getData",avd.toString());
startActivity(i);
Log.i("data",avd);
}
}
This is my code where I receive data
String avd_nr= getIntent().getStringExtra("getData");
private SurveyResponse fillInResponsData(Integer answer) {
surveyResponse.setAvdeling(avd_nr);
return surveyResponse;
}
Please give some help on what i need to add or change

in onCreate() Method put the following :
String avd_nr =getIntent.getExtras("getData");

String avd_nr =getIntent.getExtras("getData");
Its should be on onCreate() method

Related

Getter returning null in different class

while making an Android app, I have ran in the following problem:
My MainActivity looks like this:
...
private String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
tokenSetter();
}
private void tokenSetter() {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
Log.w("TRAZENITOKEN", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = Objects.requireNonNull(task.getResult()).getToken();
setToken(token);
Log.d("TRAZENITOKEN", "onGetToken: " + token);
// Log and toast
// Log.d("TRAZENITOKEN", "onComplete: " + token);
});
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
I know that the token value is being set as in an another method inside this MainActivity class, when I call getToken(), I get the value.
However, when I try to call getToken from an another Activity, something like this:
...
button.setOnClickListener(view -> {
FirebaseActions firebaseActions = new FirebaseActions();
MainActivity mainActivity = new MainActivity();
//firebaseActions.setUserNameOnToken(editText.getText().toString());
if(mainActivity.getToken() != null) editText.setText(mainActivity.getToken());
else editText.setText("Skafiskafnjak");
});
(I opted for the editText.setText method for debugging purposes, I am going to use it in the commented way)
The code snippet above always goes to the else part as the getToken is null.
Why does it return null in this class, if it returns a value in it's own class?
Could it be perhaps because I did
MainActivity mainActivity = new MainActivity();
An answer would be appreciated.
Thanks in advance!
MainActivity mainActivity = new MainActivity();
This activity instance is not the same one that the Android system created where you see the token being set. Besides, we never create an activity with new. The Android system creates activities according to the activity lifecycle and your code must work within this structure. To pass data between activities, you need to send it in the Intent when you call startActivity(). See the documentation for an example of how to do this.
Creating new activity causes new instance of that activity, therefor a new token which would be null
Send the token through the intent as String data from your MainActivity, and then from the second Activity, grab that String data(token), and do with it whatever you want.
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("token", yourTokenValue);
startActivity(intent);
and in onCreate method of your SecondActivity,you can use getIntent().getStringExtra("token"); to retrieve the token value which was passed from the first Activity
String token= getIntent().getStringExtra("token");

How to fix InvocationTargetException when sending hashmap to other activity

I'm trying to send HashMap to start new activity with startActivity(intent).
I followed the answer from this link:
How to send hashmap value to another activity using an intent
But I still get error
Of course, i tried to send String
intent.putExtra("test","some String");
startActivity(intent);
And it worked
My code:
HashMap<String,Diner> dinersOrdersHasMap = new HashMap<String,Diner>();
FillHashMap(); // Fill the HashMap with data
Intent intent = new Intent(this, BillForm.class);
intent.putExtra("dinersOrderHashMap",dinersOrdersHasMap);
startActivity(intent);
The exception:
"Could not execute method for android:onClick", e);
e.detailMessage = "Parcelable encountered IOException writing serializable
object (name = com.example.myfirstapp.Diner)
When i call
startActivity(intent);
is your Diner class Serializable or Parcelable ?
Could you post here your Diner class ?

Checking Azure connected Database onClick for login

So Azure spit the following code for me to insert into an activity (Android Studio is what I'm using)
Add the following line to the top of the .java file containing your launcher activity:
import com.microsoft.windowsazure.mobileservices.*;
Inside your activity, add a private variable
private MobileServiceClient mClient;
Add the following code the onCreate method of the activity:
mClient = new MobileServiceClient("https://pbbingo.azurewebsites.net", this);
Add a sample item class to your project::
public class ToDoItem{ public String id; public String Text;}
In the same activity where you defined mClient, add the following code:
ToDoItem item = new ToDoItem();
item.Text = "Don't text and drive";
mClient.getTable(ToDoItem.class).insert(item, new TableOperationCallback<item>(){
public void onCompleted(ToDoItem entity, Exception exception, ServiceFilter response)
{
if(exception == null){
//Insert Succeeded
} else {
//Insert Failed
}
}});
My goal is to create a login page. I understand that the above was probably offered up more with a ToList in mind. I just want to get the syntax correct today. The problem I think, is my basic class structure. I have created an OnClick Listener within my on create that gets the ID from a button in my layout. I don't need it checking for anything in the database until the button has been actually clicked to either login or register.
public class LoginClass extends AppCompatActivity{
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.MyLoginLayout);
MobileServiceClient mClient = null;
try {
mClient = new MobileServiceClient ("myAzureWebsite", "AzureKey", this);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Button Attempt = (Button) findViewById (R.id.mySubmitButton);
final MobileServiceClient finalMClient = mClient; // finalized so I can use it later.
Attempt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
final View thisView = v;
final MyToDoItemClass item = new MyToDoItemClass();
In MyToDoItemClass I have two variables (Both String) Just left over from
the example of a ToDoList (they are String ID and String Text)
item.Text = "Filler";
item.ID = "Fill";
finalMClient.getTable(MyToDoItemClass.class).insert(new Table OperationCallback<item>() { //<--- I'm getting an error that the variable, item
is from an unknown class...
public void onCompleted (Item entity, Exception exception, ServiceFilterResponse response){
if(exception == null) {
Intent i = new Intent (LoginClass.this, MainActivity.class);
startActivity(i);
}else{
Toast.makeText(thisView.getContext(), "Failed", Toast.LENGTH_LONG).show();
}}
});
}
});
}}
The problem is with that the TableOperationCallback is saying that the item from MyToDoItemClass class is from an unknown class.
There are many issues in your code, as below.
According to the javadoc for class MobileServiceClient, there is not a method insert(TableOperationCallback<E> callback), so the code finalMClient.getTable(MyToDoItemClass.class).insert(new Table OperationCallback<item>() {...} is invalid.
The generics E in Table OperationCallback<E> means that you need to write a POJO class name instead of E, not an object variable name like item, so the correct code should be new Table OperationCallback<MyToDoItemClass>, please see the Oracle tutorial for Generics to know more details.
The figure below shows all methods insert of class MobileServiceClient. The bold word Deprecated under the method name means that you should not use it for developing on new project, it‘s only compatible for old project on the new version of Java SDK.
Please follow the offical tutorial to develop your app. Any concern, please feel free to let me know.

Retrieving String From Java Class

I am fairly new to java / android programming and have mostly been following tutorials / reading. I have 2 classes called MainActivity and Homeactivity, the MainActivity is where the user logs in and HomePageactivity is opened via intent if the login is correct.
The username is passed through an edit text to which i have used the following code in the main class
String CurrentUser = editTextusername.getText().toString();
public String GetCurrentUser ()
{
return CurrentUser;
}
And this in the homepage class
MainActivity testing = new MainActivity();
String x = testing.GetCurrentUser();
CurrentUserName.setText(x);
This seems like it should work to me, how ever when launching my application it just crashes, and without the lines of code in the main activity it works fine
Any ideas as to what im doing wrong here guys
The String may be null during setting to TextView check before setting to textView
String CurrentUser = editTextusername.getText().toString();
public String GetCurrentUser ()
{
if(currentUser.length>0&&currentUser!="")
return CurrentUser;
else return "empty";
}
String x = testing.GetCurrentUser();
CurrentUserName.setText(""+x);
You can use intent to carry info from one Activity to another.
Read this: Intents
It is quite easy to transfer strings and primitive data types via intent, using putExtra() .
Some example code to make it more clear:
//this runs, for example, after a button click
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("username", userName);
startActivity(intent);
At the other end you can take them as like this:
String username = getIntent().getStringExtra("username");

When retrieving Uri from DB - "Could not execute non-public method for android:onClick", e); Java

I have an android app which stores information in an SQLite DB. On the activity I can open the Gallery, select a video, and then click on the "Watch Video" button and play that video.
HOWEVER, if I leave that activity and come back later, the saved URI IS in my DB, but loading it through the SAME onclick function produces this Exception error. ANY IDEAS WHY??
public void launchVideo(View view) {
if (my_video != null) {
Uri uri = Uri.parse(my_video);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "video/*");
startActivity(intent);//THROWS ILLEGAL ACTIVITY WHEN WORKING FROM SAVED URI
}
else{...
Using debugger I see the following...
#Override
public void onClick(#NonNull View v) {
if (mResolvedMethod == null) {
resolveMethod(mHostView.getContext());
}
try {
mResolvedMethod.invoke(mResolvedContext, v);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Could not execute non-public method for android:onClick", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(
"Could not execute method for android:onClick", e);
}
}
Similar posts have mentioned issues being the xml or use of methods with the same name. I do not have any methods with the same name and the xml is below for the button:
<Button
android:id="#+id/watchVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="launchVideo"
android:text="#string/watch_my_video"
app:layout_constraintStart_toStartOf="#+id/youtube_link"
app:layout_constraintTop_toBottomOf="#+id/youTubeEditText" />
The URI being passed in both the working and non working case is: "content://com.android.providers.media.documents/document/video%3A595"
Finally in my Debugger I see the following which I take a confirmation everything is public:
mResolvedMethod = {Method#6254} "public void com.android.mybrazilianjiu_jitsudictionary.Controller.AttackDetail.launchVideo(android.view.View)"
accessFlags = 134742017
artMethod = 3966325964
declaringClass = {Class#6043} "class com.android.mybrazilianjiu_jitsudictionary.Controller.AttackDetail"
declaringClassOfOverriddenMethod = {Class#6043} "class com.android.mybrazilianjiu_jitsudictionary.Controller.AttackDetail"
dexMethodIndex = 555
hasRealParameterData = false
parameters = null
override = false
shadow$_klass_ = {Class#3637} "class java.lang.reflect.Method"
shadow$_monitor_ = -2092042593
My latest guess is it is related to:
try {
mResolvedMethod.invoke(mResolvedContext, v);
However, I am just trying to have the video appear in the user's video player via implicit intent which IS what happens until I leave the activity and come back. Note: via checking the database and Debugger the SAME URI is present and being passed to the method in all scenarios.
THANK YOU FOR YOUR INSIGHTS!
By the following, I was able to fix the problem:
IllegalStateException: Could not execute method for android:onClick when trying to migrate to another page? was VERY helpful. On this advice I replaced my Button on click method with the following IN the OnCreate:
Button watchVideoButton = findViewById(R.id.watchVideo);
watchVideoButton.setOnClickListener(new View.OnClickListener() {...
The problem that then surfaced was lack of persistent permissions for the Uri when returning to the activity.
Persistent permission was taken via the following:
getContentResolver().takePersistableUriPermission(uri, FLAG_GRANT_READ_URI_PERMISSION);
...which I placed BEFORE the onCreate in:
androidx.activity.result.ActivityResultLauncher<String> mGetContent = registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri uri) {
my_video = uri.toString();
getContentResolver().takePersistableUriPermission(uri, FLAG_GRANT_READ_URI_PERMISSION);
Move move;
move = new Move(MoveID,PositionTableID, MoveName, MoveStatus, GiY,AttackY, DefenseY, Description, internetVideoLink, my_video);
myJiuJitsuDictionaryRepository.insert(move);
}
});

Categories

Resources