[Q] how to change the starting activity - Java for Android App Development

Hi there,
I would like some advice on what I should look for if I want to implement the following basic scenario:
the app starts with an activity (call it Activity_1) which contains a button
on clicking the button, takes me to a different activity (call it Activity_2)
next time i start the app, it takes me directly to Activity_2
and Activity_1 won't be seen again
So how can I change the startup activity?

What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}

thanks for the answer. i want to consider that the app is closed, like after restarting the device. i don't want it to be able to start with Activity_1 unless, let's say, i re-install the app.
i also had an idea about having a 3rd activity as the main one defined in the manifest, which on create changes to one of the other activities. but i don't know how that would be implemented. would it work?
octobclrnts said:
What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}
Click to expand...
Click to collapse

Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}

oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
octobclrnts said:
Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}
Click to expand...
Click to collapse

K-RAD said:
oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
Click to expand...
Click to collapse
That's absolutely right. You can store Strings and primitive values indexed by String keys.

octobclrnts said:
That's absolutely right. You can store Strings and primitive values indexed by String keys.
Click to expand...
Click to collapse
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Code:
package com.example.onetimeactivity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
}
else
{
//do something else every other time
startActivity(new Intent(this,SecondActivity.class));
}
}
}
Code:
package com.example.onetimeactivity;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class SecondActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
doLogon();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
edit.apply();
}
}

i managed to resolve it by adding android:noHistory="true" to the manifest. however, now i really can't see the first activity, not even if i rebuild the code ))
K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse

K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse
Thanks for catching my mistake. You're right that it does need an apply (or before API level 9, commit()) call.
If you don't want to see the activity MainActivity anymore, then you have to make some changes to your structure. You should make an Activity that will be the one that always shows when the user opens the app. That activity is the one who should check the SharedPreferences for your entry. If the entry does not exist, it should call the one-time-activity. Then the one-time-activity should do it's work and save the entry and call finish() to go back to the main activity (the one you usually want to be shown). This way the activity stack will be correct for the back key functionality.

