java.lang.NullPointerException at Intent - java

I am quite new to Java and Android programming, and just working on my 3rd App - however I am encountering a Problem which I am not able to solve (I already tried and researched for days).
I have a list of Elements in a LinearLayout inside a Fragment - the Elements have a OnLongClickListener attached, with a popup showing up when the User long-presses the Element. That works fine. However, one of the Buttons in the Popup is "Edit", and when a user presses this Button, I want to start another Activity with Editing Options for this Element.
So there comes my Problem: when I want to start the new Activity with an Intent, I get following Error:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.Activity.startActivityForResult(Activity.java:3370)
at android.app.Activity.startActivityForResult(Activity.java:3331)
at android.app.Activity.startActivity(Activity.java:3566)
at android.app.Activity.startActivity(Activity.java:3534)
at at.fekle.zipmanager.start.startzipinfo(start.java:299)
at at.fekle.zipmanager.start$2.onLongClick(start.java:277)
at android.view.View.performLongClick(View.java:4247)
at android.view.View$CheckForLongPress.run(View.java:17341)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
But, if i start the same Activity with the same Intent from a simple Button defined in the Layout, the Activity Starts fine without any Errors... weird, isn't it?
So, does anyone have an Idea how I can solve this problem?
Here are some extractions from my code:
The Creation of the Elements with the OnLongClickListener:
ScrollView parent = (ScrollView) maininflater.inflate(R.layout.start_ziplist_fragment_superwrapper, null, false);
inf = maininflater;
LinearLayout ll = (LinearLayout) maininflater.inflate(R.layout.start_ziplist_fragment_wrapper, parent, false);
for (Integer i = 0; i < count; i++) {
ArrayList<String> data = new DB(cont).getAllZips().get(i);
View custom = maininflater.inflate(R.layout.start_ziplist_fragment_inner, ll, false);
TextView tv = (TextView) custom.findViewById(R.id.ziplist_name);
TextView tv2 = (TextView) custom.findViewById(R.id.ziplist_text);
tv.setText(data.get(2));
tv2.setText(data.get(1));
Integer id = Integer.valueOf(data.get(0));
custom.setId(id);
custom.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Integer id = view.getId();
startzipinfo(id);
return true;
}
});
ll.addView(custom);
}
parent.addView(ll);
The void which starts the Activity:
public void startzipinfo(Integer id){
Intent in = new Intent(getApplicationContext(), zipinfo.class);
startActivity(in);
}
I'm looking forward to your Answers,
Felix
EDIT: This is the Activity which is about to be started:
package at.fekle.zipmanager;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by felix on 27.06.13.
*/
public class zipinfo extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zipinfo);
}
}

Try to use YourActivityName.this instead of getApplicationContext() :
public void startzipinfo(Integer id){
Intent in = new Intent(YourActivityName.this, zipinfo.class);
startActivity(in);
}

Check whether your new intent class is mentioned in android manifest file if it does not exists then type:<activity name=".YourClassName>
</activity>

I just solved the problem!
I had to start the activity from the parent Fragment (passed to the method by the FragmentManager) - now everything works like a charm :)
custom.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Integer id = view.getId();
id = 2;
Intent intent = new Intent(cont, zipinfo.class);
fragment.startActivity(intent);
return true;
}
});
Thanks for all answers!
Cheers,
Felix

Related

App Crashe with log error Resources$NotFoundException: Resource ID #0x0 on using AlertDialog inside ListviewAdapter

