java.lang.RuntimeException:无法实例化应用程序无法强制转换为android.app.Application

时间:2015-12-22 04:34:41

标签: android json api parsing

我不确定这意味着什么,但我现在看到的错误实际上是不同的,之后我关闭android studio重新打开它,这个错误发生了......

我的代码中没有错误,但这个应用程序无法编译,这非常令人沮丧。

12-21 23:20:02.007 6867-6867/zafir.com.motive E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: zafir.com.motive, PID: 6867
                                                            java.lang.RuntimeException: Unable to instantiate application zafir.com.motive.Volley.MySingleton: java.lang.ClassCastException: zafir.com.motive.Volley.MySingleton cannot be cast to android.app.Application
                                                                at android.app.LoadedApk.makeApplication(LoadedApk.java:563)
                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4555)
                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:151)
                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                at android.os.Looper.loop(Looper.java:135)
                                                                at android.app.ActivityThread.main(ActivityThread.java:5283)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                             Caused by: java.lang.ClassCastException: zafir.com.motive.Volley.MySingleton cannot be cast to android.app.Application
                                                                at android.app.Instrumentation.newApplication(Instrumentation.java:995)
                                                                at android.app.Instrumentation.newApplication(Instrumentation.java:980)
                                                                at android.app.LoadedApk.makeApplication(LoadedApk.java:558)
                                                                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4555) 
                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:151) 
                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379) 
                                                                at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                at android.os.Looper.loop(Looper.java:135) 
                                                                at android.app.ActivityThread.main(ActivityThread.java:5283) 
                                                                at java.lang.reflect.Method.invoke(Native Method) 
                                                                at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 

MainActivity

    public class MainActivity extends AppCompatActivity
{
    private static final String API_URL = "LINK";

    private List<Photo> listPhotos = new ArrayList<Photo>();
    private ImageLoader imageLoader;

    private RecyclerView recView;
    private RecyclerAdapter adapter;

    RequestQueue requestQueue = Volley.newRequestQueue(this);



    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Initializing the RecyclerView and it's layout
        recView = (RecyclerView) findViewById(R.id.recyclerview);
        adapter = new RecyclerAdapter(MainActivity.this, (ArrayList<Photo>) listPhotos);
        recView.setAdapter(adapter);

        StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.HORIZONTAL);
        recView.setLayoutManager(gridLayoutManager);

        sendJSONRequest();
    }


    private void sendJSONRequest()
    {
        JsonObjectRequest request = new JsonObjectRequest(API_URL, null, new Response.Listener<JSONObject>()
        {
            @Override
            public void onResponse(JSONObject response)
            {
                try
                {
                    JSONObject objectRes = response.getJSONObject("response");
                    JSONArray arrayPosts = objectRes.getJSONArray("posts");
                    for (int i = 0; i < arrayPosts.length(); i++)
                    {
                        JSONObject object = arrayPosts.getJSONObject(i);
                        JSONArray arrayPhotos = object.getJSONArray("photos");
                        for (int j = 0; j < arrayPhotos.length(); j++)
                        {
                            JSONObject firstPhoto = arrayPhotos.getJSONObject(i);
                            JSONObject originalSize = firstPhoto.optJSONObject("original_size");
                            String url = originalSize.getString("url");

                            Photo photo = new Photo();
                            photo.setthumbnail(url);
                            listPhotos.add(photo);

                        }
                    }
                } catch (JSONException e)
                {

                }

                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                VolleyLog.e("Error: ", error.getMessage());
            }
        });

        requestQueue.add(request);
    }

