java.lang.NullPointerException: Attempt to read from null array, android studio Java - java

I was trying to use intent to pass a string array to my next activity but I keep getting a null array reference error when I try to use the array in the next activity
This is the first activity
Button next;
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(first_activity.this, second_activity.class);
intent.putExtra("strarr", strarr);
}
The next activity has the following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
String[] strarr = intent.getStringArrayExtra("strarr");
TextView textview = findViewById(R.id.textView10);
textview.setText("when did you take strarr[i]);
// the error happens here when I try to reference I get the following message:
"Caused by: java.lang.NullPointerException: Attempt to read from null array"
Any help is appreciated, Thank You

Use getIntent(), then add a null check:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent != null && intent.getStringArrayExtra("strarr") != null){
String[] strarr = intent.getStringArrayExtra("strarr");
TextView textview = findViewById(R.id.textView10);
textview.setText("when did you take " + strarr[i]);
}
}

Related

How to start another activity and start a method inside it?

As soon as the setOnClickListener executes I want to start another activity and transmit the variable cn.getID() to it. When inside the other activity I want to immidietaly start the method findlocation and give cn.getID() to it.
The method findLocation is not finished yet. The idea is, once it gets the ID of the other activities button, i can search with sqllite in my database for the place it belongs to, get longitude and latitude and tell mapcontroller focus the world map on this point.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verladestellen);
final DB_Verladestellen db = new DB_Verladestellen(this);
List<DB_Place> placeList = db.getAllDBPlaces();
final LinearLayout layout = (LinearLayout) findViewById(R.id.verladestellen_liste);
for (final DB_Place cn : placeList) {
final LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Button place = new Button(this);
place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
place.setText(cn.getName());
place.setId(cn.getID());
row.addView(place);
row.setId(cn.getID());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams();
params.weight = 1.0f;
place.setLayoutParams(params);
place.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here I want to call the method to start the other activity
//and transmit cn.getID().
openMap(null);
}
});
layout.addView(row);
}
}
//The method to start the other activity
public void openMap(View view) {
Intent intent = new Intent(this, UI_MainActivity.class);
startActivity(intent);
}
This is the method from inside the new activity I want to execute immidietaly after it has started:
public void findLocation(View view){
MapView map = (MapView) findViewById(R.id.map);
IMapController mapController = map.getController();
mapController.setZoom(17);
GeoPoint myLocation = new GeoPoint(PLACEHOLDER X , PLACEHOLDER Y);
mapController.animateTo(myLocation);
}
EDIT:
#Murat K. After some edits this is my whole class now:
public class UI_Verladestellen extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verladestellen);
final DB_Verladestellen db = new DB_Verladestellen(this);
List<DB_Place> placeList = db.getAllDBPlaces();
final LinearLayout layout = (LinearLayout) findViewById(R.id.verladestellen_liste);
for (final DB_Place cn : placeList) {
final LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Button place = new Button(this);
place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
place.setText(cn.getName());
place.setId(cn.getID());
row.addView(place);
row.setId(cn.getID());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams();
params.weight = 1.0f;
place.setLayoutParams(params);
place.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMap(cn.getID());
}
});
layout.addView(row);
}
}
public void openMap(int view) {
Intent intent = new Intent(UI_Verladestellen.this, UI_MainActivity.class);
intent.putExtra("findLocation", 1);
startActivity(intent);
}
}
And this is the getIntent of my onCreate method in UI_MainActivity:
int i = getIntent().getIntExtra("findlocation", 999);
if(i == 1){
findLocation(i);
}
As I edited into my earlier comment, i cant see where my Button-ID is recieved. At first i thought i would be my ID, but that wouldnt work, since The Button ID can be every number from 1 to n.
You can achieve this with an Intent e.g.
Intent i = new Intent(BaseActivity.this, YourSecondActivity.class);
intent.putExtra("METHOD_TO_CALL", 1);
startActivity(i);
and in your onCreate() method of the starting Activity you check for it.
#Override
public void onCreate(Bundle savedInstanceState) {
int i = getIntent().getIntExtra("METHOD_TO_CALL", 999);
if(i == 1){
callMethod(i);
}
EDIT:
//The method to start the other activity
public void openMap(View view) {
Intent intent = new Intent(this, UI_MainActivity.class);
intent.putExtra("METHOD_TO_CALL", 1); // the 1 is a example, put your ID here
startActivity(intent);
}
Step #1: Use putExtra() to add your ID value to the Intent that you use with startActivity()
Step #2: In the other activity, call getIntent() in onCreate() to retrieve the Intent used to create the activity instance. Call get...Extra() (where ... depends on the data type) to retrieve your ID value. If the ID value exists, call your findLocation() method.
It depends on how you want it to work. If you only want it to execute when the activity is created (when it starts or screen rotates) then call the method within the activities onCreate method. If you want it called whenever the user returns to that activity which can include them leaving the app and coming back to it sometime later then onResume would be a better spot for it. Calling the method from either should work as you hope though.
I also recommend looking over the Activity lifecycle as that will help you a lot in the future.

Android: How can I keep empty EditText fields out of a randomized count?

I am working on this Android app that has five EditText fields in the first activity.
Users can fill out any of the EditText fields they want and after pressing a Button, they'll get a randomized answer on a single TextView in the second activity.
For example, if the user fills out 2 EditText fields, the empty ones are still part of the random count.
Also, whenever a user fills out random EditText fields (an example: choiceThree and choiceFour), nothing gets passed to the second activity.
Can anyone help me? Thanks!
Here's the code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText choiceOne;
EditText choiceTwo;
EditText choiceThree;
EditText choiceFour;
EditText choiceFive;
Button mainButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
choiceOne = (EditText) findViewById(R.id.inputOne);
choiceTwo = (EditText) findViewById(R.id.inputTwo);
choiceThree = (EditText) findViewById(R.id.inputThree);
choiceFour = (EditText) findViewById(R.id.inputFour);
choiceFive = (EditText) findViewById(R.id.inputFive);
mainButton = (Button) findViewById(R.id.inputButton);
mainButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
if(choiceOne.getText().toString() != null && !choiceOne.getText().toString().trim().equals(""))
{
intent.putExtra("choiceOne", choiceOne.getText().toString());
}
if(choiceTwo.getText().toString() != null && !choiceTwo.getText().toString().trim().equals(""))
{
intent.putExtra("choiceTwo", choiceTwo.getText().toString());
}
if(choiceThree.getText().toString() != null && !choiceThree.getText().toString().trim().equals(""))
{
intent.putExtra("choiceThree", choiceThree.getText().toString());
}
if(choiceFour.getText().toString() != null && !choiceFour.getText().toString().trim().equals(""))
{
intent.putExtra("choiceFour", choiceFour.getText().toString());
}
if(choiceFive.getText().toString() != null && !choiceFive.getText().toString().trim().equals(""))
{
intent.putExtra("choiceFive", choiceFive.getText().toString());
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
SecondActivity.java
public class SecondActivity extends Activity {
TextView answerDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
answerDisplay = (TextView) findViewById(R.id.display);
Intent intent = getIntent();
String[] choice = {intent.getStringExtra("choiceOne"), intent.getStringExtra("choiceTwo"),
intent.getStringExtra("choiceThree"), intent.getStringExtra("choiceFour"),
intent.getStringExtra("choiceFive")};
int choiceRandom = (int) (Math.random()*intent.getExtras().size());
answerDisplay.setText(choice[choiceRandom]);
}
When no input is there in an EditText, it doesnt return getText as null, but as "".
And in MainActivity, work with an ArrayList instead of an array.. gives you the option to use the various methods including add and remove.
String choiceX = intent.getStringExtra("choiceX");
if(!choiceX.equals("")) {
choice.add(choiceX);
}
for each of the choices. This is the best and easiest way i can see.. :)
Just check if the String you are getting from the Intent is not equal to ""
if(!intent.getStringExtra("choiceOne).equals(""))
and add only the Strings that are not empty to your String Array. Then you have to get your random number based on how many Strings there are in your Array, by calling choice.length.
put a check in your onClick method for each choice, only then save the value in intent.putExtra()
if(choiceX.getText().toString() != null && !choiceX.getText().toString().trim().equals("")) {
intent.putExtra("choiceX", choiceX.getText().toString());
}
and then instead of doing Math.random*5, use Math.random*intent.getExtras().size()

String is null while obtaining from another class using getIntent

Right now I am have a activity screen with edittext lines that I am obtaining user input from. When I hit the create event button on the button, the event text should populate into a news feed that I have on another activity.
Here is the portion CreateEvent activity/screen code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_event);
CreateEvent_Button = (Button)findViewById(R.id.create_event_button);
WhatEvent_Text = (EditText)findViewById(R.id.what_event);
WhenEventTime_Text = (EditText)findViewById(R.id.time_event);
WhenEventDate_Text = (EditText)findViewById(R.id.date_event);
WhereEvent_Text = (EditText)findViewById(R.id.where_event);
CreateEvent_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WhatEvent_String = WhatEvent_Text.getText().toString();
WhenEventTime_String = WhenEventTime_Text.getText().toString();
WhenEventDate_String = WhenEventDate_Text.getText().toString();
WhereEvent_String = WhereEvent_Text.getText().toString();
Log.e("What: ", WhatEvent_String);
Log.e("When_Time: ", WhenEventTime_String);
Log.e("When_Date: ", WhenEventDate_String);
Log.e("Where_Event: ", WhereEvent_String);
Intent intent = new Intent(CreateEvent.this,MainActivity.class);
intent.putExtra("WhatEvent_String", WhatEvent_String);
intent.putExtra("WhenEventTime_String", WhenEventTime_String);
intent.putExtra("WhenEventDate_String", WhenEventDate_String);
intent.putExtra("WhereEvent_String", WhereEvent_String);
startActivity(intent);
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
}
});
}
When the create event button is pressed, it creates an event into the MainActivity screen/activity; however, the user input is null. I am not sure why this is happening because I believe I am using the intent methods correctly.
Here is my MainActivity screen.
Here is the getIntent method in my onCreate method in my MainActivity
Intent intent = getIntent();
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
However, when I call my addEvent method:
protected void addEvent() {
// Instantiate a new "row" view.
// final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.list_row, mContainerView, false);
// Set the text in the new row to a random country.
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
//mContainerView.addView(newView, 0);
HitupEvent hitupEvent = new HitupEvent();
hitupEvent.setTitle("Rohit "+ "wants to "+test );
hitupEvent.setThumbnailUrl(roro_photo);
//hitupEvent.setRating(30);
//hitupEvent.setYear(1995);
//hitupEvent.setThumbnailUrl(null);
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
hitupEvent.setGenre(singleAddress);
hitupEventList.add(hitupEvent);
adapter.notifyDataSetChanged();
}
The event input text is null. I am not sure why this is happening.
I tried to resolve it but no luck,
How to send string from one activity to another?
Pass a String from one Activity to another Activity in Android
Any idea as for how to resolve this?!
Thanks!
Don't use Intent to get the String you put through putExtra()
Intent intent = getIntent(); // don't use this
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
Instead Use Bundle, an example snippet
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
EDIT
I noticed just now that you're calling the method main.addEvent() from the wrong place ! Call it in the MainActivity in the onCreate() method.
Remove these lines
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
and in your MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
addEvent(); // call your addEvent() method here
}