I'm creating an app with one Mainactivity and two class. It contains Listview adapter to show list of name with images and details. when click upon any image ...Alert Dialog Box will pop up and from option ,i want user could able to call or send email.
Earlier I used the code for Mainactivity class and it pretty much works but with ListviewAdapter it crashes.
Here is my Class
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
public ListViewAdapter(Context context,
List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position)
.getPopulation());
// Set the results into ImageView
holder.flag.setImageResource(worldpopulationlist.get(position)
.getFlag());
final String email = worldpopulationlist.get(position).getRank().toString();
final String phone = worldpopulationlist.get(position).getCountry().toString();
// Listen for ListView Item Click
final View finalView = view;
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
CharSequence options[] = new CharSequence[]{"Email", "Call"};
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
mContext.startActivity(Intent.createChooser(intent, ""));
}
if(i == 1){
Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phone));
// callIntent.setData(Uri.parse("tel:"+uri));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(callIntent);
}
}
});
builder.show();
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
and error log is
Process: com.nepalpolice.test, PID: 30475
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.Resources.getValue(Resources.java:1123)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2309)
at android.content.res.Resources.getLayout(Resources.java:939)
at android.view.LayoutInflater.inflate(LayoutInflater.java:395)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AlertController$AlertParams.createListView(AlertController.java:988)
at android.support.v7.app.AlertController$AlertParams.apply(AlertController.java:964)
at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:981)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:1005)
at com.nepalpolice.test.ListViewAdapter$1.onClick(ListViewAdapter.java:125)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5018)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Please help.
Thanks in advance.
Android has its normal classes, like AlertDialog, and then it has support versions of some of those classes, one being AlertDialog. This is to provide backwards compatibility with older Android versions that may not have these classes natively. However it can get confusing sometimes.
The tutorial you linked is using an Activity and the normal AlertDialog. However, you are using an Activity and the support AlertDialog. This won't work. AlertDialog depends on a theme or style to know what it should make itself look like. Since you're using a normal Activity, the support AlertDialog is unable to infer what it should look like because Activity doesn't use support package themes.
There are a few things you can do to fix this.
The simplest way to fix this would be to just change from using the support AlertDialog to using the native one. Delete import android.support.v7.app.AlertDialog; from your Adapter class and then reimport the AlertDialog, making sure you don't import the support version again.
The second simplest way would be to follow this answer and add a specific AppCompat theme for your AlertDialog. However, this won't fix any future issues you may run into by mixing AppCompat and normal classes.
The most involved (but also most compatible) way of fixing this is to convert to using AppCompatActivity. You'll have to change your Activity to extend AppCompatActivity instead, and also change your theme (in styles.xml) to have a parent of Theme.AppCompat.Light (remove .Light if you want a dark theme).

Nullpointerexception because of measuring time?

I want to measure the time between first button click and third button click. The code itself works fine, bur when I click the Button the 3rd time on my device, I'm getting a nullpointerexception.
why?
here's the code:
public class Game extends Activity implements OnClickListener{
Button start_time;
int i = 0;
TextView textview1;
Button RelativeLayout;
Button gameover;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// RelativeLayout.setClickable(true);
setContentView(R.layout.activity_game);
start_time = (Button) findViewById(R.id.start_time);
start_time.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
gameover = (Button) findViewById(R.id.gameover);
gameover.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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);
}
#Override
public void onClick(View v) {
textview1 = (TextView) findViewById(R.id.textView1);
Random r = new Random();
RelativeLayout decorView = (RelativeLayout) start_time.getParent();
int screenWidth = decorView.getWidth();
int screenHeight = decorView.getHeight();
long startTime = SystemClock.elapsedRealtime();
i++;
if (i == 1 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 2 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 3 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 4 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 5 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
if (i == 6 ) {
start_time.setX(r.nextInt(screenWidth - start_time.getWidth()));
start_time.setY(r.nextInt(screenHeight - start_time.getHeight()));
}
else if (i == 7) {
long difference = SystemClock.elapsedRealtime() - startTime;
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
// textview1.setText(intent.getStringExtra("time"));
// textview1.setText(String.valueOf(difference));
finish();
}
}
}
and the mainactivity :
public class MainScreen extends Activity implements OnClickListener {
Button btn_start;
TextView textview1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
btn_start = (Button) findViewById(R.id.btn_start);
btn_start.setOnClickListener(this);
textview1 = (TextView) findViewById(R.id.textView1);
}
#Override
public void onClick(View v) {
startActivityForResult(new Intent(this,Game.class), 0);
textview1.setText(getIntent().getStringExtra("time"));
}
}
logcat:
03-09 16:08:10.760: E/AndroidRuntime(6372): FATAL EXCEPTION: main
03-09 16:08:10.760: E/AndroidRuntime(6372): Process: ch.frozensparks.asdf, PID: 6372
03-09 16:08:10.760: E/AndroidRuntime(6372): java.lang.NullPointerException
03-09 16:08:10.760: E/AndroidRuntime(6372): at ch.frozensparks.bftjh.Game.onClick(Game.java:118)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.view.View.performClick(View.java:4470)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.view.View$PerformClick.run(View.java:18593)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.os.Handler.handleCallback(Handler.java:733)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.os.Handler.dispatchMessage(Handler.java:95)
03-09 16:08:10.760: E/AndroidRuntime(6372): at android.os.Looper.loop(Looper.java:157)
The exception is occuring on this line
textview1.setText(getIntent().getStringExtra("time"));
You are trying to getIntent from the current activity but passing to new intent object here
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time",difference);
(First of all, I'm assuming that the code at the top of your post is part of Game.class.)
Ok I think you're misunderstanding how intents function.
Intent intent = new Intent(Game.this, MainScreen.class);
intent.putExtra("time", difference);
Here you're creating a new intent (called 'intent') and putting the value 'difference' with the key 'time' inside it.
Then
textview1.setText(getIntent().getStringExtra("time"));
Here you're trying to access that value -- but you're actually accessing a completely different intent object. By using getIntent() you're accessing the intent object used to start the current activity, not the one you defined above it. (Also you're attempting to get a String extra from the intent, but you're storing a long.)
If you want to access that intent object, simply use:
intent.getStringExtra("time");
So your line would be:
textview1.setText(intent.getStringExtra("time"));
But instead I would just do this:
textview1.setText(String.valueOf(difference));
Last thing, I can't be sure where you're defining textview1 in the top chunk of code, but if you're trying to refer to the textview1 that is a part of MainScreen that could be causing your problem, so you may have to make it public or pass the difference variable back and set the text in MainScreen.
You need to finish yoir MainScreen Activity when navigating to Game.
MainScreen.this.finish(); in onClick method of MainScreen.
Also you need to start the activity in onclick of game activity
startActivity(intent)

I can't find the error causing a null pointer exception

I am new to android programming and I am trying to create a simple home screen replacement/launcher using a viewpager.
When I try to run the application, it starts up and then immediately force closes. I think it is something to do with a null pointer exception but I am really new to programming and can't find the source of the error.
This is my logcat.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dntmdp.matthewhuckel.simplephonelauncher/com.dntmdp.matthewhuckel.simplephonelauncher.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
// etc...
Caused by: java.lang.NullPointerException
at com.dntmdp.matthewhuckel.simplephonelauncher.MainActivity.onCreate(MainActivity.java:47)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            // etc...
08-13 20:10:58.585 1805-1805/com.dntmdp.matthewhuckel.simplephonelauncher I/Process﹕ Sending signal. PID: 1805 SIG: 9
This is my main activity java class.
public class MainActivity extends ActionBarActivity {
Button phone;
// more buttons
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton phone = (ImageButton) findViewById(R.id.imageButton);
phone.setOnClickListener(new View.OnClickListener() { // Exception thrown on this line
#Override
public void onClick(View view) {
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.android.phone");
startActivity(LaunchIntent);
}
});
//setting more onclicklisteners in exactly the same manner
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.viewpager_layout);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
// menu initialization
}
I found the answer. I was trying to find the image button id's in the activity_main xml, but they were in other activities.

