不幸的是应用程序已停止

Posted

技术标签:

【中文标题】不幸的是应用程序已停止【英文标题】:Unfortunately app has stopped 【发布时间】:2016-10-03 11:24:15 【问题描述】:

代码

public class MainActivity extends AppCompatActivity

ArrayList<Movie_setget> arrlist = null;
ListView _lvlist = null;

@Override
protected void onCreate(Bundle savedInstanceState)

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    _lvlist = (ListView)findViewById(R.id.lvlist);
    Showdata obj = new Showdata();
    obj .execute();


public class Showdata extends AsyncTask<String , Void, Long>

    @Override
    protected Long doInBackground(String... params)
    
        JsonParser jp = new JsonParser();
        JSONObject jobj = jp.getJsonFromUrl("https://api.myjson.com/bins/4xdbu");
        arrlist = new ArrayList<Movie_setget>();

        try
        
            JSONArray jarr = jobj.getJSONArray("Superhero");

            for(int i=0; i<jarr.length(); i++)
            
                JSONObject m = jarr.getJSONObject(i);

                String name = m.getString("name");
                String image = m.getString("img");
                Movie_setget obj = new Movie_setget();
                obj.setName(name);
                obj.setImg(image);
                arrlist.add(obj);
            
        
        catch(JSONException e)
        
            e.printStackTrace();
        
        return null;
    

    @Override
    protected void onPostExecute(Long result)
    

        _lvlist.setAdapter(new CustomerAdapter());
        super.onPostExecute(result);
     


public class CustomerAdapter extends BaseAdapter

    @Override
    public int getCount()
    
        return arrlist.size();
    

    @Override
    public Object getItem(int position)
    
        return null;
    

    @Override
    public long getItemId(int position)
    
        return 0;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    
        LayoutInflater inf = getLayoutInflater();
        View v =inf.inflate(R.layout.rowdetails, parent, false);
        TextView _tvname = (TextView)v.findViewById(R.id.tvname);
        //ImageView _ivimg = (ImageView)v.findViewById(R.id.ivimg);
        Movie_setget m = new Movie_setget();
        m = arrlist.get(position);
        _tvname.setText(m.getName());
        ImageLoaderTask task = new ImageLoaderTask();
        try
        
            Bitmap image = task.execute(m.getImg()).get();
            _ivimg.setImageBitmap(image);
        
        catch(Exception e)
        
            e.printStackTrace();
        
        return v;
    


public class ImageLoaderTask extends AsyncTask<String, Void, Bitmap>

    @Override
    protected Bitmap doInBackground(String... params)
    
        try
        
            URL url = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            return bitmap;
        
        catch(Exception e)
        
            e.printStackTrace();
        
        return null;
    

logcat

06-03 16:59:26.570 9720-9757/com.example.abhijitroy.superhero E/androidRuntime:致命异常:AsyncTask #1 进程:com.example.abhijitroy.superhero,PID:9720 java.lang.RuntimeException:执行 doInBackground() 时发生错误 在 android.os.AsyncTask$3.done(AsyncTask.java:304) 在 java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 在 java.util.concurrent.FutureTask.setException(FutureTask.java:222) 在 java.util.concurrent.FutureTask.run(FutureTask.java:242) 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 在 java.lang.Thread.run(Thread.java:818) 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' 在 com.example.abhijitroy.superhero.MainActivity$Showdata.doInBackground(MainActivity.java:54) 在 com.example.abhijitroy.superhero.MainActivity$Showdata.doInBackground(MainActivity.java:43) 在 android.os.AsyncTask$2.call(AsyncTask.java:292) 在 java.util.concurrent.FutureTask.run(FutureTask.java:237) 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 在 java.lang.Thread.run(Thread.java:818)

【问题讨论】:

您的 json 数据似乎丢失了......请参阅此处 MainActivity$Showdata.doInBackground(MainActivity.java:54) at com.example.abhijitroy.superhero.MainActivity$Showdata.doInBackground(MainActivity.java:43 ) 【参考方案1】:

