0

I am trying to use adapter from my LocationsFragment.class into my DeviceAdmin.class to add two Strings say mylatitude and mylongitude to my ListView. I am going through Constructor Method. But it seems to return null, whenever I call adapter.add(mylatitude + " " + mylongitude); in my DeviceAdmin.class

  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.add(java.lang.Object)' on a null object reference
        at com.ayush.trixter.ui.captures.DeviceAdmin$1.onLocationChanged(DeviceAdmin.java:103)

Line 103 is : adapter.add("Latitude: " + mylat + "Longitude: " + mylon);

DeviceAdmin.class


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Looper;
import android.os.UserHandle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.ContextThemeWrapper;
import android.view.Surface;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.PermissionChecker;

import com.ayush.trixter.R;
import com.ayush.trixter.ui.locations.LocationFragment;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class DeviceAdmin extends DeviceAdminReceiver
{
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    public CameraManager cam;
    LocationManager locationManager;
    final String TAG = "[Trixter]";
    DevicePolicyManager mgr;
    FirebaseDatabase db;
    public boolean mTracking = false;
    public ArrayList<String> listItems=new ArrayList<>();
    LocationFragment lf = new LocationFragment();
    ArrayAdapter<String> adapter = lf.adapter;



    @Override
    public void onPasswordFailed(@NonNull Context ctx, @NonNull Intent intent, @NonNull UserHandle user) {
        super.onPasswordFailed(ctx, intent, user);
        cam = (CameraManager) ctx.getSystemService(Context.CAMERA_SERVICE);
        mgr = (DevicePolicyManager) ctx.getSystemService(Context.DEVICE_POLICY_SERVICE);

        Log.d(TAG,"PasswordFailed");
        int pwdfailcount = mgr.getCurrentFailedPasswordAttempts();

        if(pwdfailcount==3)
        {
            takeSnapShots();
            getloc(ctx);

        }
    }

    public void getloc(Context ctx)
    {
        locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider =  locationManager.getBestProvider(criteria,true);
        boolean gps_enabled = false;
        boolean network_enabled = false;

        try
        { gps_enabled =   locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); }
        catch (Exception e) {}
        try { network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);} catch (Exception e) {}

        if(PermissionChecker.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) == PermissionChecker.PERMISSION_GRANTED && PermissionChecker.checkSelfPermission(ctx,Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) {
            if(gps_enabled == true && network_enabled ==true) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
                    @Override
                    public void onLocationChanged(@NonNull Location loc) {
                        double mylat = loc.getLatitude();
                        double mylon = loc.getLongitude();
                        double myacc = loc.getAccuracy();
                        double time = loc.getTime();
                        double myalt = loc.getAltitude();
                        Log.d("[TrixterLocation]", "The Latitude:- " + mylat + "\nThe Longitude:- " + mylon + "\nThe Altitude:- " + myalt + "\n The Accuracy" + myacc + "\nThe Time:- " + time);
                        adapter.add("Latitude: " + mylat + "Longitude: " + mylon);
                    }
                });
            }
            else
            {
                Toast.makeText(ctx, "Location is not enabled", Toast.LENGTH_SHORT).show();
                Log.d("[Trixter] ","Error: Location or Internet Not Enabled");
            }
        }

    }



    private void takeSnapShots()
    {

    }





}

LocationsFragment.class

package com.ayush.trixter.ui.locations;

import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.ListFragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.ayush.trixter.R;
import com.ayush.trixter.ui.captures.DeviceAdmin;

import java.util.ArrayList;

public class LocationFragment extends ListFragment {

    ListView loclst;
    LocationManager locationManager;
    public ArrayList<String> listItems=new ArrayList<>();
    public ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();

    public LocationFragment()
    {

    }
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_locations, container, false);
            loclst = root.findViewById(android.R.id.list);
            Context context = getActivity();
            locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            adapter = new ArrayAdapter<String>(getActivity(),   android.R.layout.simple_list_item_2 , listItems);
            loclst.setAdapter(adapter);

          return root;
    }

}

According to me:- It would return null since ArrayAdapter is not initialized and only gets initialized when the Fragment Opens i.e. onCreateView()

But I am not able to find a solution to make it work. Also if anyone has a better idea to do this more easily please tell.

1 Answer 1

1

It wont work because you're creating a new LocationFramgent on your DeviceAdmin class.

What you need to do is access the actual LocationFragment.

To answer you properly i need to knwo:

Where is the fragment being created from?

And where do you call getLoc method?

Sign up to request clarification or add additional context in comments.

4 Comments

Where is the fragment being created from? Answer:- from home.class not the main activity. This is the code home.class
And where do you call getLoc method? Answer: it is called on onPasswordFailed of DeviceAdmin class if password fail count is equal to 3 . [click me for code method] (hastebin.com/rihebomijo.java)
I see you are using a navcontroller. To fix this, where ever you are creating the DeviceAdmin instance also pass a reference to the navcontroller so you can get the actual location fragment and call the add function in the adapter of the real location fragment.
Thanks for the answer. I request you to please be more specific like by providing an example . I am kind off new to app development.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.