英文:
Passing Array Adapter via Constructor | ListView
问题
我试图将来自LocationsFragment.class
的适配器用于我的DeviceAdmin.class
,以将两个字符串mylatitude
和mylongitude
添加到我的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 + " " + 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
得分: 1
这不会起作用,因为你在你的DeviceAdmin类上创建了一个新的LocationFragment。
你需要做的是访问实际的LocationFragment。
要正确回答你,我需要知道:
- 片段是从哪里创建的?
- 你在哪里调用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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论