Send info from class to another class getIntent - java

I have been trying to learn java so I can program for android. I have made an app that has 2 classes, Match and MatchResult. In Match you can push a button and it will add one to a counter. At the bottom of the page i have a button that will bring you to the next class and display the counter in a textview. Im trying to send the info trough a getIntent but its something wrong that I cant find. Here is the code:
Match:
public class Match extends Activity implements OnClickListener {
public final static String EXTRA_MESSAGE_HOME = "com.epstudios.basketballmanager_v1.MATCHRESULT";
public final static String EXTRA_MESSAGE_AWAY = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(intent);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
away.setText(String.valueOf(awayresult));
}
public void resultcounter() {
// TODO Auto-generated method stub
home = (TextView) findViewById(R.id.homeresult);
away = (TextView) findViewById(R.id.awayresult);
}
}

Hmm, why not try scrapping your sendInfo() function and adding this line under your result intent instead:
result.putExtra(Match.EXTRA_MESSAGE_AWAY, awayCount);
It should work now.

It seems that code having 2 ways to call MatchResult activity hence try to use :
hasExtra() method to check whether that extra is passed with the Intent.

The constructor of Intent should have the context of your class. But in your case this refers View.OnClickListener()! So, just change it as in below.
...
case R.id.matchResult:
Intent result = new Intent(Match.this, MatchResult.class); // Like here
result.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
result.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(result);
break;
}
...
Edit: You have never used sendInfo method. As far as I get, you could remove your sendInfo method and put those codes into switch case.

I would be create a static variable shared between activities.

Related

Java getIntent problems

I am new to java programming and im currently trying to pass over info to another class and display it as a TextView. I have two classes: Match and MatchResult. In Match you can push a button and a int will +1. I also have a button on the site which can make you go to the next class. In the next class i want do make the score get displayed in a TextView. But something isn't working and I don't understand why. Here is my code hope someone can help me:
Match.java:
public class Match extends Activity implements OnClickListener{
public final static String EXTRA_MESSAGE = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, Match.class);
intent.putExtra(EXTRA_MESSAGE, awaycount);
Intent homeintent = new Intent(this, Match.class);
homeintent.putExtra(EXTRA_MESSAGE, homecount);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount ++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount ++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult.java:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
Intent awayintent = getIntent();
String awayresult = awayintent.getStringExtra(Match.EXTRA_MESSAGE);
Intent homeintent = getIntent();
String homeresult = homeintent.getStringExtra(Match.EXTRA_MESSAGE);
home.setText(homeresult);
Log.d("Petter", homeresult);
}
The Log dosen't work
You're adding as 'Integer' putExtra("KEY", int) and retrieving as 'String' (getStringExtra)
Change sendInfo with:
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivituy(intent);
}
Change MatchResult with:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
}
You are starting the second Activity using this:
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
result.putExtra(EXTRA_MESSAGE_HOME, awaycount);//Use this
result.putExtra(EXTRA_MESSAGE_AWAY, homecount);//Use this
startActivity(result);
break;
put an Intent here. Don't use 2 intents. Just put the two variables using 2 keys in same intent.
In second activity do this:
Intent intent = getIntent();
String awayresult = String.valueOf(intent.getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1));
String homeresult = String.valueOf(intent.getIntExtra(Match.EXTRA_MESSAGE_HOME, -1));
Match:
public class Match extends Activity implements OnClickListener {
public final static String EXTRA_MESSAGE_HOME = "com.epstudios.basketballmanager_v1.MATCHRESULT";
public final static String EXTRA_MESSAGE_AWAY = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(intent);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
away.setText(String.valueOf(awayresult));
}
public void resultcounter() {
// TODO Auto-generated method stub
home = (TextView) findViewById(R.id.homeresult);
away = (TextView) findViewById(R.id.awayresult);
}
}

How to set the android app theme in java,

