【问题标题】:Error in getActivity().runOnUiThreadnew Runnable()getActivity().runOnUiThreadnew Runnable() 中的错误
【发布时间】:2018-12-08 14:43:37
【问题描述】:

显示错误

致命异常:Timer-0 进程:com.example.tanis.myapplication,PID:9918 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.support.v4.app.FragmentActivity.runOnUiThread(java.lang.Runnable)” 在 com.example.tanis.myapplication.MenuItems.Home$Mytime.run(Home.java:158) 在 java.util.TimerThread.mainLoop(Timer.java:555) 在 java.util.TimerThread.run(Timer.java:505)

它在 getActivity().runOnUiThread(new Runnable() 中显示错误我不知道为什么会出现错误请帮助 谢谢

Home.java

package com.example.tanis.myapplication.MenuItems;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.tanis.myapplication.Adapters.CardItemString;
import com.example.tanis.myapplication.Adapters.CardPagerAdapterS;
import com.example.tanis.myapplication.Adapters.ViewPagerAdapter;
import com.example.tanis.myapplication.R;
import com.example.tanis.myapplication.Services.website_designing;

import java.util.Timer;
import java.util.TimerTask;
public class Home extends Fragment {


        ViewPager mViewPager;
        CardPagerAdapterS mCardAdapter;
        ShadowTransformer mCardShadowTransformer;



private Context context;
        ViewPager viewPager;


        String titlesText [] = {" Website Design", " Digital Marketing", " Domain Registration", "Graphics Design", " Mobile Apps", " Server Hosting",
        " Software Development", " Content Marketing", " Security (SSl)"};
        String  detailsArray [] = {
        "Your website is your digital home. We create, design, redesign, develop, improvise, and implement. We make beautiful websites",
        "We help your business reach potential customers on every possible digital device through all possible media channels    ",
        "To  launch  your  website  the  first  thing  you  need  is  the  domain  name.  You  can  choose  your  domain  name  with  us  here  ",
        "We  generate  creative  solutions  and  can  create  a  wide  range  of  graphic  for  your  clients  which  match  their  business         ",
        "We are mobile. And we make you mobile. We make responsive websites and mobile apps which compliment your business       ",
        "When  you  are  hosting  your     website  in  the  India  you   will  benefit  from  a      higher  ping  rate  and   lowest             latency              ",
        "Our team is competent at coding web apps with keen attention to detail & intuitive functionality that is high on design & creativity",
        "Content  is  the  heart  of  your  digital  presence. We  create  the right            content  with  the  right  focus   for   your  business",
        "Secure your site with the world's leading   provider of online security and get    these exclusive features at no added   cost",
        };
        int[] images = {R.drawable.website_design, R.drawable.digita,R.drawable.domain_registration,R.drawable.gric,
        R.drawable.mob,R.drawable.server,R.drawable.software_development,R.drawable.ontent,R.drawable.ssl};

private static final String KEY_MOVIE_TITLE = "key_title";

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

/**
 * Use this factory method to create a new instance of
 * this fragment.
 *
 * @return A new instance of fragment FragmentAction.
 */


@Override
public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);


        }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
        {


        View v = inflater.inflate(R.layout.home,container,false);
        TextView txt = (TextView)v.findViewById( R.id.textView12 );
        txt.setText("\u25BA Creative & Dedicated Team");
        TextView txt1 = (TextView)v.findViewById( R.id.textView13 );
        txt1.setText("\u25BA Affordable Cost");
        TextView txt2 = (TextView)v.findViewById( R.id.textView14 );
        txt2.setText("\u25BA Maintain Long Relationship");
        TextView txt3 = (TextView)v.findViewById( R.id.textView15 );
        txt3.setText("\u25BA Timely Deliverly ");

        context = this.getContext();

        Button b = (Button) v.findViewById( R.id.button7 ) ;
        b.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
        Intent intent=new Intent( getActivity(), website_designing.class);
        }
        } );


        mViewPager = (ViewPager)v.findViewById(R.id.viewpager1);

        mCardAdapter = new CardPagerAdapterS();




        for (int i=0; i<titlesText.length; i++){

        mCardAdapter.addCardItemS(new CardItemString( titlesText[i], detailsArray[i],images[i]));
        }

        mCardShadowTransformer = new ShadowTransformer(mViewPager, mCardAdapter);

        mViewPager.setAdapter(mCardAdapter);
        mViewPager.setPageTransformer(false, mCardShadowTransformer);
        mViewPager.setOffscreenPageLimit(3);



        viewPager = (ViewPager)v.findViewById( R.id.viewpager );
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter( this.getContext() );
        viewPager.setAdapter( viewPagerAdapter );

        Timer timer = new Timer(  );
        timer.scheduleAtFixedRate( new Mytime(),2000,4000 );



        FloatingActionButton floatingActionButton = (FloatingActionButton)v.findViewById( R.id.floatingActionButton );
        floatingActionButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
        startActivity( new Intent( getActivity(),Registration.class ) );
        }
        } );




        return v;

        }



