【问题标题】:Getting NullPointerException trying to use Volley singleton尝试使用 Volley 单例时出现 NullPointerException
【发布时间】:2016-02-20 06:59:55
【问题描述】:

主要活动类 大家好,我正在尝试解析数据,我得到了一个 java.lang。返回 sSingleton.getApplicationContext() 时出现空异常;因此,您能帮帮我吗?

public class MainActivity extends AppCompatActivity {


private VolleySingleton mVolleySingleton;
private RequestQueue mRequestQueue;
private ArrayList<ParseMe> listblogs = new ArrayList<>();
private static final String URL_GET="bestUrl";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    final TextView ChangeMe = (TextView) findViewById(R.id.ChangeMeTextView);
    Button SunnyButton = (Button) findViewById(R.id.SunnyButton);
    Button FoggyButton = (Button) findViewById(R.id.FoggyButton);
    setSupportActionBar(toolbar);

    mVolleySingleton = VolleySingleton.getInstance();
    mRequestQueue = mVolleySingleton.getRequestQueue();
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_GET, (String) null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            ToastTest.m(this.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mRequestQueue.add(request);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

我还设置了一个单例,有一个单例应用程序和一个 volleysingleton

import android.app.Application;

导入android.content.Context;

public class MyApplicationSingleton extends Application{
private static MyApplicationSingleton sSingleton;
@Override
public void onCreate() {
    super.onCreate();
    sSingleton=this;
}
public static MyApplicationSingleton getSingleton(){
    return sSingleton;
}
public static Context getAppContext(){
    return sSingleton.getApplicationContext();
}

} VolleySingleton 类

 public class VolleySingleton {
private static VolleySingleton sSingleton=  null;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private VolleySingleton() {

    mRequestQueue = Volley.newRequestQueue(MyApplicationSingleton.getAppContext());
    mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {

        private LruCache<String, Bitmap> cache = new LruCache<>((int) Runtime.getRuntime().maxMemory() / 1024 / 8);

        @Override
        public Bitmap getBitmap(String url) {

            return cache.get(url);
        }

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

        }
    });

}

//if our object is equal to null we are going to want to create a new instance of it
public static VolleySingleton getInstance() {
    if (sSingleton == null) {
        sSingleton = new VolleySingleton();
    }
    return sSingleton;
}

public RequestQueue getRequestQueue() {
    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}

}

【问题讨论】:

标签: java android android-volley


【解决方案1】:

删除 MyApplicationSingleton 类并尝试以下操作:

 private static VolleySingleton ourInstance;
 private ImageLoader imageLoader;
 private RequestQueue requestQueue;
 private static Context context;

 public static synchronized VolleySingleton getInstance(Context context) {
        if (ourInstance == null) {
            ourInstance = new VolleySingleton(context.getApplicationContext());
        }
        return ourInstance;
    }

    private VolleySingleton(Context context) {
        VolleySingleton.context = context;
        requestQueue = getRequestQueue();
        imageLoader = new ImageLoader(requestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<>((int) Runtime.getRuntime().maxMemory() / 1024 / 8);

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

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

    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        }
        return requestQueue;
    }

【讨论】:

  • 为什么要删除应用程序?我会把 VolleySingleton 移到 Application 类中
  • 来自 Google 文档:“通常不需要继承 Application。在大多数情况下,静态单例可以以更模块化的方式提供相同的功能”(developer.android.com/intl/es/reference/android/app/…)
  • 明白了。我通常只是默认使用应用程序扩展,因为扔单例是不好的做法
【解决方案2】:

假设您在清单中使用android:name=". MyApplicationSingleton"application 标记中声明了应用程序,那么此方法是不必要的。

public static Context getAppContext(){
    return sSingleton.getApplicationContext();
}

应用程序上下文 MyApplicationSingleton,因为在 Android 中是 Application extends Context

在未声明的应用程序上调用此方法会丢失清单定义,但会抛出 NullPointerException


另外,听起来你没有完全遵循README

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多