致命异常:AsyncTask #4 java.lang.RuntimeException:执行 doInBackground() 时发生错误
Posted
技术标签:
【中文标题】致命异常:AsyncTask #4 java.lang.RuntimeException:执行 doInBackground() 时发生错误【英文标题】:FATAL EXCEPTION: AsyncTask #4 java.lang.RuntimeException: An error occurred while executing doInBackground() 【发布时间】:2020-12-12 21:22:58 【问题描述】:请帮助我,我不知道如何解决这个问题,我的代码错误并出现如下:
2020-08-24 15:29:36.424 25891-26358/com.cryptbrn.treasify E/androidRuntime: FATAL EXCEPTION: AsyncTask #4
Process: com.cryptbrn.treasify, PID: 25891
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:353)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:176)
at com.cryptbrn.treasify.fragment.LocationFragment$ParserTask.doInBackground(LocationFragment.java:252)
at com.cryptbrn.treasify.fragment.LocationFragment$ParserTask.doInBackground(LocationFragment.java:245)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
2020-08-24 15:29:36.478 25891-25950/com.cryptbrn.treasify V/FA: Recording user engagement, ms: 5494
2020-08-24 15:29:36.520 25891-25950/com.cryptbrn.treasify V/FA: Activity paused, time: 607133467
2020-08-24 15:29:36.626 25891-25985/com.cryptbrn.treasify D/OpenGLRenderer: endAllActiveAnimators on 0x78542af000 (RippleDrawable) with handle 0x7854112e80
2020-08-24 15:29:38.098 25891-26121/com.cryptbrn.treasify W/OkHttpClient: A connection to https://firebasestorage.googleapis.com/ was leaked. Did you forget to close a response body?
2020-08-24 15:29:38.098 25891-26121/com.cryptbrn.treasify W/OkHttpClient: A connection to https://firebasestorage.googleapis.com/ was leaked. Did you forget to close a response body?
2020-08-24 15:29:38.098 25891-26121/com.cryptbrn.treasify W/OkHttpClient: A connection to https://maps.googleapis.com/ was leaked. Did you forget to close a response body?
2020-08-24 15:29:38.532 25891-25950/com.cryptbrn.treasify D/FA: Application going to the background
LocationFragment.java
package com.cryptbrn.treasify.fragment;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cryptbrn.treasify.InsertPostActivity;
import com.cryptbrn.treasify.JsonParser;
import com.cryptbrn.treasify.R;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
/**
* A simple @link Fragment subclass.
* Use the @link LocationFragment#newInstance factory method to
* create an instance of this fragment.
*/
public class LocationFragment extends Fragment implements OnMapReadyCallback
GoogleMap mMap;
MapView mapView;
FusedLocationProviderClient fusedLocationProviderClient;
double currentLat = 0, currentLong = 0;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public LocationFragment()
// Required empty public constructor
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment LocationFragment.
*/
// TODO: Rename and change types and number of parameters
public static LocationFragment newInstance(String param1, String param2)
LocationFragment fragment = new LocationFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
if (getArguments() != null)
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_location, container, false);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
if (ActivityCompat.checkSelfPermission(getActivity()
, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
getCurrentLocation();
else
ActivityCompat.requestPermissions(getActivity()
,new String[]Manifest.permission.ACCESS_FINE_LOCATION, 44);
FloatingActionButton btnBank = (FloatingActionButton) view.findViewById(R.id.btn_flea);
btnBank.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
String url = "https://maps.googleapis.com/maps/api/..." +
"?location=" + currentLat + "," + currentLong +
"&radius=5000" + "&type=" + "kfc"+
"&sensor=true" + "&key=" + getResources().getString(R.string.google_api_key);
new PlaceTask().execute(url);
);
FloatingActionButton btnFlea = (FloatingActionButton) view.findViewById(R.id.btn_bank);
btnFlea.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
String url = "https://maps.googleapis.com/maps/api/..." +
"?location=" + currentLat + "," + currentLong +
"&radius=5000" + "&type=" + "bank_sampah"+
"&sensor=true" + "&key=" + getResources().getString(R.string.google_api_key);
new PlaceTask().execute(url);
);
FloatingActionButton button = (FloatingActionButton) view.findViewById(R.id.btn_list);
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
Intent intent = new Intent(getActivity(), InsertPostActivity.class);
startActivity(intent);
);
return view;
private void getCurrentLocation()
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>()
@Override
public void onSuccess(Location location)
if (location != null)
currentLat = location.getLatitude();
currentLong = location.getLongitude();
);
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
mapView = view.findViewById(R.id.mapView);
if(mapView != null)
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap)
MapsInitializer.initialize(getContext());
mMap = googleMap;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(currentLat,currentLong), 40
));
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
if (requestCode == 44)
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
getCurrentLocation();
private class PlaceTask extends AsyncTask<String,Integer,String>
@Override
protected String doInBackground(String... strings)
String data = null;
try
data = downloadUrl(strings[0]);
catch (IOException e)
e.printStackTrace();
return data;
@Override
protected void onPostExecute(String s)
new ParserTask().execute(s);
private String downloadUrl(String string) throws IOException
URL url = new URL(string);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null)
builder.append(line);
String data = builder.toString();
reader.close();
return data;
private class ParserTask extends AsyncTask<String,Integer, List<HashMap<String, String>>>
@Override
protected List<HashMap<String, String>> doInBackground(String... strings)
JsonParser jsonParser = new JsonParser();
List<HashMap<String,String>> mapList = null;
JSONObject object = null;
try
object = new JSONObject(strings[0]);
mapList = jsonParser.parseResult(object);
catch (JSONException e)
e.printStackTrace();
return mapList;
@Override
protected void onPostExecute(List<HashMap<String, String>> hashMaps)
mMap.clear();
for (int i=0; i<hashMaps.size(); i++)
HashMap<String,String> hashMapList = hashMaps.get(i);
double lat = Double.parseDouble(hashMapList.get("lat"));
double lng = Double.parseDouble(hashMapList.get("lng"));
String name = hashMapList.get("name");
LatLng latLng = new LatLng(lat,lng);
MarkerOptions options = new MarkerOptions();
options.position(latLng);
options.title(name);
mMap.addMarker(options);
JsonParser.java
package com.cryptbrn.treasify;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class JsonParser
private HashMap<String,String> parseJsonObject(JSONObject object)
HashMap<String,String> dataList = new HashMap<>();
try
String name = object.getString("name");
String latitude = object.getJSONObject("geometry")
.getJSONObject("location").getString("lat");
String longitude = object.getJSONObject("geometry")
.getJSONObject("location").getString("lng");
dataList.put("name",name);
dataList.put("lat",latitude);
dataList.put("lng",longitude);
catch (JSONException e)
e.printStackTrace();
return dataList;
private List<HashMap<String,String>> parseJsonArray(JSONArray jsonArray)
List<HashMap<String,String>> dataList = new ArrayList<>();
for (int i=0; i<jsonArray.length(); i++)
try
HashMap<String,String> data = parseJsonObject((JSONObject) jsonArray.get(i));
dataList.add(data);
catch (JSONException e)
e.printStackTrace();
return dataList;
public List<HashMap<String,String>> parseResult (JSONObject object)
JSONArray jsonArray = null;
try
jsonArray = object.getJSONArray("result");
catch (JSONException e)
e.printStackTrace();
return parseJsonArray(jsonArray);
我只关注 Youtube 上的教程以在 mapview 上显示附近的位置,我已遵循所有教程但应用程序强制关闭。我发现有同样问题的人,请帮助我。
【问题讨论】:
【参考方案1】:很简单NullPointerException
这里可能有某种异常
private class PlaceTask extends AsyncTask<String,Integer,String>
@Override
protected String doInBackground(String... strings)
String data = null;
try
data = downloadUrl(strings[0]);
catch (IOException e)
e.printStackTrace(); // HERE exception
return data; // HERE IT IS NULL
@Override
protected void onPostExecute(String s)
new ParserTask().execute(s); // Here you pass null to ParserTask()
你应该调试你的应用程序并检查为什么 downloadUrl 抛出异常
也许熟悉 RestApi 库 Retrofit 是个好点 https://square.github.io/retrofit/ 它会让你的生活更轻松:)
【讨论】:
以上是关于致命异常:AsyncTask #4 java.lang.RuntimeException:执行 doInBackground() 时发生错误的主要内容,如果未能解决你的问题,请参考以下文章
AndroidRuntime:致命异常:AsyncTask #1 进程
到 phpmyadmin 的致命异常 AsyncTask 连接
E/AndroidRuntime:致命异常:Android 的 AsyncTask #1 错误
获得致命异常:使用 Async 类的 AsyncTask #1
致命异常:AsyncTask #1 java.lang.RuntimeException:执行 doInBackground() 时发生错误
致命异常:AsyncTask #1,java.lang.RuntimeException:执行 doInBackground() 时发生错误