Error on displaying int value | Android

I'm trying to follow the video series on YouTube by "The New Boston".
I'm getting an error when trying to display a variable on a toast.
Heres' what I did..
First off, I created a textView..
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/CountView"
android:text="Number Value is 0"
/>
Then,
public class MainActivity extends ActionBarActivity {
int Counter;
TextView countView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Counter = 0;
countView= (TextView)findViewById(R.id.CountView);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void Button1Click(View view) {
Counter+=1;
Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
countView.setText(String.valueOf(Counter));
}
It says that the program has stopped working. LogCat Log ->
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3606)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17446)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
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:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3601)
... 11 more
Caused by: java.lang.NullPointerException
at com.BreadApplications.program1.MainActivity.Button1Click(MainActivity.java:36)
... 14 more
I just started learning Android.. Any help?
Try this:
Toast.makeText(this, ""+Counter, Toast.LENGTH_SHORT).show();//auto type conversion really convinent
You pass integer value in the toast parameter; that is the error. You have to remember that you just pass String value in the Toast parameter so make the Integer value into String and then show this value by using Toast. See this example:
public void Button1Click(View v){
Counter+=1;
Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
//convering integer value to String
Toast.makeText(this, Counter+"", Toast.LENGTH_SHORT).show();
}
Change to
Toast.makeText(this, String.valueOf(Counter), Toast.LENGTH_SHORT).show();
Counter is a int value ( should be named according to java naming conventions. c should be small not ins caps).
It looks for resource with the id if not found you get ResourceNotFoundException. There is one that takes int which is a resource id.
What you want is the one that takes CharacterSequence. If you look at the docs the second param is a CharacterSequence. So use String.valueOf(intvlaue)
public static Toast makeText (Context context, CharSequence text, int duration)
Added in API level 1
Make a standard toast that just contains a text view.
Parameters
context The context to use. Usually your Application or Activity object.
text The text to show. Can be formatted text.
duration How long to display the message. Either LENGTH_SHORT or LENGTH_LONG
Edit:
To the Edited post
The views belong to the fragment. So you initialize views in onCreateView of Fragment using rootView.findViewById
Or if you set fragment_main.xmlto activity get rid of the if block and the fragment related code.
Your tutorial seems to be outdated. Follow
NullPointerException accessing views in onCreate()
Edit 2:
Get rid of android:onClick="Button1Click" in fragment_main.xml for button
Remove
public void Button1Click(View view) {
Counter+=1;
Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
countView.setText(String.valueOf(Counter));
}
Then in Fragment
public static class PlaceholderFragment extends Fragment {
TextView countView;
int Countter;
public PlaceholderFragment() {
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView countView = (TextView)(TrootView.findViewById(R.id.CountView);
Button button = (TextView)(TrootView.findViewById(R.id.buttonid);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Counter+=1;
Toast.makeText(getActivity(), "Added 1", Toast.LENGTH_SHORT).show();
countView.setText(String.valueOf(Counter));
}
});
return rootView; }
}
}
The method makeText of the class Toast is overloaded.
makeText(Context context, int resId, int duration)
makeText(Context context, CharSequence text, int duration)
You are using the first method because you are passing a int value as the second parameter. This method is searching for a resource id with the value of your counter and a resource not found exception is being thrown.
the solution is to make a cast to the integer value to String to invoke the correct makeTest method.
Toast.makeText(this, Integer.toString(Counter), Toast.LENGTH_SHORT).show();
You are using makeText (Context context, int resId, int duration) of Toast.In this function the resId should be the resource id of the string resource to use,But you pass just simple integer number.So it gives runtimeerror
So,Try below code
public void Button1Click(View view) {
Counter+=1;
Toast.makeText(YourActivity.this, "Added 1", Toast.LENGTH_SHORT).show();
//countView.setText(""+Counter);
Toast.makeText(YourActivity.this, String.valueOf(Counter), Toast.LENGTH_SHORT).show();
}

