2014-04-09 2 views
0

내 코드와 XML을 모두 찾으십시오. 내 문제는 스피너 (코드 spinner1에서) 내가 결정할 수없는 몇 가지 이유로 null이며 실행하는 데 실패한 응용 프로그램 이외의 오류가 발생하지 않습니다. 어떤 도움을 주시면 감사하겠습니다!Android 스피너 onselecteditem 회 전자가 null입니까? 아래 코드

activity_main.xml :

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/pager" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/black" 
    tools:context=".MainActivity" /> 

MainActivity.java :

package com.example.passwordplayground; 

import java.util.Locale; 

import com.example.MyApplication.EncryptionSpinner; 
import com.example.MyApplication.MyApplication; 

import android.app.ActionBar; 
import android.app.Activity; 
import android.app.FragmentTransaction; 
import android.content.Context; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import android.support.v4.app.NavUtils; 
import android.support.v4.view.ViewPager; 
import android.view.Gravity; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.Spinner; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends FragmentActivity implements 
     ActionBar.TabListener { 

    /** 
    * The {@link android.support.v4.view.PagerAdapter} that will provide 
    * fragments for each of the sections. We use a 
    * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which 
    * will keep every loaded fragment in memory. If this becomes too memory 
    * intensive, it may be best to switch to a 
    * {@link android.support.v4.app.FragmentStatePagerAdapter}. 
    */ 
    SectionsPagerAdapter mSectionsPagerAdapter; 

    /** 
    * The {@link ViewPager} that will host the section contents. 
    */ 
    ViewPager mViewPager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // Set up the action bar. 
     final ActionBar actionBar = getActionBar(); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 
     Spinner spinner1 = (Spinner) findViewById(R.id.encryptionSpin); 
     if (spinner1 == null) 
      System.out.println("Spinner1 is null"); 
     else 
      System.out.println("Funcion is null"); 
     spinner1.setOnItemSelectedListener(new EncryptionSpinner()); 

     // Create the adapter that will return a fragment for each of the three 
     // primary sections of the app. 
     mSectionsPagerAdapter = new SectionsPagerAdapter(
       getSupportFragmentManager()); 

     // Set up the ViewPager with the sections adapter. 
     mViewPager = (ViewPager) findViewById(R.id.pager); 
     mViewPager.setAdapter(mSectionsPagerAdapter); 

     // When swiping between different sections, select the corresponding 
     // tab. We can also use ActionBar.Tab#select() to do this if we have 
     // a reference to the Tab. 
     mViewPager 
       .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
        @Override 
        public void onPageSelected(int position) { 
         actionBar.setSelectedNavigationItem(position); 
        } 
       }); 

     // For each of the sections in the app, add a tab to the action bar. 
     for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { 
      // Create a tab with text corresponding to the page title defined by 
      // the adapter. Also specify this Activity object, which implements 
      // the TabListener interface, as the callback (listener) for when 
      // this tab is selected. 
      actionBar.addTab(actionBar.newTab() 
        .setText(mSectionsPagerAdapter.getPageTitle(i)) 
        .setTabListener(this)); 
     } 
    } 

    @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 void onTabSelected(ActionBar.Tab tab, 
      FragmentTransaction fragmentTransaction) { 
     // When the given tab is selected, switch to the corresponding page in 
     // the ViewPager. 
     mViewPager.setCurrentItem(tab.getPosition()); 
    } 

    @Override 
    public void onTabUnselected(ActionBar.Tab tab, 
      FragmentTransaction fragmentTransaction) { 
    } 

    @Override 
    public void onTabReselected(ActionBar.Tab tab, 
      FragmentTransaction fragmentTransaction) { 
    } 

    /** 
    * A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
    * one of the sections/tabs/pages. 
    */ 
    public class SectionsPagerAdapter extends FragmentPagerAdapter { 

     public SectionsPagerAdapter(FragmentManager fm) { 
      super(fm); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      // getItem is called to instantiate the fragment for the given page. 
      // Return a DummySectionFragment (defined as a static inner class 
      // below) with the page number as its lone argument. 
      Fragment fragment = new DummySectionFragment(); 
      Bundle args = new Bundle(); 
      args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); 
      fragment.setArguments(args); 
      return fragment; 
     } 

     @Override 
     public int getCount() { 
      // Show 4 total pages. 
      return 4; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      Locale l = Locale.getDefault(); 
      switch (position) { 
      case 0: 
       return getString(R.string.title_section1).toUpperCase(l); 
      case 1: 
       return getString(R.string.title_section2).toUpperCase(l); 
      case 2: 
       return getString(R.string.title_section3).toUpperCase(l); 
      case 3: 
       return ("Practicality").toUpperCase(); 
      } 
      return null; 
     } 
    } 

    /** 
    * A dummy fragment representing a section of the app, but that simply 
    * displays dummy text. 
    */ 
    public static class DummySectionFragment extends Fragment { 
     /** 
     * The fragment argument representing the section number for this 
     * fragment. 
     */ 
     public static final String ARG_SECTION_NUMBER = "section_number"; 

     public DummySectionFragment() { 
     } 
     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = null; 
      if (getArguments().getInt(ARG_SECTION_NUMBER)==1) { 
       rootView = inflater.inflate(R.layout.encryption,container, false); 
      } 
      else if (getArguments().getInt(ARG_SECTION_NUMBER)==2) { 
       rootView = inflater.inflate(R.layout.fragment_main_dummy, 
         container, false); 
       TextView dummyTextView = (TextView) rootView 
         .findViewById(R.id.section_label); 
       dummyTextView.setText("I'm second!"); 
      } 
      else if (getArguments().getInt(ARG_SECTION_NUMBER)==3) { 
       //dummyTextView.setText("I'm third"); 
      } 
      else if (getArguments().getInt(ARG_SECTION_NUMBER)==4) { 
       //dummyTextView.setText("I'm fourth and last!"); 
      } 
      return rootView; 
     } 
    } 

} 