what it sounds like you want is something like a splash/logon screen
like previously said use sharedprefs.
in the splash/logon call the sharedpref and make the default false (I use booleans, you can use ints or strings):
so it would be like this
Code:
SharedPreferences settings;
SharedPreferences.Editor editor;
boolean splash;
[user=439709]@override[/user]
public void onCreate() {
settings = getSharedPreferences("settings", 0);
splash = settings.getboolean("splash", false);
editor = settings.edit();
if(splash == false){
setContentView(//the view you are using);
//do everything else you need to do
button.setonclicklistener(new OnClickListener(){
editor.putboolean("splash", true);
editor.commit();
finish();
});
}else{
//open up your second activity
finish();
}
if its a login screen, when the user clicks logout you would do the editor and change "splash" to false.

Related

[Q] Calling new activity on a button click

Hey guys,
I'm new to android development and have been working through the Android Development guides on Google's site. I'm using what I've learned so far to create a simple app that enables the user to press a button and enter a second screen. I'm incredibly confused at this point and any help would be much appreciated. I have a class Project001.java with a button and would like class Project002.java to be launched when Button 1 is pressed. I have main.xml providing the layout for Project001 and main2.xml providing the layout for Project002. Here is what I have so far in Project001 (which I know is wrong).
package com.smith.Project001;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.smith.Project002;
public abstract class Project001 extends Activity implements OnClickListener {
Button button = (Button)findViewById(R.id.Button01);
abstract void setOnClickListener(View v);
// Implement the OnClickListener callback
public void onClick(View v) {
//do something when the button is clicked
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myIntent = new Intent();
myIntent.setClassName("com.smith.Project001", "com.smith.Project002");
startActivity(myIntent);
}}
I've been searching through the Google archives and can't seem to put all the pieces together. Thanks in advance for your help!
Try the tutorial here. The second one, called menus and intents, I think, shows starting one activity from another.
http://www.vogella.de/articles/Android/article.html
________________________________
Unrevoked forever
SkyRaider Sense 3.5
Radio 2.15.00.09.01
Try something like this in your main activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startNewActivityBtn = (Button) findViewById(R.id.newactivitybtn);
startNewActivityBtn.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
// put your intent and start activity here; should work fine
}
});
}
Click to expand...
Click to collapse
You really don't need abstract or implements. And there is no reason to import "Project2" into "Project1". Project2 should handle all that goes on in the new window. If you need to pass data to Project2 you can do that too
Thanks for the help so far guys,
I'm still having troubles with this code (new to development and very much appreciative of your help). I've done a lot of reading and I don't think I need to use intents because I have to data to pass from Project001 to Project002. All I need is to click the button and to move from Project001 to Project 002. My problem right now is that as soon as I run the app in the emulator, I get a force close. I've been trying to find a solution but haven't been able to. I've tried to implement the method you gave me and took the entire tutorial two posts up. Here is the new code. Again, any help is much appreciated.
package com.smith.Project001;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Project001 extends Activity implements OnClickListener {
Button button = (Button)findViewById(R.id.Button01);
void setOnClickListener(View v) {
}
// Implement the OnClickListener callback
public void onClick(View v) {
setContentView(R.layout.main2);
//do something when the button is clicked
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startNewActivityBtn = (Button) findViewById(R.id.Button01);
startNewActivityBtn.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
// put your intent and start activity here; should work fine
}
});
}
Always look into logcat, it's REALLY helpful. Anyway, here's a couple of things I see wrong;
1) I'm not sure why you're having two layouts for one activity, just put them into one layout file
2) setContentView() needs to be in onCreate()
3) You can't call findViewById() before the layout file has been processed by setContentView()
Try this example. I think it does exactly what you want. It has two xml files (screen 1 and screen 2). When you press the button on the first screen, it displays the second screen.
http://www.warriorpoint.com/blog/2009/05/24/android-how-to-switch-between-activities/
________________________________
Unrevoked forever
SkyRaider Sense 3.5
Radio 2.15.00.09.01
Yep, that should work.
Please note that on the second Activity, a "Previous" or "Return" type button is not required; the hard Back Key on Android phones does the exact same thing as the code.

[Q] Playing new sound on each click