public class Mytime extends TimerTask {
    @Override
    public void run() {

       //here it is showing me error//

           **getActivity().runOnUiThread( new Runnable() {
            @Override
            public void run() {

                if(viewPager.getCurrentItem() == 0) {
                    viewPager.setCurrentItem( 1 );
                }
                else if (viewPager.getCurrentItem()== 1){
                    viewPager.setCurrentItem( 2 );

                }
                else if (viewPager.getCurrentItem()== 2){
                    viewPager.setCurrentItem( 3 );

                }
                else if (viewPager.getCurrentItem()== 3){
                    viewPager.setCurrentItem( 4 );

                }
                else {
                    viewPager.setCurrentItem(0);
                }
            }
        } );
    }
}

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


    }


}

【问题讨论】:

  • 添加此检查if (getActivity()!=null)

标签: android


【解决方案1】:

java.lang.NullPointerException: 尝试调用虚方法 'void android.support.v4.app.FragmentActivity.runOnUiThread(java.lang.Runnable)'

NullPointerException 在应用程序尝试使用 具有 null 值的对象引用。

你应该在下面添加检查。

if (getActivity()!=null)

演示

   if (getActivity()!=null)
   {
    getActivity().runOnUiThread( new Runnable() {
            @Override
            public void run() {
            ......
   }

【讨论】:

    【解决方案2】:

    将上下文传递给线程,例如:

    new Mytime( getActivity() );
    

    现在在你的线程中,更改如下

    public class Mytime extends TimerTask {
    
        Context context;
        public Mytime(Context _context){
          context = _context;
        }
        @Override
        public void run() {
    
               context.runOnUiThread( new Runnable() {
        ............
    

    【讨论】:

      【解决方案3】:

      不要在内部类中使用getActivity()。只需在您的片段中创建一个字段:

      private Activity myActivity;
      

      然后在片段的onCreateView() 中初始化它,例如:

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState){
          myActivity = getActivity();
          //Your code
      }
      

      然后使用:

      myActivity.runOnUiThread()
      

      【讨论】:

        【解决方案4】:

        你可以在Fragment下面的步骤中使用它

        步骤-1

        Activity mActivity;
        @Override
        public void onAttach(Context context) {
          super.onAttach(context);
          mActivity = (Activity) context;
        }
        

        步骤-2

        public class Mytime extends TimerTask  {
                @Override
                public void run() {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // Your code here
                        }
                    });
                }
         }
        

        【讨论】:

          猜你喜欢
          • 2014-07-12
          • 2012-10-17
          • 2019-09-18
          • 1970-01-01
          • 2020-05-10
          • 2017-01-24
          • 1970-01-01
          • 1970-01-01
          • 2018-08-11
          相关资源
          最近更新 更多