encryption.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:android1="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity$Encryption" > 

    <Spinner 
     android1:id="@+id/encryptionSpin" 
     android1:layout_width="fill_parent" 
     android1:layout_height="wrap_content" 
     android1:layout_alignParentTop="true" 
     android1:layout_centerHorizontal="true" 
     android1:layout_marginTop="14dp" 
     android1:background="@color/orange" 
     android1:entries="@array/cryptArray" /> 

</RelativeLayout> 

EncryptionSpinner.java :

package com.example.MyApplication; 

import android.view.View; 
import android.widget.AdapterView; 
import android.widget.Toast; 
import android.widget.AdapterView.OnItemSelectedListener; 

public class EncryptionSpinner implements OnItemSelectedListener { 

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
     // An item was selected. You can retrieve the selected item using 
     // parent.getItemAtPosition(pos) 
     Toast toast = Toast.makeText(MyApplication.getAppContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG); 
     toast.show(); 
     System.out.println(parent.getItemAtPosition(pos).toString()); 
    } 

    public void onNothingSelected(AdapterView<?> parent) { 
     // Another interface callback 
    } 
} 
,

로그 캣 오류 :

04-09 01:16:28.637: I/System.out(1440): Spinner1 is null 
04-09 01:16:28.657: D/AndroidRuntime(1440): Shutting down VM 
04-09 01:16:28.657: W/dalvikvm(1440): threadid=1: thread exiting with uncaught exception (group=0x414c4700) 
04-09 01:16:28.692: E/AndroidRuntime(1440): FATAL EXCEPTION: main 
04-09 01:16:28.692: E/AndroidRuntime(1440): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.passwordplayground/com.example.passwordplayground.MainActivity}: java.lang.NullPointerException 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.ActivityThread.access$600(ActivityThread.java:141) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.os.Handler.dispatchMessage(Handler.java:99) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.os.Looper.loop(Looper.java:137) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.ActivityThread.main(ActivityThread.java:5103) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at java.lang.reflect.Method.invokeNative(Native Method) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at java.lang.reflect.Method.invoke(Method.java:525) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at dalvik.system.NativeStart.main(Native Method) 
04-09 01:16:28.692: E/AndroidRuntime(1440): Caused by: java.lang.NullPointerException 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at com.example.passwordplayground.MainActivity.onCreate(MainActivity.java:65) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.Activity.performCreate(Activity.java:5133) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175) 
04-09 01:16:28.692: E/AndroidRuntime(1440):  ... 11 more 

레이아웃 '구이 : 다음 activity_main 당신이 지금이 아니 자신하고에 있기 때문에 해당 파일에 넣어 가지고에서 당신이 사용자 회 원한다면 layouta_main vs encryption

+0

너는 spinner .. – Riser

+0

에 값을 지정하지 않거나 해당 ID가 레이아웃 파일과 일치하지 않습니다. – Riser

+0

'MyApplication.getAppContext()'대신'view.getContext()'를 시도해 보셨습니까? –

답변

0

encryption.xml 파일.

