【问题标题】:NullPointerException when setting text in fragment在片段中设置文本时出现 NullPointerException
【发布时间】:2016-08-16 10:14:32
【问题描述】:

我收到错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

尝试在片段中设置 textView 的文本时(在方法 changeText 中)

这是我的片段代码

public class MainFragment extends Fragment {

    String date;
    TextView infoText2;

    public MainFragment() {
        // Required empty public constructor
    }

    public Boolean daily;
    //instantiate variables

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootview = inflater.inflate(R.layout.fragment_main, container, false);

        infoText2 = (TextView) rootview.findViewById(R.id.infoText2);
        //TODO THIS COULD POSSIBLY BE A PROBLEM TOO

        //calls setdate function
        startup(rootview);
        btnClick(rootview);

        return rootview;
    }

    public void startup(View v) {
        date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
        //gets the current date

        TextView textView = (TextView) v.findViewById(R.id.infoText);
        textView.setText(date);
        //finds and replaces text in textView

        SeekBar seekBar = (SeekBar) v.findViewById(R.id.seekBar2);
        seekBar.setProgress(5);
        seekBar.setMax(10);
        //sets the seekbar progress

        //BEGIN CHECKING IF USER HAS ADDED ENTRY
        //TODO ADD IF ENTRY NOT COMPLETED STATEMENT
    }

    public void changeText(String mText) {
        //TODO FIX THIS PROBLEM
        infoText2.setText(mText);
        //runs getTheData method
    }

    public void btnClick(View v) {
        Button clickButton = (Button) v.findViewById(R.id.btnRate);
        clickButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(MainFragment.this.getActivity(), "Rating successful", Toast.LENGTH_SHORT).show();
                //conformation toast
                SeekBar seekBar = (SeekBar) MainFragment.this.getActivity().findViewById(R.id.seekBar2);
                seekBar.setEnabled(false);
                Button btnRate = (Button) MainFragment.this.getActivity().findViewById(R.id.btnRate);
                btnRate.setEnabled(false);
                //disable seekbar and button
                daily = true;
                //marks rating complete for the day
                //TODO reset complete back to false the next day
                int value = seekBar.getProgress();
                TextView ratingDisplay = (TextView) MainFragment.this.getActivity().findViewById(R.id.ratingText);
                ratingDisplay.setText("Rating: " + Integer.toString(value) + " out of 10");
                //sets the rating display to the value of the seekbar

                ((MainActivity) getActivity()).writeText(date, Integer.toString(value));
                //Runs writeText method

                ((MainActivity) getActivity()).getTheData();
            }
        });

这也是我的 MainActivity 中的代码

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

    NavigationView navigationView = null;
    Toolbar toolbar = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //sets the initial fragment
        MainFragment fragment = new MainFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

        //sets up the navigation drawer
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    /*public void rateOnClickListener(){
        Button btnNavigator = (Button)findViewById(R.id.btnRate);
        btnNavigator.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                MainFragment fragment = new MainFragment();
                MainFragment.rate(v);
                Toast.makeText(MainActivity.this, "yes", Toast.LENGTH_LONG);
            }
        });
    }*/

    //if the user presses the back button when the navdrawer is open
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")@Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            MainFragment fragment = new MainFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        } else if (id == R.id.nav_gallery) {
            SecondFragment fragment = new SecondFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void writeText(String timestamp, String rating) {
        String my_results = rating + ", " + timestamp + "\n";
        // String my results contains the date/time and the my_total score

        String file_name = "fresh_3";
        try {
            FileOutputStream fileOutputStream = openFileOutput(file_name, MODE_APPEND | MODE_PRIVATE);
            fileOutputStream.write(my_results.getBytes());
            fileOutputStream.close();
            Toast.makeText(getApplicationContext(), my_results + " success", Toast.LENGTH_LONG).show();

        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        //saves values to file
    }

    public void getTheData() {
        try {
            String Message;
            String myData;
            int i = 0;
            FileInputStream fileInputStream = openFileInput("fresh_3");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();

            while ((Message = bufferedReader.readLine()) != null) {
                stringBuilder.append(Message + "\n");
                i++; //counter for the array to sort the data
            }
            //put data in a string with lines
            fileInputStream.close();
            myData = stringBuilder.toString(); // old successful method to output - need to count the lines
            //instantiate the array
            String mylines[] = new String[i]; //assigning number of lines to new array as Java cannot make a indeterminate array
            mylines = myData.split("\\n");
            Arrays.sort(mylines, Collections.reverseOrder()); //sort the array in order of first character - reverse order - descending
            //remove the dodgy brackets and print the sorted data

            MainFragment mainFragment = new MainFragment();
            mainFragment.changeText(Arrays.toString(mylines).replaceAll("\\[|\\]", "")); //write the sorted data using regex (regular expression)
            //infoText2.setVisibility(View.VISIBLE);
            Toast.makeText(getApplicationContext(), "Number of records " + i, Toast.LENGTH_LONG).show(); //shows line number

        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

}

我已经尝试了各种方法来解决这个问题,包括findViewById 前面的getActivity() 和rootview.。我已将它们重新安排在不同的位置,但没有任何效果。

似乎除了.setText 之外的一切都在工作,但如果有人能告诉我为什么它拒绝合作,我将不胜感激。

【问题讨论】:

  • 能否请您出示您的fragment_main-XML?
  • 简单的原因可能是您的 TextView 对象为 null 可能是因为它未初始化或不存在于布局文件中。在调用setText方法之前请检查TextView是否被初始化。

标签: java android android-fragments nullpointerexception


【解决方案1】:

onCreateView 运行时,片段未附加到活动。为确保它正常工作,请在片段的 OnResume() 中调用所需的函数。

例如:

gridview_left = (GridView)getView().findViewById(R.id.gridview_left);

【讨论】:

  • 如果你能告诉我如何在这种情况下做到这一点,那将非常有帮助。不过还是谢谢你的回复:)
  • 实现片段的Override Onresume方法。就像你有你的 onCreateView 一样,而是写下这一行: infoText2 = (TextView)getview.findViewById(R.id.infoText2);在 OnResume() 方法中。这是我最好的猜测。
【解决方案2】:

确保fragment_main布局文件中存在带有@+id/infoText2的TextView。

【讨论】:

    【解决方案3】:

    尝试在 onActivityCreated() 中转移 btnClick(rootview) 调用...

    我认为该片段尚未附加到活动中

    【讨论】:

    • 我这样做了(我认为)并得到了这个错误 java.lang.RuntimeException: Unable to start activity ComponentInfo{au.com.alexh.dayrater/au.com.alexh.dayrater.MainActivity}: android.support.v4.app.SuperNotCalledException: Fragment MainFragment{f00e10e #0 id=0x7f0c006c} 没有调用到 super.onActivityCreated() 原因:android.support.v4.app.SuperNotCalledException: Fragment MainFragment{f00e10e #0 id =0x7f0c006c} 没有调用 super.onActivityCreated()
    • 之后调用 btnClick(rootview)
    • 超级调用始终是第一行...只有在那之后你才能调用其他东西:)
    【解决方案4】:
    MainFragment mainFragment = new MainFragment();
    mainFragment.changeText(Arrays.toString(mylines).replaceAll("\\[|\\]", ""));
    

    当您在此处调用片段上的方法时,没有运行任何片段生命周期方法,例如 onCreateView()。您需要等待片段交易被执行。

    更好的主意是使用参数Bundle 将参数传递给您的片段,并在生命周期方法中读取片段本身中的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-19
      • 2013-08-08
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多