Can't use Spinner in android app

I have a spinner in my android app and I can get it to show but the sec. I click it, the app crashes and throws :
Unable to add Window -- token android.view.ViewRootImpl$Wfb# is not valid: is your activity running?
The layout is simple. I have an activity that has a list and a button to add something to the list. When clicked, the add button open a popup window that displays the spinner, a text box and a button. Everything works fine till I click the spinner .
Now I've searched google for an hour and found these:
Android - Dynamically Adding values to Spinners
BadTokenException Unable to add Window Spinner in PopUpWindow
Android Spinner Error : android.view.WindowManager$BadTokenException: Unable to add window
and more. They all seem to point to the context, however I've tried everything from using "this", to getApplicationContext, to the name of my activity.context and none of it works. I tried using the answer someone provided twice instead of just setting the contentView to the page and that made things worse (the app crashed with a null pointer exception right away).
Here's the code for the popup window (executed when the "add" button is clicked):
public void add_itinerary_clicked(View view)
{
LayoutInflater i = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = i.inflate(R.layout.itinerary_add_item_page, null);
popup = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
popup.showAtLocation(popupView , Gravity.CENTER, 0, 0);
Spinner airlineChoice = (Spinner) popupView.findViewById(R.id.airlineSpinner);
Button addBtn= (Button) popupView.findViewById(R.id.finish_addItinerary);
String[] list = new String[1];
list = airlineMap.keySet().toArray(list);
ArrayAdapter<CharSequence> spinnerAdapter = new ArrayAdapter<CharSequence>(getApplicationContext(), android.R.layout.simple_spinner_item, list );
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
airlineChoice.setAdapter(spinnerAdapter);
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish_addItinerary_clicked();
popup.dismiss();
}
});
}
I'm completely at a loss at this point. If it's not the context (I've tried what others have said) then what is it?
Here's the complete error message:
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#40de1700 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:567)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:993)
at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:899)
at android.widget.ListPopupWindow.show(ListPopupWindow.java:603)
at android.widget.Spinner$DropdownPopup.show(Spinner.java:981)
at android.widget.Spinner.performClick(Spinner.java:609)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I think you should not be using the application context, but the activity context.
Use a dialog and not a popup. It's easier, less code to maintain, and the standard according to Google.
I think there needs to be some sort of click listener on the spinner.
Thanks to Buggie, I have found a work around. I'm using a dialog instead. It works and doesn't throw an error. I'm not sure why this works and a popup window doesn't but here's my code that works:
public void add_itinerary_clicked(View view)
{
dialog = new Dialog(this);
dialog.setContentView(R.layout.itinerary_add_item_page);
Spinner airlineChoice = (Spinner) dialog.findViewById(R.id.airlineSpinner);
Button addBtn= (Button) dialog.findViewById(R.id.finish_addItinerary);
String[] list = new String[1];
list = airlineMap.keySet().toArray(list);
ArrayAdapter<CharSequence> spinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, list );
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
airlineChoice.setAdapter(spinnerAdapter);
airlineChoice.setOnItemSelectedListener(this);
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish_addItinerary_clicked();
dialog.dismiss();
}
});
dialog.show();
}
One thing you might try is using your activity context, rather than your application/base context. This might help the situation.

Categories