Access another class via threads in Android Studio?

2

Hello I have a project in android studio which saves the user's location (longitude and latitude), for this I have created a series of methods in a single Activity, now what I need is that when the user changes activity I follow saving the location, I created a thread in another activity to call the method where the location is saved in the other Activity but it shows me a null error. Here I leave the thread code:

public class Activity2 extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
   
    Activity1 x;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x=new Activity1();
        time time=new time();
        ejecutar();
    }
    
    public void hilo(){
        Thread t=new Thread();
        try{
            Thread.sleep(600000);
        }catch (Exception e){
            e.printStackTrace();
        }
        t.start();
    }

    public void ejecutar(){
        x.GuardarUbicacion();//aqui manda el error
        time time=new time();
        time.execute();
    }

    public class time extends AsyncTask <Void, Integer,Boolean>{

        @Override
        protected Boolean doInBackground(Void... voids) {
            hilo();
            return true;
        }

        @Override
        public void onPostExecute(Boolean aBoolean){
            ejecutar();
            Toast.makeText(Activity2.this, "La ubicacion se guarda cada 10min", Toast.LENGTH_SHORT).show();
        }
    }

Error: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper ()' on a null object reference

    
asked by Geek 13.08.2018 в 20:00
source

1 answer

0

The problem is that you have to wait for the Interface thread (UI) of the main activity (the methods must be synchronized). You can modify the SaveLocation method in this way:

public void GuardarUbicacion(new Runnable() {
    public void run() {
       // Tu codigo aqui
    }
});

Remember to also use the correct context with "getContext ()" in the main activity.

    
answered by 14.08.2018 в 06:39