Android Intent makes my app crash, why?

so I tried out my app without passing the score variable, and it worked. But If I try to use it, it won't work at all.
main class:
int start = 10;
// start Play Intent
public void onPlay(View view){
Intent playIntent = new Intent(this, Quiz_1.class);
playIntent.putExtra("Score", start);
startActivity(playIntent);
}
and the Quiz_1 class:
public class Quiz_1 extends Activity {
int printScore;
TextView printPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_1);
printPoints = (TextView) findViewById(R.id.q_result);
}
Intent intent = getIntent();
int score = intent.getIntExtra("Score", 0);
String printFin = String.valueOf(score);
public void q_result(View view){
printPoints.setText(printFin);
}
I am sure, I did something wrong when I tried to pass the start value to my other activity. There I wanted to change a textView's text to the previous int start value = 10;
So,
First activity:
int t start = 10;
Second. activity:
int score = start;
printScore(it's a TextView) setText = score
If you want to pass a value to another intent, you can look into the code below.
You can put key value pairs like in intents and you can retrieve these values in the activity you are calling. You can look into :-
Intent returnIntent = new Intent(getApplicationContext, SecondActivity.class);
returnIntent.putExtra("name","abc");
startActivity(returnIntent,11);
And in you other activity result method, you can do
Bundle extras = getIntent().getExtras();
if (extras != null) {
String name = bundle.getString("name");
// and get whatever data you are adding
}
You can look into this.
All Java code must be in a method. Here, the last three lines are not in any method and are therefore not executed.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_1);
printPoints = (TextView) findViewById(R.id.q_result);
} <----- move this closing brace
Intent intent = getIntent();
int score = intent.getIntExtra("Score", 0);
String printFin = String.valueOf(score);
} <----- to here
You need to have these inside a method like onCreate
Intent intent = getIntent();
int score = intent.getIntExtra("Score", 0);
String printFin = String.valueOf(score);
However the crash may still happen so better post the stack trace
Edit:
String printFin; //declare as class member
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_1);
printPoints = (TextView) findViewById(R.id.q_result);
Intent intent = getIntent();
int score = intent.getIntExtra("Score", 0);
printFin = String.valueOf(score);
}
change all your code to
public class Quiz_1 extends Activity {
int printScore;
TextView printPoints;
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_1);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
score = extras.getInt("Score");
}
printPoints = (TextView) findViewById(R.id.q_result);
printPoints.setText(String.valueOf(score));
}
I have gone through this link - http://pastebin.com/BGAkdeCv
I may have found an error
Case 1 : - You are passing the defaultScore value in passScore key and retrieving it in Quiz1.Java
MainActivity.Java ->
startQuiz.putExtra("passScore", defaultScore);
Quiz_1.Java ->
current_score = extras.getInt("passScore");
Case 2 : - You are passing current_score in passNewScore and retrieving it in Quiz2.Java
Quiz_1.Java ->
quiz1.putExtra("passNewScore", current_score);
Quiz2.Java
current_score = extras.getInt("passScore");
getScore = extras.getInt("passNewScore");
Now, the error here is :-
in quiz2.java where you are extracting passScore in current_score because this key value was put in your main_activity, not your quiz1.java from where you are calling quiz2.java.,.
so to retrieve this value in quiz2.java, you have to pass it again in quiz1.java from where you are calling quiz2 intent
To correct it modify your quiz1.java :-
public void on_quiz_1_wrong(View view){ // button clicked the wrong answer
current_score = current_score - 2;
Intent quiz1 = new Intent(this, Quiz_2.class);
startActivity(quiz1);
quiz1.putExtra("passNewScore", current_score);
quiz1.putExtra("passScore", whatever value you want to pass here);
}

