通过构造函数传递ArrayAdapter | 列表视图

huangapple go评论80阅读模式
英文:

Passing Array Adapter via Constructor | ListView

问题

我试图将来自LocationsFragment.class的适配器用于我的DeviceAdmin.class,以将两个字符串mylatitudemylongitude添加到我的ListView中。
我正在使用构造函数方法。
但是每当我在我的DeviceAdmin.class中调用adapter.add(mylatitude + " " + mylongitude);时,它似乎返回null。

        at com.ayush.trixter.ui.captures.DeviceAdmin$1.onLocationChanged(DeviceAdmin.java:103)

第103行是:adapter.add("Latitude: " + mylat + "Longitude: " + mylon);

DeviceAdmin.class

package com.ayush.trixter.ui.captures;

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;
    }

}

根据我的观察:
它会返回null,因为ArrayAdapter未初始化,并且只有在Fragment打开时才会初始化,即在onCreateView()方法中。

但是我无法找到使其工作的解决方案。
如果有人有更好的方法来更轻松地完成这个任务,请告诉我。

英文:

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 + &quot; &quot; + mylongitude); in my DeviceAdmin.class

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

Line 103 is : adapter.add(&quot;Latitude: &quot; + mylat + &quot;Longitude: &quot; + 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 = &quot;[Trixter]&quot;;
DevicePolicyManager mgr;
FirebaseDatabase db;
public boolean mTracking = false;
public ArrayList&lt;String&gt; listItems=new ArrayList&lt;&gt;();
LocationFragment lf = new LocationFragment();
ArrayAdapter&lt;String&gt; 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,&quot;PasswordFailed&quot;);
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 &amp;&amp; PermissionChecker.checkSelfPermission(ctx,Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) {
if(gps_enabled == true &amp;&amp; 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(&quot;[TrixterLocation]&quot;, &quot;The Latitude:- &quot; + mylat + &quot;\nThe Longitude:- &quot; + mylon + &quot;\nThe Altitude:- &quot; + myalt + &quot;\n The Accuracy&quot; + myacc + &quot;\nThe Time:- &quot; + time);
adapter.add(&quot;Latitude: &quot; + mylat + &quot;Longitude: &quot; + mylon);
}
});
}
else
{
Toast.makeText(ctx, &quot;Location is not enabled&quot;, Toast.LENGTH_SHORT).show();
Log.d(&quot;[Trixter] &quot;,&quot;Error: Location or Internet Not Enabled&quot;);
}
}
}
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&lt;String&gt; listItems=new ArrayList&lt;&gt;();
public ArrayAdapter&lt;String&gt; adapter = (ArrayAdapter&lt;String&gt;) 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&lt;String&gt;(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

得分: 1

这不会起作用,因为你在你的DeviceAdmin类上创建了一个新的LocationFragment。

你需要做的是访问实际的LocationFragment。

要正确回答你,我需要知道:

  1. 片段是从哪里创建的?
  2. 你在哪里调用getLoc方法?
英文:

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?

huangapple
  • 本文由 发表于 2020年8月13日 19:13:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63393924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定