RecyclerAdapter

    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>
{
    private Context context;
    private List<Photo> listPhotos;
    private MySingleton mySingleton;
    private ImageLoader imageLoader;
    private LayoutInflater layoutInflater;
    private ViewHolder viewHolder;
    private int focusedItem = 0;

    public class ViewHolder extends RecyclerView.ViewHolder
    {
        //If this doesn't work change back to ImageView
        public NetworkImageView thumbnail;

        public ViewHolder(View itemView)
        {
            super(itemView);
            this.thumbnail = (NetworkImageView) itemView.findViewById(R.id.rec_image);
        }
    }

    public RecyclerAdapter(Context context, ArrayList<Photo> arrayList)
    {
        this.listPhotos = arrayList;
        this.context = context;
    }

    public void setPhotos(ArrayList<Photo> photos)
    {
        this.listPhotos = photos;
        notifyItemRangeChanged(0, listPhotos.size());
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        View recyclerViewLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_layout,null);
        ViewHolder viewHolder = new ViewHolder(recyclerViewLayout);
        return new ViewHolder(recyclerViewLayout);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position)
    {
        Photo currentPhoto = listPhotos.get(position);
        imageLoader = MySingleton.getInstance(context).getImageLoader();
        viewHolder.itemView.setSelected(focusedItem == position);
        viewHolder.getLayoutPosition();
        viewHolder.thumbnail.setImageUrl(currentPhoto.getthumbnail(), imageLoader);
        //viewHolder.thumbnail.setDefaultImageResId(R.drawable.ic_view_quilt_black_36dp);
    }

    @Override
    public int getItemCount()
    {
        return listPhotos.size();
    }
}

MySingleton

    public class MySingleton extends Activity
{
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    public MySingleton()
    {

    }

    public MySingleton(Context context)
    {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(LruBitmapCache.getCacheSize(mCtx)));
    }

    public static synchronized MySingleton getInstance(Context context)
    {
        if (mInstance == null)
        {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue()
    {
        if (mRequestQueue == null)
        {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req)
    {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader()
    {
        return mImageLoader;
    }
}

LruBitMapCache

    public class LruBitmapCache extends LruCache<String, Bitmap>
        implements ImageLoader.ImageCache
{

    public LruBitmapCache(int maxSize) {
        super(maxSize);
    }

    public LruBitmapCache(Context ctx) {
        this(getCacheSize(ctx));
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }

    // Returns a cache size equal to approximately three screens worth of images.
    public static int getCacheSize(Context ctx) {
        final DisplayMetrics displayMetrics = ctx.getResources().
                getDisplayMetrics();
        final int screenWidth = displayMetrics.widthPixels;
        final int screenHeight = displayMetrics.heightPixels;
        // 4 bytes per pixel
        final int screenBytes = screenWidth * screenHeight * 4;

        return screenBytes * 3;
    }
}

照片

    public class Photo
{

    private String thumbnail;

    //----------Constructor----------

    public Photo(String urlImage)
    {
        this.thumbnail = urlImage;
    }

    public Photo()
    {

    }

    //----------Get-and-Set----------

    public String getthumbnail()
    {
        return thumbnail;
    }

    public void setthumbnail(String thumbnail)
    {
        this.thumbnail = thumbnail;
    }

    //----------ToString-------------

    @Override
    public String toString()
    {
        return "urlImage" + thumbnail;
    }
}

5 个答案:

答案 0 :(得分:1)

你的MySingleton类应该扩展android.app.Application而不是Activity

class MySingleton extends android.app.Application// not Activity

答案 1 :(得分:0)

您的问题是:Caused by: java.lang.ClassCastException: zafir.com.motive.Volley.MySingleton cannot be cast to android.app.Application。您的MySingleton扩展自Activity类,而不是Application类的继承。

答案 2 :(得分:0)

在logcat错误中清楚地提到并由mr.icetea解释 问题:由java.lang.ClassCastException引起的崩溃:zafir.com.motive.Volley.MySingleton无法强制转换为android.app.Application。你的MySingleton从Activity类扩展而来,它不是Application类的继承
解决方案: 在线下更改

 mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());

 mRequestQueue = Volley.newRequestQueue(mCtx);

答案 3 :(得分:0)

zafir.com.motive.Volley.MySingleton无法转换为android.app.Application。 MySingleton扩展自Activity类,它不是Application类的继承。使用Application类扩展MySingleton,并在应用程序标记中的manifest中输入:

<application
        android:name="zafir.com.motive.Volley.MySingleton"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"

答案 4 :(得分:0)

无需扩展类Activity。普通班更合适。 而且,是自己写的Volley班吗?我搜索过,找不到这个类的库。也许这一行:RequestQueue requestQueue = Volley.newRequestQueue(this);导致错误。你能用Volley.newRequestQueue()方法发布代码吗?