你的 json 对象是 null 这就是为什么它给你这个错误

@Override
protected Long doInBackground(String... params)

    JsonParser jp = new JsonParser();
    JSONObject jobj = jp.getJsonFromUrl("https://api.myjson.com/bins/4xdbu");
    arrlist = new ArrayList<Movie_setget>();

    try
    
      if(jobj!=null)
        JSONArray jarr = jobj.getJSONArray("Superhero");

        if(jarr!=null)
        for(int i=0; i<jarr.length(); i++)
        
            JSONObject m = jarr.getJSONObject(i);

            String name = m.getString("name");
            String image = m.getString("img");
            Movie_setget obj = new Movie_setget();
            obj.setName(name);
            obj.setImg(image);
            arrlist.add(obj);
        
      
     
    
    catch(JSONException e)
    
        e.printStackTrace();
    
    return null;

试试这段代码,我已经为 jsonobject 和 jsonarray 添加了 if 语句来检查它是否不为空。

【讨论】:

Jsonobject 不为空请检查,内容未加载这里是新的json链接------api.myjson.com/bins/3utze 但日志显示“尝试在空对象引用上调用虚拟方法 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)'”尝试调试您的您在这些行中发现问题的代码。【参考方案2】:

您好,请使用 Volly 进行 json 解析

    StringRequest strReq = new StringRequest(Method.GET,
                "https://api.myjson.com/bins/4xdbu", new Response.Listener<String>() 

                    @Override
                    public void onResponse(String response) 
                        Log.d(TAG, response.toString());
//                      msgResponse.setText(response.toString());
//                      hideProgressDialog();

                    
                , new Response.ErrorListener() 

                    @Override
                    public void onErrorResponse(VolleyError error) 
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
//                      hideProgressDialog();
                    
                );

在这里我得到了完美的回应

字符串请求类

public class StringRequest extends Request<String> 
    private final Listener<String> mListener;

    /**
     * Creates a new request with the given method.
     *
     * @param method the request @link Method to use
     * @param url URL to fetch the string at
     * @param listener Listener to receive the String response
     * @param errorListener Error listener, or null to ignore errors
     */
    public StringRequest(int method, String url, Listener<String> listener,
            ErrorListener errorListener) 
        super(method, url, errorListener);
        mListener = listener;
    

    /**
     * Creates a new GET request.
     *
     * @param url URL to fetch the string at
     * @param listener Listener to receive the String response
     * @param errorListener Error listener, or null to ignore errors
     */
    public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) 
        this(Method.GET, url, listener, errorListener);
    

    @Override
    protected void deliverResponse(String response) 
        mListener.onResponse(response);
    

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) 
        String parsed;
        try 
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
         catch (UnsupportedEncodingException e) 
            parsed = new String(response.data);
        
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    

完美的给我这个日志

D/StringRequestActivity: "Superhero":["name":"Batman vs Superman","img":"http://cdn1-www.comingsoon.net/assets/uploads/gallery/batman-v-superman-dawn-of-justice-1400694960/tb9umjs-1.jpg","name":"CivilWar","img":"http://screenrant.com/wp-content/uploads/captain-america-civil-war-trailer-2-views.jpg","name":"WonderWoman","img":"http://cdn2-www.comingsoon.net/assets/uploads/2016/03/wonder-woman-header5.jpg"]

【讨论】:

以上是关于不幸的是应用程序已停止的主要内容,如果未能解决你的问题,请参考以下文章

不幸的是,应用程序已停止在模拟器中工作

Android自定义ArrayAdapter:滚动时“不幸的是,应用程序已停止”

Android 应用程序错误 - 不幸的是,您的应用程序已停止

GCM Android:不幸的是,GCM 演示已停止

Android:更改视图顺序会导致“不幸的是,应用程序已停止”OK。为啥?

不幸的是,相机已停止