Class.forName() keeps showing error: java.lang.NullPointerException - java

I want to create a variable to contain an Activity.class so that I can dynamically change the Activity to be called with intent. I want the startBtn to start the intent to the last level played Activity which I will store in json format internally in the device. However, I keep showing up error when I try to use the forName() function to call the Activity class.
Main Activity.class
public class MainActivity extends Activity {
Button startBtn, chooseLevelBtn;
Class classVariable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button) findViewById(R.id.startBtn);
chooseLevelBtn = (Button) findViewById(R.id.chooseLevelBtn);
try {
/*
* Set class Variable so that I can dynamically change the Activity
* to be called with intent.
* Testing the variable with Level001Activity, but app keep crashing
* when startBtn is pressed with stack error I post below
*/
classVariable = Class.forName("com.ed.pieces.Level001Activity");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
classVariable);
startActivity(i);
}
});
}
}
Error Stack
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Class.getName()' on a null object reference
at android.content.ComponentName.(ComponentName.java:129)
at android.content.Intent.(Intent.java:4449)
at com.example.ed.pieces.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
P.S I will store the last level played information in json format as a string which is such as "com.ed.pieces.Level001Activity", and when the user start the app, the class classVariable should contain the Activity class of the last played level.
All suggestions are greatly welcomed. Thank you in advance.

Your exception is coming from your onClick() method and its attempt to create an Intent, not from your forName() call. That is because your forName() call is failing for some reason.
Moreover, you do not need forName(). Replace:
try {
/*
* Set class Variable so that I can dynamically change the Activity
* to be called with intent.
* Testing the variable with Level001Activity, but app keep crashing
* when startBtn is pressed with stack error I post below
*/
classVariable = Class.forName("com.ed.pieces.Level001Activity");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
with:
classVariable = Level001Activity.class;
and add the appropriate import to pull in Level001Activity.

Related

How to call TextToSpeech activity from another activity?

I have an activity (MainActivity) that implements TextToSpeech and works perfectly. When a button's onClick is called, it speaks whatever is typed in EditText.
MainActivity:
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{
private TextToSpeech engine;
private EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.text);
engine = new TextToSpeech(this, this);
Intent i=getIntent();
Bundle b=i.getExtras();
word=b.getString("word");
speakText2(word);
}
// speakText is called by onClick button
public void speakText(View v) {
String textContents = text.getText().toString();
engine.speak(textContents, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void speakText2(String textContents) {
engine.speak(textContents, TextToSpeech.QUEUE_ADD, null, null);
}
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
//Setting speech Language
engine.setLanguage(Locale.ENGLISH);
engine.setPitch(1);
}
}
}
Now, I want to call MainActivity from another activity and pass a string to speak up.
I tried:
MainActivity mainactivity = new MainActivity();
String word;
word = "speak";
mainactivity.speakText2(word); // Error
But, getting error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.speech.tts.TextToSpeech.speak(java.lang.CharSequence, int, android.os.Bundle, java.lang.String)' on a null object reference
at MainActivity.speakText2(TTSEngine.java:53)
I tried using intent from another activity:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("word", word);
startActivity(intent);
But, getting error:
I/TextToSpeech: Sucessfully bound to com.google.android.tts
W/TextToSpeech: speak failed: not bound to TTS engine
W/TextToSpeech: speak failed: not bound to TTS engine
W/TextToSpeech: speak failed: not bound to TTS engine
I/TextToSpeech: Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
I/TextToSpeech: Set up connection to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
I tried to implement TextToSpeech in the activity I want to use it in. But, it does not work for the first time I call speakText2 and give error:
W/TextToSpeech: speak failed: not bound to TTS engine
I/TextToSpeech: Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
I/TextToSpeech: Set up connection to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
For rest of the time it work perfectly. Any idea how to fix this?
You can only let the engine speak, after onInit is done, so do following in onInit():
if (status == TextToSpeech.SUCCESS) {
speakText2(word);
}
You have to use an Intent to start an Activity. See https://developer.android.com/training/basics/firstapp/starting-activity.html
When you create your Activity instance manually the onCreate method is not called (and any other lifecycle methods) - that’s why you’re getting an NPE accessing your engine property - it wasn’t initialized.

Unable to restore nested fragment state

