context.getSystemService(context.LAYOUT_INFLATER_SERVICE)调用时报NullPointerException

LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(context.LAYOUT_INFLATER_SERVICE);
		view = inflater.inflate(R.layout.home_select_list, null);


这行报空指针,可能原因为,这个适配器调用构造函数实例化时:

public DesignAdapter(Context context, int resource, int textViewResourceId,
			Object[] objects) {
		super(context, resource, textViewResourceId, objects);
		// TODO Auto-generated constructor stub
		context = context;
	}


context前没有加this, 类变量context并没有赋值  这样导致LayoutInflater实例化时报空指针。

解决办法:

public DesignAdapter(Context context, int resource, int textViewResourceId,
			Object[] objects) {
		super(context, resource, textViewResourceId, objects);
		// TODO Auto-generated constructor stub
		
		this.context = context;
	}
 

 

目前代码如下:package com.example.bus.ui.home; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.example.bus.MainActivity; import com.example.bus.RealTimePoiSuggestHelper; import com.example.bus.SearchResultActivity; import com.example.bus.databinding.FragmentHomeBinding; import android.app.Activity; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private HomeViewModel homeViewModel; private static final int TIPS_DELAY = 300; // 防抖延迟 private Handler handler = new Handler(Looper.getMainLooper()); private Runnable pendingRequest; private boolean isLocationPermissionGranted = false; // 记录权限状态 private ActivityResultLauncher<Intent> searchLauncher; private RealTimePoiSuggestHelper suggestHelper; private com.amap.api.location.AMapLocationClient locationClient; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); searchLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() == Activity.RESULT_OK) { Intent data = result.getData(); if (data != null && data.hasExtra("updated_keyword")) { String updated = data.getStringExtra("updated_keyword"); if (!updated.equals(binding.homeInput.getText().toString())) { binding.homeInput.setText(updated); binding.homeInput.setSelection(updated.length()); } } } }); // 初始化 ViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); homeViewModel.getText().observe(getViewLifecycleOwner(), text -> { binding.textHome.setText(text); }); disableSearchInputInitially(); setupSearchSuggestion(); setupSearchAction(); setupSearchBoxWithPermissionControl(); return root; } /** * 初始禁用搜索框输入,直到获得定位权限 */ private void disableSearchInputInitially() { binding.homeInput.setFocusable(true); binding.homeInput.setFocusableInTouchMode(false); // 禁止编辑模式 binding.homeInput.setCursorVisible(false); binding.homeInput.setClickable(true); } private void setupSearchBoxWithPermissionControl() { binding.homeInput.setOnClickListener(v -> { // 👉 每次点击都交给 MainActivity 去处理权限(和搜索按钮行为一致) MainActivity activity = (MainActivity) requireActivity(); activity.ensureFineLocationPermission(() -> { // ✅ 权限已授予,启用输入功能,并保存状态 if (!isLocationPermissionGranted) { isLocationPermissionGranted = true; enableSearchInput(); } }); }); } /** * 启用搜索框输入功能(权限通过后调用) */ /** * 启用搜索框输入功能,并在权限通过后请求一次定位 */ private void enableSearchInput() { binding.homeInput.post(() -> { binding.homeInput.setFocusableInTouchMode(true); binding.homeInput.requestFocus(); binding.homeInput.setCursorVisible(true); InputMethodManager imm = (InputMethodManager) requireContext() .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.showSoftInput(binding.homeInput, InputMethodManager.SHOW_IMPLICIT); } // ✅ 开始单次定位(关键!) startSingleLocationForSuggestions(); }); } private void startSingleLocationForSuggestions() { if (locationClient != null) return; // 防止重复创建 try { locationClient.startLocation(); // 这个方法会 throw Exception } catch (Exception e) { Log.e("HomeFragment", "启动定位失败", e); destroyLocationClient(); } com.amap.api.location.AMapLocationClientOption option = new com.amap.api.location.AMapLocationClientOption(); option.setLocationMode(com.amap.api.location.AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); // 高精度 option.setOnceLocation(true); // 🔑 只定位一次 option.setNeedAddress(true); // 要地址(拿城市名) option.setMockEnable(false); option.setInterval(2000); locationClient.setLocationOption(option); locationClient.setLocationListener(location -> { boolean success = false; if (location.getErrorCode() == 0) { // 定位成功 double lat = location.getLatitude(); double lng = location.getLongitude(); String city = location.getCity(); if (city == null || city.isEmpty()) { city = location.getProvince(); } // 去掉“市”字 if (city != null && city.endsWith("市")) { city = city.substring(0, city.length() - 1); } // 更新 suggestHelper if (suggestHelper != null) { suggestHelper.setLocationBias(lat, lng); suggestHelper.setUseDistanceSort(true); suggestHelper.setCurrentCity(city != null ? city : "全国"); } Log.d("HomeFragment", "📍 单次定位成功: " + lat + "," + lng + " | 城=" + city); success = true; } else { Log.e("HomeFragment", "❌ 单次定位失败: " + location.getErrorInfo()); } // ✅ 无论成败,清理 client destroyLocationClient(); // 🔁 如果之前已有输入内容,手动触发一次 suggestion 请求 String text = binding.homeInput.getText().toString().trim(); if (!text.isEmpty() && suggestHelper != null) { suggestHelper.requestSuggestions(text); } }); try { locationClient.startLocation(); } catch (Exception e) { e.printStackTrace(); destroyLocationClient(); // 清理 } } private void destroyLocationClient() { if (locationClient != null) { locationClient.stopLocation(); locationClient.onDestroy(); locationClient = null; } } /** * 设置输入建议功能(suggestion) */ private void setupSearchSuggestion() { // 创建建议助手 suggestHelper = new RealTimePoiSuggestHelper(requireContext()); suggestHelper.setCurrentCity("全国"); // 可改为动态城市 suggestHelper.setCallback(suggestions -> { if (suggestions.length > 0) { ArrayAdapter<String> adapter = new ArrayAdapter<>( requireContext(), android.R.layout.simple_dropdown_item_1line, suggestions ) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); // 👉 添加点击事件 view.setOnClickListener(v -> { String selectedText = getItem(position); if (selectedText != null && !selectedText.isEmpty()) { binding.homeInput.setText(selectedText); binding.homeInput.clearFocus(); // 隐藏软键盘 InputMethodManager imm = (InputMethodManager) requireContext() .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(binding.homeInput.getWindowToken(), 0); } // 直接触发搜索(跳转到 SearchResultActivity) performSearch(); } }); return view; } }; // 主线程更新 UI new Handler(Looper.getMainLooper()).post(() -> { binding.homeInput.setAdapter(adapter); if (requireActivity().getCurrentFocus() == binding.homeInput) { binding.homeInput.showDropDown(); } }); } else { new Handler(Looper.getMainLooper()).post(() -> binding.homeInput.setAdapter(null) ); } }); // 防抖控制 handler = new Handler(Looper.getMainLooper()); pendingRequest = null; binding.homeInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (pendingRequest != null) { handler.removeCallbacks(pendingRequest); } if (s.length() == 0) { binding.homeInput.setAdapter(null); return; } boolean hasPermission = requireContext().checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED; if (!hasPermission) { // 没有权限 → 不请求建议,也不显示任何提示 binding.homeInput.setAdapter(null); return; } pendingRequest = () -> suggestHelper.requestSuggestions(s.toString()); handler.postDelayed(pendingRequest, TIPS_DELAY); } @Override public void afterTextChanged(Editable s) {} }); } /** * 设置搜索动作:回车 & 按钮点击 */ private void setupSearchAction() { // 回车搜索 binding.homeInput.setOnEditorActionListener((v, actionId, event) -> { if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_SEARCH) { performSearch(); return true; } return false; }); // 搜索按钮点击 binding.homeSearch.setOnClickListener(v -> performSearch()); } private void performSearch() { String keyword = binding.homeInput.getText().toString().trim(); if (keyword.isEmpty()) { Toast.makeText(requireContext(), "请输入关键词", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(requireContext(), SearchResultActivity.class); intent.putExtra("keyword", keyword); searchLauncher.launch(intent); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; // 清理防抖任务 if (handler != null) { handler.removeCallbacksAndMessages(null); } destroyLocationClient(); } } 点击搜索框就闪退了
最新发布
12-11
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值