메이크업의 activity_main.xml 아래와 같이 :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:android1="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity$Encryption" > 

<android.support.v4.view.ViewPager 

    android:id="@+id/pager" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@color/black" 
    tools:context=".MainActivity" /> 

    <Spinner 
     android1:id="@+id/encryptionSpin" 
     android1:layout_width="fill_parent" 
     android1:layout_height="wrap_content" 
     android1:layout_alignParentTop="true" 
     android1:layout_centerHorizontal="true" 
     android1:layout_marginTop="14dp" 
     android1:background="@color/orange" 
     android1:entries="@array/cryptArray" /> 

</RelativeLayout> 
+0

솔루션을 시도했지만 변수 자체가 여전히 null입니다. – Kyle

+0

activity_main xml 파일도 있습니까? – Riser

+0

예, 질문을 포함하도록 업데이트되었습니다. \ – Kyle

0

당신은 당신의 활동 레이아웃 activity_main을 팽창하고 당신은 당신의 activity_main 레이아웃에없는 Spinner에 액세스하려고합니다.

오류가 발생했습니다. Spinneractivity_main 레이아웃에 없습니다. 당신이 널 포인터 예외가 볼

public static class DummySectionFragment extends Fragment { 

    public static final String ARG_SECTION_NUMBER = "section_number"; 

    public DummySectionFragment() { 
    } 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = null; 
     if (getArguments().getInt(ARG_SECTION_NUMBER)==1) { 
      rootView = inflater.inflate(R.layout.encryption,container, false); 
       Spinner spinner1 = (Spinner)rootView.findViewById(R.id.encryptionSpin); 
     } 
+0

라인을 변경 한 경우 setContentView (R.layout.activity_main); onContentView (R.layout.encryption)에 대한 onCreate 함수에서; 문제를 해결할 수 있을까요? 내 조각 탭 코드에 따르면, 그것은 tabl의로드 중 infalted이므로 어쨌든 거기에 가야하지만. – Kyle

+0

업데이트 된 답변을 확인하십시오. – GrIsHu

+0

좋아, 제안한 코드를 추가했는데 이제 68 행에 널 포인터가 생겼다. mViewPager.setAdapter (mSectionsPagerAdapter); 그래서 내 추측은 그 기능에 추가 된 것을 좋아하지 않는다는 것입니다. – Kyle

0

:

그래서 다음과 같이 당신의 SpinneronCreateViewDummySectionFragment의 방법을 초기화해야합니다. 은 사용중인 구성 요소를 제어 할 수 없다는 것을 의미합니다. 이는 두 가지 이유 ( )로 인해 발생할 수 있습니다. 1. 두 구성 요소의 ID가 동일합니다. 2. 정의 된 레이아웃이 잘못되었습니다. 레이아웃 이름이 레이아웃의 이름

R.layout.encryption 

변화에게 그리고 당신은 갈 준비하는 동안 귀하의 경우

당신은 레이아웃

R.layout.activity_main 

을 사용하고 있습니다.

+0

의견을 주셔서 감사합니다. 이제 setContentView (R.layout.encryption);로 변경했습니다. 그러나 불행히도 나는 onCreate에 있던 오류를 여전히 남겨 두었습니다. 어떤 사람들은 그것을 조각으로 옮길 것을 제안했는데, 다른 선에서 다른 널 오류가 발생했습니다. – Kyle

0

콘텐츠 뷰를 xml 중 하나로 설정하면 activity_mail 레이아웃에 ViewPager를 넣고 encryption.xml에 Spinner를 넣습니다. 그래서 어느 누구도 다른 사람을 식별 할 수 없습니다. null 포인터 예외가 throw됩니다.

R.layout.activity_main 갖는 ViewPager

R.layout.Spinner를 갖는 암호화

setcontentView(R.layout.activity_main)을 설정하면 findViewById(R.id.encryptionSpin); 라인은 널 포인터를 던집니다.

setcontentView(R.layout.encryption)을 설정하면 mViewPager = (ViewPager) findViewById(R.id.pager); 라인이 널 포인터를 발생시킵니다.

+0

좋아, 그럼 어떻게해야합니까? – Kyle

+0

@Kyle은 두 개의 뷰를 하나의 XML로 저장하고 setContentView()에서 xml을 설정합니다. – Yuvaraja

+0

다른 탭이 포함 된 레이아웃을 호출하는 기본 레이아웃은 하나 (적어도 모르는 방법)는 불가능합니다. 그것은 프로젝트 생성 과정에서 sdk 자체에 의해 자동 생성되었습니다. – Kyle