I've run into a little trouble and I'm wondering if someone can help me out.
I have a button with several sound effects that go with it. I'm wanting to play a different sound each time the button is pressed, but I just can't get things to work out. Can someone show me the way? Any help would be huge. This is the only thing keeping me from finishing. Here's a little code:
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.finn_whatthejugisthat);
mSoundManager.addSound(2, R.raw.finn_wordtoyourmother);
Button SoundButton = (Button)findViewById(R.id.Button1);
SoundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(1);
mSoundManager.playSound(2);
}
});
}
}
If you want to play a different sound with each click, then you'll have to keep a global counter variable or global string that you change to the next audio file name with each click of the button--sort of a circular buffer. The code you have there tries to play both sounds on the same click and likely mixes them together at the same time if "playSound()" is asynchronous, but I don't know what the SoundManager class is so I have no idea.
Gene Poole said:
If you want to play a different sound with each click, then you'll have to keep a global counter variable or global string that you change to the next audio file name with each click of the button--sort of a circular buffer. The code you have there tries to play both sounds on the same click and likely mixes them together at the same time if "playSound()" is asynchronous, but I don't know what the SoundManager class is so I have no idea.
Click to expand...
Click to collapse
Okay, so I understand what you mean, but I don't know how to say that in Java. Could you give a short example? As for SoundManager, it's really a useless class I have that I was using to play my media. You can take a look here:
Code:
package com.andrew.finnandjake;
import java.util.HashMap;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundManager {
private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;
public SoundManager()
{
}
public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put(1, mSoundPool.load(mContext, SoundID, 1));
}
public void playSound(int index) {
int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}
public void playLoopedSound(int index) {
int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}
}
OK, I see it uses SoundPool. First, change your definition for addSound to:
Code:
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put([COLOR="Red"]Index[/COLOR], mSoundPool.load(mContext, SoundID, 1));
}
Here's code that should work to do a different tone each push and loop back to the beginning.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonSound extends Activity{
private SoundManager mSoundManager;
private int next=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager=new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(0,R.raw.freeze);
mSoundManager.addSound(1,R.raw.ascend);
mSoundManager.addSound(2,R.raw.bubble);
mSoundManager.addSound(3,R.raw.chiff);
Button SoundButton=(Button)findViewById(R.id.button1);
SoundButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
mSoundManager.playSound(next);
next++;
if(next>3)
next=0;
}
});
}
}
Gene Poole said:
OK, I see it uses SoundPool. First, change your definition for addSound to:
Code:
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put([COLOR="Red"]Index[/COLOR], mSoundPool.load(mContext, SoundID, 1));
}
Here's code that should work to do a different tone each push and loop back to the beginning.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonSound extends Activity{
private SoundManager mSoundManager;
private int next=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager=new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(0,R.raw.freeze);
mSoundManager.addSound(1,R.raw.ascend);
mSoundManager.addSound(2,R.raw.bubble);
mSoundManager.addSound(3,R.raw.chiff);
Button SoundButton=(Button)findViewById(R.id.button1);
SoundButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
mSoundManager.playSound(next);
next++;
if(next>3)
next=0;
}
});
}
}
Click to expand...
Click to collapse
Mkay, so I adjusted my code according to the example and everything came back error free; however, when I run the app and click the button, nothing happens. No sound, but no force close either.
I ran the Debugger and it's telling me that the SoundPool sample is not ready. "Sample 1 not READY", "Sample 2 not READY", etc.
I don't know. I assume you used different names for your sound files. I just grabbed those out of the "notifications" directory of my phone.
Gene Poole said:
I don't know. I assume you used different names for your sound files. I just grabbed those out of the "notifications" directory of my phone.
Click to expand...
Click to collapse
Alright, that's cool. Thanks a lot for all of the help. I owe you one.

Error opening trace file: No such file or directory (2)

Hello,
I did a search on this forum and did not find a solution. This is my first time using the forum by the way. Anyways, I am developing my first application with one main activity that has two buttons each trying to open another activity.
When I try to run the app in Eclipse, I get the following error:
Error opening trace file: No such file or directory (2)
Any direction on how I can solve this would be greatly appreciated.
Absolutely! Here it is:
Code:
package com.mcrsports.mcr;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----LATEST NEWS BUTTON-----
Button newsButton = (Button) findViewById(R.id.latestNewsButton);
newsButton.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, LatestNewsActivity.class));
}
});
//-----PARK LOCATIONS BUTTON-----
Button parksButton = (Button) findViewById(R.id.parkLocationsButton);
parksButton.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ParkLocationsActivity.class));
}
});
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
For me it happens as well and I have never had any problems.
However, here are some solutions: http://stackoverflow.com/questions/11446049/error-opening-trace-file-no-such-file-or-directory-2
Attached is my manifest file. Since I am new and have less than 10 posts, I could not successfully cut/paste within
Code:
block, so I pasted it into Notepad.
Thanks.
bueller?.......... bueller?..........bueller?

[Q] Open another screen on button click