Solution to equation won't display? (no errors being reported on my end)

So I managed to take 4 different activities involving 4 variables and wrote them in this kind of format:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step1);
Button c = (Button) this.findViewById(R.id.continue1);
final EditText input = (EditText) findViewById(R.id.enterscore);
input.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String score1 = input.getText().toString();
Double.parseDouble(score1);
{ Intent myintent = (new Intent(step1.this,step2.class));
myintent.putExtra("SCORE1",score1);
startActivity(myintent);
}
On my final activity the one that's suppose to display the solution I have coded the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
}
public void solutionf(View v) {
Bundle extras = getIntent().getExtras();
if(extras!=null){
double score1 = extras.getDouble("SCORE1");
double score2 = extras.getDouble("SCOREF");
double l2 = extras.getDouble("L2");
double l3= extras.getDouble("L3");
double solution= (((score2-score1)/l2)*l3);
String resultString = "Result:" +solution;
TextView resultText= (TextView) findViewById(R.id.solution);
resultText.setText(resultstring);
}
}
}
Why won't the final solution display? I've checked over to make sure everything matches up in terms of the doubles that are set in the activities. Could it be I didn't properly bring the variables over from the previous activities through error on my code?
Any help to getting the solution to show would be appreciated!
Unless a part of your code is missing, solution() is never called.
Add a call to this function in onCreate of your second activity, it should help.

Categories

Resources