I'm having a problem restoring the state of nested fragments. Here's the hierarchy:
MainActivity
----> AlarmOverviewFragment (doesn't really hold any important data)
--------> AlarmFragment (holds data)
The problem I am running into is when I minimize the app (press home button) and then reopen the app, it crashes every time when trying to get data from an array stored as one of Fragment's instance variables inside of onCreateView().
The frustrating bit is that I'm saving the instance variables in onSaveInstanceState(), but savedInstanceState is always null in onCreateView(), onCreate(), and onActivityCreated().
Clearly I am missing something huge here because I've tried many solutions found on stackoverflow to no avail. Here's some relevant code bits:
Saving instance data:
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("hour", this.hour);
outState.putInt("window", this.window);
outState.putInt("minutes", this.minutes);
outState.putBooleanArray("days", this.days);
super.onSaveInstanceState(outState);
}
Unsuccessfully trying to restore data
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
/* Never happens */
hour = savedInstanceState.getInt("hour");
window = savedInstanceState.getInt("window");
minutes = savedInstanceState.getInt("minutes");
days = savedInstanceState.getBooleanArray("days");
}
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
if (savedInstanceState != null) {
/* Also never happens */
}
super.onActivityCreated(savedInstanceState);
}
And just in case this is helpful, here's the stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: group12.wakemeup, PID: 22756
java.lang.RuntimeException: Unable to resume activity {group12.wakemeup/group12.wakemeup.MainActivity}: java.lang.NullPointerException: Attempt to read from null array
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3121)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5525)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.NullPointerException: Attempt to read from null array
at group12.wakemeup.AlarmFragment.onCreateView(AlarmFragment.java:113)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1682)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:607)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:181)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.app.Activity.performStart(Activity.java:6288)
at android.app.Activity.performRestart(Activity.java:6334)
at android.app.Activity.performResume(Activity.java:6339)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3110)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5525) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 
EDIT
Extra information
Each AlarmFragment is added dynamically and given a unique ID via View.generateViewId(), so I've been unsure of how to save each fragment in MainActivity. Also worth mentioning that I do use a FragmentPagerAdapter to handle tabs/swiping (there are other Overview fragments in this app, but I left them out as they aren't causing me problems). I've heard there is a way to use a ViewPager to save state, perhaps there is one with a FragmentPagerAdapter as well?
Since your problem seems different from the start, actually you don't need to re-create your fragments inside onNewIntent every time.
You can do this instead:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if ("some_action".equals(intent.getAction())) {
//your action, in your case create and assign fragment
//remove the action
intent.setAction(null);
}
}
Try to save your fragments in your activity
private YourFragment yourFragment;
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment instances
getFragmentManager().putFragment(outState, "any string you want as key", yourFragment);
//or use code below if you use android.support.v4.app.Fragment
//getSupportFragmentManager().putFragment(outState, "any string you want as key", yourFragment);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
//retrieve your fragment that saved from onSaveInstanceState()
yourFragment = (YourFragment) getFragmentManager().getFragment(savedInstanceState, "any string you want as key");
//or
//yourFragment = (YourFragment) getSupportFragmentManager().getFragment(savedInstanceState, "any string you want as key");
}
else {
//create your fragment if it is first time
yourFragment = new YourFragment();
}
}
Well I guess my problem came from something completely different. MainActivity was creating a new AlarmFragment using onNewIntent() when it returned from a series of activities to define the values for each AlarmFragment. Evidently, minimizing the app and then reopening it calls onNewIntent() every time, so my solution was to make sure that I was actually creating new AlarmFragments with data. Stupid problem, stupid solution

OrientationChange doesn't destroy activity?