Hello, I'm extremely new to both android application developing, and this forum.
I am trying to open another screen ( activity ) when a button ( readyButton ) on the splash screen is pressed. I've tried at least ten different times with different tutorials to no avail, this is my current code which didn't work, and instead forces the app to crash.
Code:
public class MainActivity extends Activity {
// Called when the activity is first created.
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
OnClickListener listener = new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent("SecondActivity");
startActivity(intent);
}
};
Button btn = (Button) findViewById(R.id.readybutton);
btn.setOnClickListener(listener);
}
}
Please help.
The button's name is 'readybutton'
the second activity name is 'SecondActivity'
also, where am I supposed to put this code into the java class? Here is how it is currently set up:
Code:
package com.unchat;
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.widget.Button;
import android.view.View.OnClickListener;
// Default Items
public class FirstActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
/** New button code start */
public class MainActivity extends Activity {
// Called when the activity is first created.
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
OnClickListener listener = new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent("SecondActivity");
startActivity(intent);
}
};
Button btn = (Button) findViewById(R.id.readybutton);
btn.setOnClickListener(listener);
}
}
/** new button code end */
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
// End of Default Items
incorrectly announces intent
Try like this.
Code:
Intent intent = new Intent(this, SecondActivity.class) ;
startActivity(intent);
and check whether your Listener
1. you need to use the full name of your activity, including the package name.
2. you need to declare the activity in your AndroidManifest.xml file before calling it.
rhmsoft said:
2. you need to declare the activity in your AndroidManifest.xml file before calling it.
Click to expand...
Click to collapse
Unless he want's to run an activity that's not his, like opening the contact list, but I think you're right in assuming he's looking to launch a second one of his own activities.
bornander said:
Unless he want's to run an activity that's not his, like opening the contact list, but I think you're right in assuming he's looking to launch a second one of his own activities.
Click to expand...
Click to collapse
I thought you had to declare all your activities in the manifest?
Log
Post the error log please

App crashes when when calling a method

Hello,
So I am new to Java programming and I want to develop a small and simple app for plant identification. But the app crashes when I call a function wich set the text of a TextView. It happens in the OnCreate when I switch to a second activity. I tried to call the method with only comments in it. It also works when I create a new instance of the MainActivity class. It crashes when I try to set the text of a TextView from the MainActivity layout. It is probably a simple and basic problem, but I've been searching for my error for hours now and I still can't get it. I want to understand what's wrong and move on the the next step
I use the layout of MainActivity in Morphe activity.
Code:
package com.gobtron.cleidfougeres;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Morphe extends MainActivity {
TextView MorphTextTop;
TextView LongFrondeTextTop;
TextView FormeLimbeTextTop;
TextView DisposFrondeTextTop;
TextView DescTextTop;
TextView EspeceTextTop;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopText topText = new TopText();
topText.SetText();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_morphe, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code for the method in TopText method (located in TopText.java)
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
gobtron said:
Hello,
So I am new to Java programming and I want to develop a small and simple app for plant identification. But the app crashes when I call a function wich set the text of a TextView. It happens in the OnCreate when I switch to a second activity. I tried to call the method with only comments in it. It also works when I create a new instance of the MainActivity class. It crashes when I try to set the text of a TextView from the MainActivity layout. It is probably a simple and basic problem, but I've been searching for my error for hours now and I still can't get it. I want to understand what's wrong and move on the the next step
I use the layout of MainActivity in Morphe activity.
Code:
package com.gobtron.cleidfougeres;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Morphe extends MainActivity {
TextView MorphTextTop;
TextView LongFrondeTextTop;
TextView FormeLimbeTextTop;
TextView DisposFrondeTextTop;
TextView DescTextTop;
TextView EspeceTextTop;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopText topText = new TopText();
topText.SetText();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_morphe, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code for the method in TopText method (located in TopText.java)
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
Click to expand...
Click to collapse
Though you haven't posted a stack trace but I'm pretty sure a NullPointerException is being thrown in your code and this is because
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
Is creating a new instance of Activity class MainActivity in which the field "MorphTextTop" is not initialized.......
All the fields in your main activity must be initialized in the onCreate method of the Activity after you have called " setContentView(R.layout.activity_main);"
The initialization would look something like
Code:
MorphTextTop = (TextView) findViewById(R.id."THIS_VIEWS_ID");
put your activity_main.xml here if you then I could give you the complete code.
What does your log say after the app crashes? And where's your actual MainActivity class?
Ok I finally found out the problem. Turns out that I was creating an instance of the TextView before setting the ContentView. Yay!

Categories

Resources