I may have my terms mixed up, but I'm creating an android app and I want to encapsulate some of the routine functions. For instance my actionBar. At first I had the code on all my activities and if I change one thing I have to change it else where. I want to create a NavigationActionBarManager.java file to handle the inital setup, onNavigationListener, setListNavigationCallbacks, etc.
Here's the class so far:
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;
public class NavigationActionBarManager extends Activity {
public ActionBar actionBar = getActionBar(); // actionbar object
// METHOD: display
public void display() {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
}
// METHOD: inflate
public void inflate(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_adventurers_new, menu);
}
// METHOD: listen
public void listen() {
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.array_character_views, android.R.layout.simple_spinner_dropdown_item);
OnNavigationListener mOnNavigationListener = new OnNavigationListener() {
//String[] strings = getResources().getStringArray(R.array.array_character_views);
#Override
public boolean onNavigationItemSelected(int position, long itemId) {
Intent nextScreen = null;
switch(position) {
case 0:
break;
case 1:
nextScreen = new Intent(getApplicationContext(), AdventurersNewAbilitiesActivity.class);
break;
case 2:
break;
}
if(nextScreen != null) {
startActivity(nextScreen);
}
return false;
}
};
actionBar.setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
}
}
Back in my activity class, I want to apply it as such:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adventurer_new_character);
navBar.display();
navBar.listen();
}
I'm running into an error and I don't understand LogCat's output. Here's the LogCat ouput:
04-17 23:12:01.110: E/AndroidRuntime(14013): FATAL EXCEPTION: main
04-17 23:12:01.110: E/AndroidRuntime(14013): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.app/com.app.AdventurersNewCharacterActivity}: java.lang.NullPointerException
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1903)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2004)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.ActivityThread.access$600(ActivityThread.java:132)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.os.Looper.loop(Looper.java:137)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.ActivityThread.main(ActivityThread.java:4580)
04-17 23:12:01.110: E/AndroidRuntime(14013): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 23:12:01.110: E/AndroidRuntime(14013): at java.lang.reflect.Method.invoke(Method.java:511)
04-17 23:12:01.110: E/AndroidRuntime(14013): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-17 23:12:01.110: E/AndroidRuntime(14013): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
04-17 23:12:01.110: E/AndroidRuntime(14013): at dalvik.system.NativeStart.main(Native Method)
04-17 23:12:01.110: E/AndroidRuntime(14013): Caused by: java.lang.NullPointerException
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.Activity.initActionBar(Activity.java:2071)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.Activity.getActionBar(Activity.java:2058)
04-17 23:12:01.110: E/AndroidRuntime(14013): at com.app.NavigationActionBarManager.<init>(NavigationActionBarManager.java:13)
04-17 23:12:01.110: E/AndroidRuntime(14013): at com.app.AdventurersNewCharacterActivity.<init>(AdventurersNewCharacterActivity.java:13)
04-17 23:12:01.110: E/AndroidRuntime(14013): at java.lang.Class.newInstanceImpl(Native Method)
04-17 23:12:01.110: E/AndroidRuntime(14013): at java.lang.Class.newInstance(Class.java:1319)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.Instrumentation.newActivity(Instrumentation.java:1025)
04-17 23:12:01.110: E/AndroidRuntime(14013): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1894)
04-17 23:12:01.110: E/AndroidRuntime(14013): ... 11 more
Have you implemented the onCreateOptionsMenu() method in your activity?
doc available at https://developer.android.com/guide/topics/ui/actionbar.html
Related
I have FirstRunActivity and MainActivity (launcher). When app opening and if app opened for the first time, i start FirstRunActivity (with clearing activity history).
It's working ok. But when turning on autorotation in device, then opening app with rotated device, screen is blinking. In log i can see that activity is recreates itself in loop.
Log :
3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:00.390 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:00.410 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:00.410 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:00.480 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:00.480 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:00.520 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:00.520 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:00.630 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:00.630 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:00.680 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:00.680 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:00.800 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:00.810 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:00.870 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:00.870 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:00.960 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:00.970 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:00.990 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:00.990 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:01.060 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:01.060 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:01.080 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:01.080 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:01.150 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:01.150 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:01.180 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:01.180 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:01.250 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
04-17 22:49:01.250 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStop
04-17 22:49:01.280 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onStart
04-17 22:49:01.280 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onResume
04-17 22:49:01.430 3028-3028/tm.mobile.payment D/SazHyzmat﹕ FirstRunActivity onPause
FirstRunActivity.java :
public class FirstRunActivity extends ActionBarActivity {
#InjectView(R.id.password) EditText passwordView;
#InjectView(R.id.password_retype) EditText passwordRetypeView;
#InjectView(R.id.save) View saveButton;
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_run);
ButterKnife.inject(this);
}
#Override protected void onStart() {
super.onStart();
U.l("FirstRunActivity onStart");
}
#Override protected void onStop() {
super.onStart();
U.l("FirstRunActivity onStop");
}
#Override protected void onPause() {
super.onStart();
U.l("FirstRunActivity onPause");
}
#Override protected void onResume() {
super.onStart();
U.l("FirstRunActivity onResume");
}
}
MainActivity.java :
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
settingsManager = SettingsManager.getInstance(this);
//If app not initialized
if (! settingsManager.isAppInitialized()) {
Intent intent = new Intent(this, FirstRunActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
finish();
} else {
//Other code
}
}
If i change code that starting first run activity (in MainActivity.java) with just starting activity, activity is not blinking, but when pressing back button it will open MainActivity with white screen.
Or clearing activity history with other way like here: Clear the entire history stack and start a new activity on Android screen is blinking anyway.
So how can i stop blinking and clearing activity history?
EDIT
After tests i have found that in my other activities, that have no connection with above code, have same problem, blinking. When opening activity with rotated device.
Looking at the documentation for IntentCompat.makeRestartActivityTask, it sounds like it creates an intent that serves to restart your current activity. I recommend removing these two lines:
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
I've never needed them while changing activities.
Additionally, the call to mContext.finish() can be accomplished with just finish() and can never be null in that case, most likely the reason that you were seeing the white screen was that mContext was null, so you never successfully finished that activity.
You need to define the Activity in the manifest with a NoDisplay Theme. Then, start FirstRunActivity or LoginActivity (or whatever). The IntentCompat is not needed unless you support versions below HoneyComb, where you can use FLAG_ACTIVITY_CLEAR_TASK
See https://stackoverflow.com/a/4892712/218473
I am currently looking through the Android Developer tutorials and am on the most basic of tutorials which is passing an intent from one activity to another and displaying the result.
Eclipse shows the app has having no errors and everything works fine (not functional) till I insert these lines of code:
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
I'm looking at the LogCat and did manage to resolve one error where i'd simply named something incorrectly but now i'm stumped again. Here is my current LogCat output:
10-09 18:09:03.882: D/Send Message Button(9652): Pressed
10-09 18:09:03.917: E/FragmentManager(9652): No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{422e3888 #0 id=0x7f05003c}
10-09 18:09:03.917: E/FragmentManager(9652): Activity state:
10-09 18:09:03.917: D/FragmentManager(9652): Local FragmentActivity 422d1598 State:
10-09 18:09:03.922: D/FragmentManager(9652): mCreated=truemResumed=false mStopped=false mReallyStopped=false
10-09 18:09:03.922: D/FragmentManager(9652): mLoadersStarted=false
10-09 18:09:03.922: D/FragmentManager(9652): Active Fragments in 422d1808:
10-09 18:09:03.922: D/FragmentManager(9652): #0: PlaceholderFragment{422e3888 #0 id=0x7f05003c}
10-09 18:09:03.922: D/FragmentManager(9652): mFragmentId=#7f05003c mContainerId=#7f05003c mTag=null
10-09 18:09:03.922: D/FragmentManager(9652): mState=0 mIndex=0 mWho=android:fragment:0 mBackStackNesting=0
10-09 18:09:03.927: D/FragmentManager(9652): mAdded=true mRemoving=false mResumed=false mFromLayout=false mInLayout=false
10-09 18:09:03.927: D/FragmentManager(9652): mHidden=false mDetached=false mMenuVisible=true mHasMenu=false
10-09 18:09:03.927: D/FragmentManager(9652): mRetainInstance=false mRetaining=false mUserVisibleHint=true
10-09 18:09:03.927: D/FragmentManager(9652): mFragmentManager=FragmentManager{422d1808 in DisplayMessageActivity{422d1598}}
10-09 18:09:03.927: D/FragmentManager(9652): mActivity=com.example.myfirstapp.DisplayMessageActivity#422d1598
10-09 18:09:03.927: D/FragmentManager(9652): Added Fragments:
10-09 18:09:03.927: D/FragmentManager(9652): #0: PlaceholderFragment{422e3888 #0 id=0x7f05003c}
10-09 18:09:03.927: D/FragmentManager(9652): FragmentManager misc state:
10-09 18:09:03.927: D/FragmentManager(9652): mActivity=com.example.myfirstapp.DisplayMessageActivity#422d1598
10-09 18:09:03.927: D/FragmentManager(9652): mContainer=android.support.v4.app.FragmentActivity$2#422d1880
10-09 18:09:03.927: D/FragmentManager(9652): mCurState=2 mStateSaved=false mDestroyed=false
10-09 18:09:03.927: D/FragmentManager(9652): View Hierarchy:
10-09 18:09:03.927: D/FragmentManager(9652): com.android.internal.policy.impl.PhoneWindow$DecorView{422d31a8 V.E..... ... 0,0-0,0}
10-09 18:09:03.932: D/FragmentManager(9652): com.android.internal.widget.ActionBarOverlayLayout{422d37e8 V.ED.... ... 0,0-0,0 #1020313 android:id/action_bar_overlay_layout}
10-09 18:09:03.932: D/FragmentManager(9652): android.widget.FrameLayout{422d43f8 V.E..... ... 0,0-0,0 #1020002 android:id/content}
10-09 18:09:03.932: D/FragmentManager(9652): android.widget.TextView{422e3b30 V.ED.... ... 0,0-0,0}
10-09 18:09:03.932: D/FragmentManager(9652): com.android.internal.widget.ActionBarContainer{422d47f8 V.ED.... ... 0,0-0,0 #1020314 android:id/action_bar_container}
10-09 18:09:03.932: D/FragmentManager(9652): com.android.internal.widget.ActionBarView{422d4d00 V.E..... ... 0,0-0,0 #1020315 android:id/action_bar}
10-09 18:09:03.932: D/FragmentManager(9652): android.widget.LinearLayout{422d5270 VFE...C. ... 0,0-0,0}
10-09 18:09:03.932: D/FragmentManager(9652): com.android.internal.widget.ActionBarView$HomeView{422d6350 V.E..... ... 0,0-0,0}
10-09 18:09:03.937: D/FragmentManager(9652): android.widget.ImageView{422d66e8 V.ED.... ... 0,0-0,0 #102025a android:id/up}
10-09 18:09:03.937: D/FragmentManager(9652): android.widget.ImageView{422d6a48 V.ED.... ... 0,0-0,0 #102002c android:id/home}
10-09 18:09:03.937: D/FragmentManager(9652): android.widget.LinearLayout{422d7c40 G.E..... ... 0,0-0,0}
10-09 18:09:03.937: D/FragmentManager(9652): android.widget.TextView{422d7f58 V.ED.... ... 0,0-0,0 #1020265 android:id/action_bar_title}
10-09 18:09:03.937: D/FragmentManager(9652): android.widget.TextView{422d8be0 G.ED.... ... 0,0-0,0 #1020266 android:id/action_bar_subtitle}
10-09 18:09:03.937: D/FragmentManager(9652): com.android.internal.widget.ActionBarContextView{422d9200 G.E..... ... 0,0-0,0 #1020316 android:id/action_context_bar}
10-09 18:09:03.937: D/AndroidRuntime(9652): Shutting down VM
10-09 18:09:03.937: W/dalvikvm(9652): threadid=1: thread exiting with uncaught exception (group=0x41f55ba8)
10-09 18:09:03.942: E/AndroidRuntime(9652): FATAL EXCEPTION: main
10-09 18:09:03.942: E/AndroidRuntime(9652): Process: com.example.myfirstapp, PID: 9652
10-09 18:09:03.942: E/AndroidRuntime(9652): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{422e3888 #0 id=0x7f05003c}
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.os.Handler.dispatchMessage(Handler.java:102)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.os.Looper.loop(Looper.java:136)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.ActivityThread.main(ActivityThread.java:5001)
10-09 18:09:03.942: E/AndroidRuntime(9652): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 18:09:03.942: E/AndroidRuntime(9652): at java.lang.reflect.Method.invoke(Method.java:515)
10-09 18:09:03.942: E/AndroidRuntime(9652): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-09 18:09:03.942: E/AndroidRuntime(9652): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
10-09 18:09:03.942: E/AndroidRuntime(9652): at dalvik.system.NativeStart.main(Native Method)
10-09 18:09:03.942: E/AndroidRuntime(9652): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{422e3888 #0 id=0x7f05003c}
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:934)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:571)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.Activity.performStart(Activity.java:5241)
10-09 18:09:03.942: E/AndroidRuntime(9652): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
10-09 18:09:03.942: E/AndroidRuntime(9652): ... 11 more
MainActivity.java
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public void sendMessage(View view) {
Log.d("Send Message Button", "Pressed");
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
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;
}
#Override
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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
DisplayMessageActivity.java
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
Any help is appreciated. Thanks
EDIT: Ran a clean and this is logcat now:
10-09 18:24:43.317: W/dalvikvm(9771): threadid=1: thread exiting with uncaught exception (group=0x41f55ba8)
10-09 18:24:43.322: E/AndroidRuntime(9771): FATAL EXCEPTION: main
10-09 18:24:43.322: E/AndroidRuntime(9771): Process: com.example.myfirstapp, PID: 9771
10-09 18:24:43.322: E/AndroidRuntime(9771): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{4228bce8 #0 id=0x7f05003c}
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.os.Handler.dispatchMessage(Handler.java:102)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.os.Looper.loop(Looper.java:136)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.ActivityThread.main(ActivityThread.java:5001)
10-09 18:24:43.322: E/AndroidRuntime(9771): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 18:24:43.322: E/AndroidRuntime(9771): at java.lang.reflect.Method.invoke(Method.java:515)
10-09 18:24:43.322: E/AndroidRuntime(9771): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-09 18:24:43.322: E/AndroidRuntime(9771): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
10-09 18:24:43.322: E/AndroidRuntime(9771): at dalvik.system.NativeStart.main(Native Method)
10-09 18:24:43.322: E/AndroidRuntime(9771): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{4228bce8 #0 id=0x7f05003c}
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:934)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:571)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.Activity.performStart(Activity.java:5241)
10-09 18:24:43.322: E/AndroidRuntime(9771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
10-09 18:24:43.322: E/AndroidRuntime(9771): ... 11 more
You have replace the view R.layout.activity_display_message with text view. The layout R.layout.activity_display_message contains the container to put fragment into it.
The IllegalArgument is passed in your setContentView that is textView in your case so the container Id in you mainActivity is missing and your fragment is still attached to your activity thats why the exception occured.
Though you have not provided xml. Check your xml file and look for container Because it says No view found for container. Try adding or replacing it with frame layout
10-09 18:09:03.942: E/AndroidRuntime(9652): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{422e3888 #0 id=0x7f05003c}
In your setContentView you have to set a layout you defined in /res/layout folder. There you can create your textView...
For example setContentView(R.layout.myFirstLayout);
I'm trying to populate a listview with some data from json.
Here are the errors I am getting:
04-17 12:54:25.573: E/JSON Parser(1169): Error parsing data org.json.JSONException:
of type org.json.JSONArray cannot be converted to JSONObject
04-17 12:54:26.223: E/AndroidRuntime(1169): FATAL EXCEPTION: main
04-17 12:54:26.223: E/AndroidRuntime(1169): Process: com.example.mysqltest, PID: 1169
04-17 12:54:26.223: E/AndroidRuntime(1169): java.lang.NullPointerException
04-17 12:54:26.223: E/AndroidRuntime(1169): at com.example.mysqltest.PropertyView$JSONParseP.onPostExecute(PropertyView.java:95)
04-17 12:54:26.223: E/AndroidRuntime(1169): at com.example.mysqltest.PropertyView$JSONParseP.onPostExecute(PropertyView.java:1)
04-17 12:54:26.223: E/AndroidRuntime(1169): at android.os.AsyncTask.finish(AsyncTask.java:632)
04-17 12:54:26.223: E/AndroidRuntime(1169): at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-17 12:54:26.223: E/AndroidRuntime(1169): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
04-17 12:54:26.223: E/AndroidRuntime(1169): at android.os.Handler.dispatchMessage(Handler.java:102)
04-17 12:54:26.223: E/AndroidRuntime(1169): at android.os.Looper.loop(Looper.java:136)
04-17 12:54:26.223: E/AndroidRuntime(1169): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-17 12:54:26.223: E/AndroidRuntime(1169): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 12:54:26.223: E/AndroidRuntime(1169): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 12:54:26.223: E/AndroidRuntime(1169): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-17 12:54:26.223: E/AndroidRuntime(1169): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-17 12:54:26.223: E/AndroidRuntime(1169): at dalvik.system.NativeStart.main(Native Method)
Here is my Java file...
JSONArray array = null
public void onClick(View view)
new JSONParseP().execute()
private class JSONParseP extends AsyncTask<String, String, JSONObject>
protected JSONObject doInBackground(String... args)
JSONParserP jParser = new JSONParserP();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrlP(url);
return json;
protected void onPostExecute(JSONObject json)
pDialog.dismiss();
try {
// Getting JSON Array from URL
array = json.getJSONArray(null);
for(int i = 0; i < array.length(); i++){
JSONObject c = array.getJSONObject(i);
Any help I would highly appreciate it.
Thanks.
Try changing JSONObject c = array.getJSONObject(i); to JSONArray c = array.getJSONArray(i);
I've looked at countless projects and tutorials and haven't been able to figure out why my app is crashing as soon as it is ran. It seems to run fine if i comment out the first line in the try catch "JSONObject dataObject = json.getJSONObject("data");" The JSON that i'm trying to parse is formatted as such:
{"recordcount":3,
"columnlist":"department,emailaddress,firstname,has_photos,job_full_title,job_title,kid,lastname,location,middlename,no_show_photo,phone,school",
"data":
{"department":["Public Safety","Information Technology","Information Technology"],
"emailaddress":["todd.mongeon#wne.edu","amutti#wne.edu","fatemeh.shams#wne.edu"],
"firstname":["Todd","Tony","Toffee"],
"has_photos":["Y","Y","N"],
"job_full_title":["Officer","Director, Administrative Information Systems","Sr.Technical Programmer/Analyst and Integ Specialist"],
"job_title":["Officer","Director, Administrative Information Systems","Sr.Technical Programmer/Analyst and Integ Specialist"],
"kid":[286899,2497,297411],
"lastname":["Mongeon","Mutti","Shams"],
"location":["PS","12 V","12 V"],
"middlename":["A.","M.",""],
"no_show_photo":["","",""],
"phone":["413-782-1207","413-782-1212","413-796-2398"],
"school":["Public Safety Group","Information Technology Group","Information Technology Group"]}}
My program looks like this (please excuse formatting / things that don't need to be there... it needs to be cleaned up from a lot of the things i've tried to get this to work..)
public class Directory_finalActivity extends ListActivity {
public static String url = "http://www1.wne.edu/webservices/directorydemo.cfc?wsdl&method=getEmployees&limit=25&firstname=to&outputtype=JSON";
// JSON array names
private static final String TAG_FIRST = "firstname";
private static final String TAG_LAST = "lastname";
private static final String TAG_SCHOOL = "school";
private static final String TAG_DEPARTMENT = "department";
private static final String TAG_EMAIL = "emailaddress";
private static final String TAG_PHONE = "phone";
private static final String TAG_JOB = "job_title";
private static final String TAG_LOCATION = "location";
//create JSON array
JSONArray firstNames = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
String[] firstNames = null;
try {
// Getting the data object
JSONObject dataObject = json.getJSONObject("data"); //This is the line that seems to be causing the error.
int numResults = json.getInt("recordcount");
/**
JSONArray firstNameArray = dataObject.getJSONArray("firstname");
JSONArray lastNameArray = dataObject.getJSONArray("lastname");
JSONArray schoolArray = dataObject.getJSONArray("school");
JSONArray departmentArray = dataObject.getJSONArray("department");
JSONArray eMailArray = dataObject.getJSONArray("emailaddress");
JSONArray phoneNumberArray = dataObject.getJSONArray("phone");
JSONArray jobTitleArray = dataObject.getJSONArray("job_title");
JSONArray locationArray = dataObject.getJSONArray("location");
//Loop through index of array(s)
for(int i = 0; i <= numResults; i++)
{
//Store value of JSONArray at index "i" into string variables.
String firstName = firstNameArray.getString(i);
String eMail = eMailArray.getString(i);
String phone = phoneNumberArray.getString(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_FIRST, firstName);
map.put(TAG_EMAIL, eMail);
map.put(TAG_PHONE, phone);
//add the hashmap to array list.
contactList.add(map);
}*/
}
catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
//ListAdapter adapter = new SimpleAdapter(this, contactList,
// R.layout.list_item,
// new String[] { TAG_FIRST, TAG_EMAIL, TAG_PHONE }, new int[] {
// R.id.name, R.id.email, R.id.mobile });
//setListAdapter(adapter);
}
}
My JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I'm probably doing something incredibly stupid here, i'm new to this so give me a break please haha. I appreciate any info that you guys may have for me.
For curiosity sake the end goal is to search the database (first name, last name, school, and department) and put the results into a list view, when clicked on a window will pop up displaying other relevant information with a couple other features.
It seems every example i see the JSON output they receive from the url is formatted much differently, so i'm having trouble getting this done even with the amount of examples available (sorry for re-post).
Once again thank you for any assistance.
EDIT 1:
LOGCAT:
04-17 00:45:35.828: W/System.err(305): java.net.UnknownHostException: api.androidhive.info
04-17 00:45:35.828: W/System.err(305): at java.net.InetAddress.lookupHostByName(InetAddress.java:513)
04-17 00:45:35.838: W/System.err(305): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:278)
04-17 00:45:35.838: W/System.err(305): at java.net.InetAddress.getAllByName(InetAddress.java:242)
04-17 00:45:35.838: W/System.err(305): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
04-17 00:45:35.838: W/System.err(305): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-17 00:45:35.838: W/System.err(305): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-17 00:45:35.838: W/System.err(305): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
04-17 00:45:35.838: W/System.err(305): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-17 00:45:35.838: W/System.err(305): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-17 00:45:35.838: W/System.err(305): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-17 00:45:35.838: W/System.err(305): at directory.plus.JSONParser.getJSONFromUrl(JSONParser.java:39)
04-17 00:45:35.838: W/System.err(305): at directory.plus.Directory_finalActivity.onCreate(Directory_finalActivity.java:53)
04-17 00:45:35.849: W/System.err(305): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-17 00:45:35.849: W/System.err(305): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-17 00:45:35.849: W/System.err(305): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-17 00:45:35.849: W/System.err(305): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-17 00:45:35.849: W/System.err(305): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-17 00:45:35.849: W/System.err(305): at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 00:45:35.849: W/System.err(305): at android.os.Looper.loop(Looper.java:123)
04-17 00:45:35.849: W/System.err(305): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 00:45:35.849: W/System.err(305): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 00:45:35.849: W/System.err(305): at java.lang.reflect.Method.invoke(Method.java:521)
04-17 00:45:35.858: W/System.err(305): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 00:45:35.858: W/System.err(305): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 00:45:35.858: W/System.err(305): at dalvik.system.NativeStart.main(Native Method)
04-17 00:45:35.858: E/Buffer Error(305): Error converting result java.lang.NullPointerException
04-17 00:45:35.868: E/JSON Parser(305): Error parsing data org.json.JSONException: End of input at character 0 of
04-17 00:45:35.868: D/AndroidRuntime(305): Shutting down VM
04-17 00:45:35.868: W/dalvikvm(305): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-17 00:45:35.888: E/AndroidRuntime(305): FATAL EXCEPTION: main
04-17 00:45:35.888: E/AndroidRuntime(305): java.lang.RuntimeException: Unable to start activity ComponentInfo{directory.plus/directory.plus.Directory_finalActivity}: java.lang.NullPointerException
04-17 00:45:35.888: E/AndroidRuntime(305): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.os.Looper.loop(Looper.java:123)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 00:45:35.888: E/AndroidRuntime(305): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 00:45:35.888: E/AndroidRuntime(305): at java.lang.reflect.Method.invoke(Method.java:521)
04-17 00:45:35.888: E/AndroidRuntime(305): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 00:45:35.888: E/AndroidRuntime(305): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 00:45:35.888: E/AndroidRuntime(305): at dalvik.system.NativeStart.main(Native Method)
04-17 00:45:35.888: E/AndroidRuntime(305): Caused by: java.lang.NullPointerException
04-17 00:45:35.888: E/AndroidRuntime(305): at directory.plus.Directory_finalActivity.onCreate(Directory_finalActivity.java:59)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-17 00:45:35.888: E/AndroidRuntime(305): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
EDIT 2:
NEW LOGCAT OUTPUT:
04-17 01:26:12.899: E/JSON Parser(548): Error parsing data in JSONParser org.json.JSONException: Value <wddxPacket of type java.lang.String cannot be converted to JSONObject
04-17 01:26:12.899: D/AndroidRuntime(548): Shutting down VM
04-17 01:26:12.899: W/dalvikvm(548): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-17 01:26:12.919: E/AndroidRuntime(548): FATAL EXCEPTION: main
04-17 01:26:12.919: E/AndroidRuntime(548): java.lang.RuntimeException: Unable to start activity ComponentInfo{directory.plus/directory.plus.Directory_finalActivity}: java.lang.NullPointerException
04-17 01:26:12.919: E/AndroidRuntime(548): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.os.Looper.loop(Looper.java:123)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 01:26:12.919: E/AndroidRuntime(548): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 01:26:12.919: E/AndroidRuntime(548): at java.lang.reflect.Method.invoke(Method.java:521)
04-17 01:26:12.919: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 01:26:12.919: E/AndroidRuntime(548): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 01:26:12.919: E/AndroidRuntime(548): at dalvik.system.NativeStart.main(Native Method)
04-17 01:26:12.919: E/AndroidRuntime(548): Caused by: java.lang.NullPointerException
04-17 01:26:12.919: E/AndroidRuntime(548): at directory.plus.Directory_finalActivity.onCreate(Directory_finalActivity.java:59)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-17 01:26:12.919: E/AndroidRuntime(548): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-17 01:26:12.919: E/AndroidRuntime(548): ... 11 more
04-17 01:26:33.279: I/Process(548): Sending signal. PID: 548 SIG: 9
EDIT FINAL: Problem solved:
Needed to take a sub string of the result returned from the html and pass that into a json object
java.net.UnknownHostException: api.androidhive.info
It looks like your app can't access the network. Have you added:
<uses-permission
android:name="android.permission.INTERNET" />
to your code AndroidManifest.xml?
when testing my application in the emulator(I'm using Eclipse) it shows me "The application Counter(com.ian.counter) has stopped unexpectedly. Please try again." when running it. I've searched and searched for an answer but I've found none. Anyone know the problem?
Code:
package com.ian.counter;
import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
import android.widget.Toast;
public class CounterActivity extends Activity {
/** Called when the activity is first created. */
TextView textView1 = (TextView) this.findViewById(R.id.textView1);
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void Count(){
count ++;
textView1.setText(Integer.toString(count));
}
}
Logcat:
12-28 16:59:20.615: D/AndroidRuntime(353): Shutting down VM
12-28 16:59:20.686: W/dalvikvm(353): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-28 16:59:20.756: E/AndroidRuntime(353): FATAL EXCEPTION: main
12-28 16:59:20.756: E/AndroidRuntime(353): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ian.counter/com.ian.counter.CounterActivity}: java.lang.NullPointerException
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.os.Handler.dispatchMessage(Handler.java:99)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.os.Looper.loop(Looper.java:123)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.reflect.Method.invokeNative(Native Method)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.reflect.Method.invoke(Method.java:507)
12-28 16:59:20.756: E/AndroidRuntime(353): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-28 16:59:20.756: E/AndroidRuntime(353): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-28 16:59:20.756: E/AndroidRuntime(353): at dalvik.system.NativeStart.main(Native Method)
12-28 16:59:20.756: E/AndroidRuntime(353): Caused by: java.lang.NullPointerException
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.Activity.findViewById(Activity.java:1647)
12-28 16:59:20.756: E/AndroidRuntime(353): at com.ian.counter.CounterActivity.<init>(CounterActivity.java:10)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.Class.newInstanceImpl(Native Method)
12-28 16:59:20.756: E/AndroidRuntime(353): at java.lang.Class.newInstance(Class.java:1409)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-28 16:59:20.756: E/AndroidRuntime(353): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
Any help is appreciated.
You're trying to set the textView1 variable before the layout has been set. You need to define it as a variable and then assign it in onCreate() after you've called setContentView(). Like this:
package com.ian.counter;
import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;
import android.widget.Toast;
public class CounterActivity extends Activity {
/** Called when the activity is first created. */
TextView textView1;
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView) this.findViewById(R.id.textView1);
}
public void Count(){
count ++;
textView1.setText(Integer.toString(count));
}
}
Just copy and paste the above, that'll work just fine.
You should put this line
textView1 = (TextView) this.findViewById(R.id.textView1);
after
setContentView(R.layout.main);
and you just declare TextView in the begining
TextView textView1;
dont try to use findViewById(R.id.textView1); while declaraing instance variable as view does not exist at that point of time.
This is how your code should look like:
TextView textView1 = null;
int count = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textView1 = (TextView) findViewById(R.id.textView1);
}
public void Count(){
count ++;
textView1.setText(Integer.toString(count));
}