I have a rather commonly occurring situation in Android, which has to do with the previous asynctask updating the activity, whilst the activity has been lost because of a change in orientation.
I have an activity, Activity A.
Activity A implements OnDownloadCompleteListener {
public void sync()
{
new SyncAttestationInfoTask(this).execute();
}
#Override
public void onComplete()
{
loadAttestationInfo();
}
}
Here is my asynctask shortened:
package com.evento.mofa.backgroundtasks;
import java.util.ArrayList;
import java.util.List;
/**
* #author Ahmed
*
*/
public class SyncAttestationInfoTask extends AsyncTask<Void, Void,Void> {
/*TIP*/
//TO SPEED UP THIS OPERATION WE CAN USE THE EXECUTEONEXECUTOR .
private ProgressDialog pd;
private OnDownloadComplete parentActivityContext;
EntityConvert convert = new EntityConvert();
private AttestationDao aDao = new AttestationDao();
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (Locale.getDefault().getLanguage().equals("ar"))
{
/*EMPTY ALL THE TABLES THEN START PROCESSING*/
aDao.flushTables(Locale.getDefault().getLanguage());
syncAttestLocations(Webservices.ATTEST_LOCATION_AR,1);
syncDocumentTypes(Webservices.DOCUMENT_TYPES_AR,1);
syncAttestationInfo(Webservices.ATTESTATION_INFO_AR,1);
} else {
/*EMPTY ALL THE TABLES THEN START PROCESSING*/
aDao.flushTables(Locale.getDefault().getLanguage());
syncAttestLocations(Webservices.ATTEST_LOCATION,0);
syncDocumentTypes(Webservices.DOCUMENT_TYPES,0);
syncAttestationInfo(Webservices.ATTESTATION_INFO,0);
}
return null;
}
public SyncAttestationInfoTask(OnDownloadComplete context) {
parentActivityContext = context;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog((Context)parentActivityContext);
pd.setTitle("Loading...");
pd.setMessage("Updating Data.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
parentActivityContext.onComplete();
// findViewById(R.id.the_button).setEnabled(true);
}
}
There is something strange with my Activity.
I put a breakpoint on the onComplete callback inside my activity
I start a progress dialog inside the sync async task.
As soon as the progress dialog displays on the screen I landscape my device.
The dialog box vanishes, and pd.dismiss() raises a "View not attached" error (I understand that the activity that it was attached to no longer exists).
The above means that parentActivityContext().oncomplete should also throw the same error, however it does not.
I commented the pd.Dismiss(), and found out that the breakpoint on onComplete() is invoked? Isn't this strange given the fact that the reference to the activity has been lost at this point?
Please give me insight into this.
I would do this
Add this line to your Manifest.xml file, this will prevent of calling onCreate() when screen rotates.
<activity android:name=".yourActivity" android:configChanges="keyboardHidden|orientation">
Version above Android 3.2, you also need to add "screenSize":
<activity android:name=".yourActivity" android:configChanges="keyboardHidden|orientation|screenSize">
This will prevent activity from restarting on orientation change, and you should not have any problems (except maybe some layout fixes)
The previous Activty is being referenced by the AsyncTask via a strong reference.
AsyncTask constructed with Activity 1 (parentActivityContex =
Activity 1)
Activity 1 "destroyed" and Activity 2 comes into foreground
AsyncTask completes, calls parentActivityContext (Activity 1) onComplete
Activity 2 just sits there doing nothing
Activity 1 no longer has active references pointing to it, is collected
You could try doing your task in a Service and having whatever Activity is in the foreground receive a broadcast, or you could try having your AsyncTask reference a Fragment with setRetainInstance(true). Below is an example of the second case. Note that you might want to handle the case where the AsyncTask completes while the Fragment is detached from one Activity and not yet attached to the next Activity
public class ExampleDownloadFragment extends Fragment {
#Override
public void onCreate(final Bundle savedInstanceState) {
setRetainInstance(true);
new SyncAttestationInfoTask(this).execute();
}
public void onComplete() {
final Activity activity = getActivity();
if (activity != null && activity instanceof A) {
((A) activity).onComplete();
}
}
}

Unable to create a new Loader after long periods of inactivity