I want to allow the user change the theme from the entire app by clicking a button,
So I want to know if there is a way to change the app theme within java code.
You can use the setTheme() method on a Context.
Be sure to pay attention to the note in the documentation- you need to call setTheme() before you instantiate any Views.
If you change themes while your application is open, you will need to recreate your Activity for the changes to show.
public class ThemeSwitcher extends Activity implements OnClickListener {
private boolean isThemeSwitch = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (isDefault() == false) {// Default theme defined in Style file.
setTheme(android.R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.theme_switcher);
findViewById(R.id.switchTheme).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.switchTheme) {
switchTheme();
isThemeSwitch = true;
finish();
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isThemeSwitch) {
Intent intent = new Intent(this, ThemeSwitcher.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
private SharedPreferences getPreference() {
return getSharedPreferences("theme", 0);
}
private void switchTheme() {
if (isDefault()) {
getPreference().edit().putBoolean("theme", false).commit();
}
else {
getPreference().edit().putBoolean("theme", true).commit();
}
}
private boolean isDefault() {
boolean isDef = true;
isDef = getPreference().getBoolean("theme", false);
return isDef;
}
}

Error when I try sending strings over intent

I have an app in which many activities open another in which some things are set after the buttons that opened it(images, tags, etc.).After this activity is closed I want to be returned a string vith value "1" which will be converted to an int and used to set a score.
In activity that returns i have this:
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vie);
img = (ImageView) findViewById(R.id.img);
et = (EditText) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btnCheck);
txt = (TextView) findViewById(R.id.txt);
win_sound = MediaPlayer.create(Vie.this, R.raw.win);
wrong_sound= MediaPlayer.create(Vie.this, R.raw.wrong);
i = getIntent();
Bitmap back = i.getParcelableExtra("back");
Drawable b = new BitmapDrawable(getResources(), back);
img.setImageDrawable(b);
String tag = i.getStringExtra("tag");
Object tag2 = (Object) tag;
img.setTag(tag2);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean mb = check(et, img);
if (mb) {
// Sunet toast thread
txt.setText(title(img));
win_sound.start();
i.putExtra("score", "1");
setResult(RESULT_OK, i);
Thread t = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(win_sound.getDuration());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
finish();
}
}
};
t.start();
}
if (!mb) {
// sunet toast thread
wrong_sound.start();
Toast t = Toast.makeText(getApplicationContext(),"Wrong answer! Please check if you have spelled corectly the name of the team!",Toast.LENGTH_LONG);
t.show();
}
}
And the OnActivityResult methode:
int a = 0
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (data.getExtras().containsKey("score")) {
a +=Integer.valueOf(data.getStringExtra("score"));
}
}
and a textView is set to show a:
txtScore.setText(a);
But this gives me an error, this is my LogCat:
06-29 15:28:25.312: E/AndroidRuntime(981): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
06-29 15:28:25.312: E/AndroidRuntime(981): at android.content.res.Resources.getText(Resources.java:230)
06-29 15:28:25.312: E/AndroidRuntime(981): at android.widget.TextView.setText(TextView.java:3769)
06-29 15:28:25.312: E/AndroidRuntime(981): at com.RandDdev.uclquiz.Teams.onCreate(Teams.java:61)
Could you help me?
txtScore.setText(a);
a is a Integer. So Android is looking for a String inside R with that id.
change with
txtScore.setText(String.valueOf(a));
you are using setText(int), instead of setText(Charsequence)
You should use the below
txtScore.setText(String.valueOf(a));
public final void setText (int resid)
http://developer.android.com/reference/android/widget/TextView.html
So it will look for a resource id which is an int value. This does not exist. Hence you get Resource not found exception
Please try txtScore.setText(""+a);
You cannot set an int directly to TextView

sending Message with bundle data to a thread in another class in an inner class and then back to the UI handler?

I'm trying to send data to my Thread called ToD1 which is in an inner class of my Threads class then I need to do some work to it then need it to be set back to the UI thread handler my qestion is how would I call the Handlers to send the Message data? I know about AsyncTask and will try using it later the purpose of this app is for me to learn and understand the concepts of Handlers, HandlerThread, and AsyncTask so I can use them in my programing.
Here is my code for MainActivity:
public class MainActivity extends Activity implements OnClickListener {
TextView display1;
TextView display2;
EditText cl;
Button enter;
Button tod1;
Button tod2;
Bundle d = new Bundle();
static Handler mHandler;
Message msg;
Object task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tod1 = (Button) findViewById(R.id.display1);
tod2 = (Button) findViewById(R.id.display2);
enter = (Button) findViewById(R.id.Enter);
display1 = (TextView) findViewById(R.id.Display1);
display2 = (TextView) findViewById(R.id.Display2);
cl = (EditText) findViewById(R.id.CL);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Enter:
Bundle in = new Bundle();
String input = cl.getText().toString();
d.putString("in", input);
msg.setData(d);
// eclipes ask to resovle d1 varible type?
d1.sendMessage(msg);
notifyAll();
break;
case R.id.display1:
break;
case R.id.display2:
break;
}
}
}
Here is my Thread class:
public class Threads {
public static class ToD1 {
Thread display1 = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
Message msg = new Message();
Bundle b = new Bundle();
Looper.prepare();
Handler d1 = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
String output;
b.putString("key1", "out:" + String.valueOf(output));
msg.setData(b);
// Send msg to UI thread handler
// eclipes asked solve mHandler to varible type
mHandler.sendMessage(msg);
}
};
}
}

How to store a list of objects temporarily

I have a list of objects which need to persist should the user minimize the app. Is there any way to do this without using SharedPreferences or an SQLite database (seems like overkill for a single list)?
Have the object implement Parclable or Serializable
Then you can just put it in the Bundle
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(key, value);
}
And get it back in onCreate(),onRestoreInstanceState() depending on your needs.
Using a tutorial I found here, I implemented it using SharedPreferences, the main difference was that instead of using a key ,"MEM1", I use an Index. When my activity loads, I can check the size of the index using this code,
for(int x =0; ;x++) {
index = x;
if(sharedPreferences.contains(String.valueOf(x))){
temp = gson.fromJson(sharedPreferences.getString(String.valueOf(x), null), PointOfInterest.class);
pointList.add(temp);
}
else {
break;
}
}
Example:
public class AndroidSharedPreferencesEditor extends Activity {
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
editText1 = (EditText)findViewById(R.id.edittext1);
editText2 = (EditText)findViewById(R.id.edittext2);
buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
LoadPreferences();
}
};
Button.OnClickListener buttonSaveMem2OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM2", editText2.getText().toString());
LoadPreferences();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}

Categories

Resources