I got a problem: the first activity (below) doesn't send intent to second activity.
Here is MainActivity.java
package com.example.quizjavatest;
import android.os.Bundle;
import android.app.Activity;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
List<Question> quesList;
int score=0;
int qid=0;
ImageView quizimg;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DbHelper db=new DbHelper(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1); //question
rda=(RadioButton)findViewById(R.id.radio0); //option A
rdb=(RadioButton)findViewById(R.id.radio1); //option B
rdc=(RadioButton)findViewById(R.id.radio2); //option C
quizimg=(ImageView) findViewById(R.id.ImgQuiz); //img quiz
butNext=(Button)findViewById(R.id.button1); //button next
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<5){
currentQ=quesList.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
quizimg.setImageBitmap(currentQ.getBitmap());
qid++;
}
}
ResultActivity.java
package com.example.quizjavatest;
import android.os.Bundle;
import android.app.Activity;
import android.widget.RatingBar;
import android.widget.TextView;
public class ResultActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_results);
RatingBar bar=(RatingBar)findViewById(R.id.ratingBar1);
bar.setNumStars(5);
bar.setStepSize(0.5f);
//get text view
TextView t=(TextView)findViewById(R.id.textResult);
//get score
Bundle b = getIntent().getExtras();
int score= b.getInt("score");
//display score
bar.setRating(score);
switch (score)
{
case 1:
case 2: t.setText("Oopsie! Better Luck Next Time!");
break;
case 3:
case 4:t.setText("Hmmmm.. Someone's been reading a lot of trivia");
break;
case 5:t.setText("Who are you? A trivia wizard???");
break;
}
}
}
Change your intent:
Intent intent = new Intent(this, ResultActivity.class); //better use `this` instead of global context
intent.putExtras("score", score); //Put your score to your next
startActivity(intent);
finish();
No need to use Bundle unless you're passing Object, Intent's extras they are Bundle already, don't do same twice.
In ResultActivity catch it:
Intent intent = getIntent();
int score = intent.getIntExtra("score");
Hope this will solve your problem.
Related
I have a menu at the beginning of my application which allows the user to choose a specific type of diet, I want to save this as a string to use in another class which finds nearby restaurants,cafes,etc.
For example, if the user chooses the "Vegan" card, then I want to be able to use "Vegan" in other classes, but if it's "Kosher" I want to use the string "kosher" in other classes.
I tried creating a DietChoice class to set/get the diet but that doesn't work because I can't create a HomeMenu object in my MapsActivity class.
How can I make it so that when the user clicks the Vegan card, I can make it so that I can use a string "Vegan" in my MapsActivity class?
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
public class HomeMenu extends AppCompatActivity implements View.OnClickListener {
private CardView veganMenu,halalMenu,vegeterianMenu,kosherMenu;
private DietChoice diet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_menu);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
public void onClick(View v) {
Intent intent = new Intent(this,Home.class)
switch (v.getId()) {
case R.id.vegan_menu:
intent.putExtra("STRING_I_NEED", "vegan");
startActivity(intent);
break;
case R.id.vegetarian_menu:
intent.putExtra("STRING_I_NEED", "vegetarian");
startActivity(intent);
break;
case R.id.halal_menu:
intent.putExtra("STRING_I_NEED", "halal");
startActivity(intent);
break;
case R.id.kosher_menu:
intent.putExtra("STRING_I_NEED", "kosher");
startActivity(intent);
break;
}
Hello just putExtra with intent and extract it later on in your next Activity.No need of any Pojo.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
public class HomeMenu extends AppCompatActivity implements View.OnClickListener {
private CardView veganMenu,halalMenu,vegeterianMenu,kosherMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_menu);
getSupportActionBar().setDisplayShowHomeEnabled(true);
veganMenu = (CardView) findViewById(R.id.vegan_menu);
halalMenu = (CardView) findViewById(R.id.vegetarian_menu);
vegeterianMenu = (CardView) findViewById(R.id.halal_menu);
kosherMenu = (CardView) findViewById(R.id.kosher_menu);
veganMenu.setOnClickListener(this);
halalMenu.setOnClickListener(this);
vegeterianMenu.setOnClickListener(this);
kosherMenu.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = new Intent(this,Home.class)
switch (v.getId()) {
case R.id.vegan_menu:
intent.putExtra("STRING_I_NEED", "vegan");
startActivity(intent);
break;
case R.id.vegetarian_menu:
intent.putExtra("STRING_I_NEED", "vegetarian");
startActivity(intent);
break;
case R.id.halal_menu:
intent.putExtra("STRING_I_NEED", "halal");
startActivity(intent);
break;
case R.id.kosher_menu:
intent.putExtra("STRING_I_NEED", "kosher");
startActivity(intent);
break;
}
}
}
To Retrive the String in Home activity use below Code
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
I am trying to make a "News App" with Android Studio. I have on my main activity a ListView and a floating button. On my second activity I got two TextViews, two EditViews and one Button. What I'd like to do is the following:
First I press on the floating Button from my main Activity. Then the second Activity should pop up and there I write on the two EditText's and then press on the button. After that I should go back to the main activity and there, a new Item should be added to the ListView. The new item should be filled with the text from the second activity's EditTexts.
This is my main activity:
package news;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get subject value from addpost Activity
final String new_value = getIntent().getStringExtra("newSubject");
String [] new_subject = new String []
{new_value};
FloatingActionButton add_post_button = findViewById(R.id.post_btn);
final ListView post_view = findViewById(R.id.news_feed);
//Create Adapter to add the new subject to listview
if (new_subject != null) {
ArrayAdapter newslist_adapter = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
MainActivity.this.startActivity(intent);
}
});
}
}
This is the second activity(addpost_activity):
package news;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class addpost_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addpost_activity);
Button post_button = findViewById(R.id.post_btn);
final EditText subject_text = findViewById(R.id.subject_edit);
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
startActivity(intent);
}
}
});
}
}
My problem is now that the app crashes every time I start it. I also get this message from my logs:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Solved:
Thanks to Munir, the problem was solved.
Here are my activities
MainActivity:
package news;
import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayAdapter newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton add_post_button = findViewById(R.id.post_btn);
//Create Adapter to add the new subject to listview
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final ListView post_view = findViewById(R.id.news_feed);
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String new_value = data.getStringExtra("newSubject");
new_subject.add(new_value);
newslist_adapter = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
}
}
This is my second Activity(addpost_activity):
package news;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class addpost_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addpost_activity);
Button post_button = findViewById(R.id.post_btn);
final EditText subject_text = findViewById(R.id.subject_edit);
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
setResult(Activity.RESULT_OK, intent);
finish();
}
}
});
}
}
For that purpose I suggest using Fragments instead of two Activities. The MainActivity then holds all your data.
See Fragments guide.
From your MainActivity call the addpost_activity using startActivityForResult() method Instead of startActivity();
In your addpost_activity set the data which you want to return back to FirstActivity
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
setResult(Activity.RESULT_OK,intent );
finish();
}
}
});
And in the MainActivity Access the result by overriding onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("newSubject");
//Add this value to your adapter and call notifyDataSetChanged();
}
}
}
use ArrayList insted of String [] if you want to keep old entry in list change your code like below.
Main Activity
declare this variable as global
ArrayAdapter newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();
set Adapter like
newslist_adapter = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
change startActivity to startActivityForResult
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
startActivityForResult(intent,100);
}
});
Override this method in onActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
String result=data.getStringExtra("newSubject");
new_subject.add(result)
//Add this value to your adapter and call newslist_adapter.notifyDataSetChanged();
}
}
And In your addpost_activity set the data which you want to return back
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subject_text.getText() != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("newSubject", subject_text.getText().toString());
setResult(100,intent );
finish();
}
}
});
In MainActivity.java, you should override a function named "onActivityRecsult" this method will be called when you come back from second activity to first activity.
I cannot figure this out. My app will always go to the .Weather class no matter what I click on.
package com.example.matmap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class ResourcesPage extends Activity implements OnClickListener {
LinearLayout display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resources_page);
//display = (LinearLayout) findViewById(R.id.menuSweet);
LinearLayout locate = (LinearLayout) findViewById(R.id.locate);
LinearLayout ndsu = (LinearLayout) findViewById(R.id.ndsu);
LinearLayout weather = (LinearLayout) findViewById(R.id.weather);
LinearLayout contact = (LinearLayout) findViewById(R.id.contact);
locate.setOnClickListener(this);
ndsu.setOnClickListener(this);
weather.setOnClickListener(this);
contact.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.locate:
Intent myIntent = new Intent(ResourcesPage.this, MapView.class);
startActivity(myIntent);
case R.id.ndsu:
Intent myIntent2 = new Intent(getApplicationContext(), TimesTable.class);
startActivity(myIntent2);
case R.id.weather:
Intent myIntent3 = new Intent(getApplicationContext(), Weather.class);
startActivity(myIntent3);
break; }
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.resources_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menuHome){
Intent i = new Intent(getApplicationContext(), ResourcesPage.class);
startActivity(i);
}
return true;
}
}
Trying to get to the mapview class
package com.example.matmap;
import android.app.Activity;
import android.os.Bundle;
public class MapView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapview);
}
}
I don't know what the problem is since I've done these same things before and it's worked perfectly...
You should add break in each case statement
switch(v.getId()){
case R.id.locate:
Intent myIntent = new Intent(ResourcesPage.this, MapView.class);
startActivity(myIntent);
break;
case R.id.ndsu:
Intent myIntent2 = new Intent(getApplicationContext(), TimesTable.class);
startActivity(myIntent2);
break;
You're missing breaks:
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.locate:
Intent myIntent = new Intent(ResourcesPage.this, MapView.class);
startActivity(myIntent);
break;
case R.id.ndsu:
Intent myIntent2 = new Intent(getApplicationContext(), TimesTable.class);
startActivity(myIntent2);
break;
case R.id.weather:
Intent myIntent3 = new Intent(getApplicationContext(), Weather.class);
startActivity(myIntent3);
break;
}
}
I have an application that displays a splash screen then a 'Showonce' screen, I have used app prefs and a boolean "user_accept" to decide wether the screen gets displayed or not, trouble no matter if the boolean = true it still shows the page, please see my code for the pages, any help greatly appreciated :).
package com.overclockerz.webtest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Window;
import android.widget.Toast;
public class SplashScreen extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_layout);
final SharedPreferences settings = getSharedPreferences("APP_PREFS",
MODE_PRIVATE);
final boolean hasAgreed = settings.getBoolean("user_accepted", false);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (hasAgreed == false){
Intent intent = new Intent(SplashScreen.this, ShowOnce.class);
SplashScreen.this.startActivity(intent);
Toast.makeText(getApplicationContext(), "DEBUG: USER HAS NOT ACCEPTED",Toast.LENGTH_LONG).show();
}else if (hasAgreed == true){
Toast.makeText(getApplicationContext(), "DEBUG: USER HAS ACCEPTED",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
finish();
}
}, 2000); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
}
package com.overclockerz.webtest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
public class ShowOnce extends Activity implements OnClickListener {
Button show_options_dialog, accept_button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.show_once);
show_options_dialog = (Button) findViewById(R.id.show_options_dialog);
accept_button = (Button) findViewById(R.id.accept_button);
show_options_dialog.setOnClickListener(this);
accept_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == show_options_dialog){
Intent intent = new Intent(getApplicationContext(), SettingScreen.class);
startActivity(intent);
}
else if (v == accept_button){
SharedPreferences settings = getSharedPreferences("APP_PREFS",
MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean("user_accept", true);
Toast.makeText(getApplicationContext(), "DEBUG: USER CLICKED ACCEPT", Toast.LENGTH_LONG).show();
prefEditor.commit();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
}
you are saving user_accept and checking for user_accepted
Please use public static final String to avoid such problems:
public static final String USER_ACCEPTED = "accepted";
.........
prefEditor.putBoolean(USER_ACCEPTED , true);
.........
settings.getBoolean(USER_ACCEPTED , false);
So using suggestions from the last question I asked, I figured out how to call BarCodeScanner, and return the value to a field. so now, I have a toast that says "successful scan" and then I want to pass the result to a new activity. when I comment out my intent, everything works (minus the passing of data/switching of screen, obviously) but when I run my project as is, it FC's... no errors reported by eclipse in code or XML. Any insights?
package com.mhe.test.scan;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button myScanButton = (Button) findViewById(R.id.myScanButton);
totalbox = (EditText) findViewById(R.id.tBox);
myScanButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
});
}
private EditText totalbox;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
final String contents = intent.getStringExtra("SCAN_RESULT");
if ( totalbox != null )
totalbox.setText(contents);
Context context = getApplicationContext();
CharSequence text = "Successful Scan";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent i = new Intent(main.this, Result.class);
i.putExtra("SNARP", "SCAN_RESULT");
startActivityForResult(i, 0);
} else if (resultCode == RESULT_CANCELED) {
if ( totalbox != null )
totalbox.setText("bummer");
}
}
}
}
And then to handle the data being passed, in the new activity:
package com.mhe.test.scan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Result extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent i = getIntent();
Bundle b = i.getExtras();
String foosh = b.getString("SNARP");
EditText box1 = (EditText) findViewById(R.id.tBox1);
box1.setText(foosh);
Try sending a Bundle object when calling the new intent.
Intent i = new Intent(main.this, Result.class);
Bundle b = new Bundle();
b.putString("SNARP", "SCAN_RESULT")
i.putExtras(b);
Try getting string in the child Activity this way.
public class Result extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Intent i = getIntent();
String foosh = i.getStringExtra("SNARP");