I have an Android application whose Fragments rely on loaders to fetch data. Below is the skeleton code of my Fragment. Everything is the same except I have some custom code in the onLoadFinished method.
public class Events extends Fragment implements LoaderCallbacks<ArrayList<Event>> {
private Integer intWeek;
public static Events newInstance(Integer intWeek) {
Events pageFragment = new Events();
pageFragment.intWeek = intWeek;
pageFragment.setArguments(new Bundle());
return pageFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.events, null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(this.intWeek, savedInstanceState, this);
}
public Loader<ArrayList<Event>> onCreateLoader(int intLoader, Bundle bndBundle) {
return new Scraper(getActivity().getApplicationContext());
}
public void onLoadFinished(Loader<ArrayList<Event>> ldrEvents, final ArrayList<Event> lstEvents) {
//Do something with the returned data
}
public void onLoaderReset(Loader<ArrayList<Event>> ldrEvents) {
return;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
This Fragment is used inside a FragmentActivity which uses ViewPager which gets its Fragment´s using aFragmentPagerAdapter`.
This works fine and I'm able to page between the Fragments like the one shown above. Every time a new Fragment is added to the ViewPager, the onCreate method fires and it creates a new Loader.
When I press the "Home" button on my phone, the application pauses and goes into the background. I can always restore the application and it works just fine — after 5/10/20 minutes of being in the background.
...but If I leave the application in the background for a long time, an hour or more, the application crashes upon start and the stacktrace points to the following line in the onCreate method:
getLoaderManager().initLoader(this.intWeek, savedInstanceState, this);
Now I'm very lost as to why this is happening. It seems that the Android framework destroys something in the background after long periods of inactivity in the background and the initLoader method isn't able to create a Loader. The documentation about the initLoader method specifically says:
Ensures a loader is initialized and active. If the loader doesn't
already exist, one is created and (if the activity/fragment is
currently started) starts the loader. Otherwise the last created
loader is re-used.
Would anyone be able to point out what I'm doing wrong here? This seems to be a pretty difficult issue to debug because I can't replicate it at will. It is very random. Thanks
Stacktrace from logcat:
Transmitting stack trace: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mridang.stadi/com.mridang.stadi.Main}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2079)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
at android.app.ActivityThread.access$600(ActivityThread.java:132)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4575)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mridang.stadi.events.Events.onCreate(Events.java:73)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:834)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:1805)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:200)
at com.mridang.stadi.Main.onCreate(Main.java:23)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2033)
... 11 more
I ran into a similar problem with the loaders. What I found is that the Fragment/Loader lifecycle is complicated. I'd love to find a document that explains it in detail.
Anyhow, what I did to fix the problem was move the initLoader() call to the onActivityCreated() method. Give that a try.
Try using something like this:
boolean canFire = ((loader != null) && !loader.isReset());
// restart or initialise loader
if (canFire) {
getLoaderManager().restartLoader(loaderId, args, this);
} else {
getLoaderManager().initLoader(loaderId, args, this);
}

Android; Declaring edittext in class body (Out of any method)

I have experience with programming languages but am a bit new to android programming.
I have a program with some fields that function as labels(textview), buttons, and data entry(edittext).
Whenever i declare them at the beginning of the program out of any methods(but in the class of course), when I start my application it crashes and simulation gives a "unfortunately, your program has stopped" alert.
Eclipse doesn't give any errors for the declaration and i did use the same way for defining regular variables with no issue. It also gives the same error when i declare a mediaplayer object in the class body.
Does anyone know why it gives error?
And is there another way to declare global objects like edittext, viewtext, etc... Declaring them over and over again in methods sounds weird to me.
Thank you!!
public class TrainerActivity extends Activity {
Button stopTimer = (Button)findViewById(R.id.StopTimer);
Button startTimer = (Button)findViewById(R.id.StartTimer);
EditText totalTime = (EditText)findViewById(R.id.TotalTime);
EditText enterMin = (EditText)findViewById(R.id.EnterMin);
EditText enterSec = (EditText)findViewById(R.id.EnterSec);
private boolean breaker = false;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StartTimer();
}
});
stopTimer.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Button_StopTimer();
}
});
}
Without seeing example code of what you're trying it's impossible to say for definite (we don't do mind-reading here). But let me guess, you're doing something like this?...
public class MyActivity extends Activity {
TextView tv1; // This is fine.
  TextView tv2 = (TextView) findViewById(R.id.textview2); // Don't do this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView) findViewById(R.id.textview1); // This is fine
tv1.setText("Some text"); // This works
tv2.setText("Some text"); // NullPointerException here
}
}
The tv2.setText(...) will fail because you used findViewById(...) BEFORE you call setContenetView(...) and as a result, tv2 will be null.
It's quite acceptable to declare your widgets as instance members in your Activity but don't try to use findViewById(...) until AFTER you have set your content view.
try declaring the widget objects names only outside the onCreate() method
Button stopTimer;
Button startTimer;
EditText totalTime;
EditText enterMin;
EditText enterSec;
then initialise them after setContentView() inside onCreate()
setContentView(R.layout.main);
stopTimer = (Button)findViewById(R.id.StopTimer);
startTimer = (Button)findViewById(R.id.StartTimer);
totalTime = (EditText)findViewById(R.id.TotalTime);
enterMin = (EditText)findViewById(R.id.EnterMin);
enterSec = (EditText)findViewById(R.id.EnterSec);
Can you post a bit of sample code that illustrates the issue? It is fine to declare a member variable that is an EditText or TextView in the class.
logcat(in DDMS) should be give you some info about the error as well. If you are using eclipse there is a tab for DDMS, if not you can just run DDMS from a command line look at the logcat tab and launch your app (with your phone plugged in via usb, of course.) You should be able to see the actual error being reported.
You can declare these variables inside the Class body or inside the method body. In the former case, the variables are global and thus can be accessed within the whole class; in the latter case, they are local and thus can be only accessed within that method. Both of them could be commonly seen in proramming.
In Android, the typical application is that you declare the variables in the Class body and instantiate them in the onCreate() method. Something like this:
public Class MyClass extends Activity{
TextView label;// so this variable can be accessed within any methods in this Class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(Bundle savedInstanceState);
setContentView(R.layout.main) // load the layout of the activity
label=(TextView)findViewById(R.id.<the TextView id defined in the layout file>); //this variable get instantiated. From now on you can manipulate it anywhere inside the class.
Button submit=(Button)findViewById(R.id.<the Button id defined in the layout file>);//you declared and instantiated it, but it could only be used within this method since you declared it here.
}
}
If you just declare a variable in the Class body,in most caeses, you can't use it until you instantiate it, because they are null before the instantiation. I think this is why you have problems. Please post the logcat so we can specify the real problem.

Categories