Android Intent makes my app crash, why? - java

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);
}

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.

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 - Passing more variebles via intent makes app crash

So, here is the code from the main activity(the main screen,) if you click on play a random activity( a quiz question) will show up. The problem is that, i am trying to pass an integer, default score to question #1, where the score will be 5(it's the default).
if the user clicks on the wrong button, it will navigate the user to Question #2, and for Question #2, the score will be minus2, less than 2.
int defaultScore = 51;
// start Play Intent
public void onPlay(View view){
Random r = new Random();
int XML_random = r.nextInt(5)+1; // 5 different Quiz XML files
Intent startQuiz = new Intent();
switch(XML_random){
case 1:
startQuiz.setClass(view.getContext(), Quiz_1.class);
break;
case 2:
startQuiz.setClass(view.getContext(), Quiz_2.class);
break;
case 3:
startQuiz.setClass(view.getContext(), Quiz_3.class);
break;
case 4:
startQuiz.setClass(view.getContext(), Quiz_4.class);
break;
case 5:
startQuiz.setClass(view.getContext(), Quiz_5.class);
break;
} // end of the Random switch
startQuiz.putExtra("passScore", defaultScore);
startActivity(startQuiz);
}
So, next if a random activity is chosen, then it's score will be 5, because for the first question, I want the users to start with 5 as a start. So, here is an activty(Question #1) and if the user clicks on the wrong button then Question #2 will show up. And for this activity, the score will be minus 2. Because the user chose the wrong answer.
Question 1 - user clicks on the wrong button:
public class Quiz_1 extends Activity {
TextView textviewScore;
int current_score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_1);
textviewScore = (TextView) findViewById(R.id.q_result); // declaring the TextView
Bundle extras = getIntent().getExtras();
if (extras != null)
{
current_score = extras.getInt("passScore");
}
textviewScore.setText(String.valueOf(current_score));
} // end of onCreate
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);
}
And here is Question #2, and for this activity i want the score to be minus 2.
public class Quiz_2 extends Activity {
TextView textviewScore;
int current_score = 0;
int getScore=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_2);
textviewScore = (TextView) findViewById(R.id.q_result); // declaring the TextView
Bundle extras = getIntent().getExtras();
if (extras != null)
{
current_score = extras.getInt("passScore");
getScore = extras.getInt("passNewScore");
}
current_score = current_score - getScore;
textviewScore.setText(String.valueOf(current_score));
} // end of onCreate
you must first put extra to your intent then start it.
quiz1.putExtra("passNewScore", current_score);
startActivity(quiz1);
You are not passing the value for key "passScore" in quiz1 and calling quiz2, so how can you expect to retrieve the value on "passScore" in quiz2 ?
Pass the value for key "passScore" in quiz1.java in this method on_quiz_1_wrong(View view)

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.

AppWidget with SharedPreferences has to update twice

I'm building a Widget which displays a textview which is editable as a edittext in a configuration class. And I just implemented sharedpreferences, so when the user would edit the widget for the second or third time etc. the already inputted text would appear in the edittext field in the configuration class.
And it works I guess. Well, before I implemented the sharedpreferences, the widget would update just fine after configuration. But now, I edit the text, press apply, but the widget doesn't update, I then edit the widget again and the widget updates with the text I applied to it the time before. So i guess you can say, that it's one update delayed. I hope I'm being clear, it's a little hard to explain.
So what am I doing wrong, I can not get it to work, any help would be very much appreciated.
Code:
public class WidgetConfig extends Activity implements OnClickListener {
AppWidgetManager awm;
int awID;
Context c;
EditText info;
Button b;
String note;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
c = WidgetConfig.this;
info = (EditText)findViewById(R.id.etwidgetconfig);
b = (Button)findViewById(R.id.bwidgetconfig);
loadPrefs();
b.setOnClickListener(this);
//Getting Info about the widget that launched this activity
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null){
awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID );
}
awm = AppWidgetManager.getInstance(c);
}
private void loadPrefs(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
note = sp.getString("NOTE", "DEFAULT");
info.setText(note);
}
private void savePrefs(String key, String value){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value); // value to store
editor.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("NOTE", info.getText().toString());
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.tvConfigInput, note);
ComponentName thisWidget = new ComponentName(this, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
Intent in = new Intent(c, WidgetConfig.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.B_EditAgain, pi);
awm.updateAppWidget(awID, views);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK, result);
finish();
}
}
You're not actually updating the TextView with the value of the EditText field. Your pseudocode currently looks like this:
String note;
onCreate(){
note = getSharedPref(NOTE);
}
onClick(){
putSharedPref(info.getText());
views.setText(note);
}
This ignores the value in your EditText until the NEXT time that you call onCreate, which you observed.
You should update the views with the text from the EditText:
onClick(){
putSharedPref(info.getText());
views.setText(info.getText());
}

Categories

Resources