2016-02-14 6 views
0

Основная активность класса Привет, ребята, я пытаюсь разобрать данные, и я получаю java.lang. null исключение при возврате sSingleton.getApplicationContext(); Поэтому, пожалуйста, помогите мне?Получение NullPointerException при попытке использовать Volley singleton

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; 
} 

}

+0

Если продлить приложение, вы должны объявить его в вашем манифесте –

+0

Возможный дубликат [Расширение приложения для совместного использования переменных по всему миру] (http://stackoverflow.com/questions/4572338/extending-application-to-share-variables-globally) –

+1

Пожалуйста, не отказывайтесь от вандализма Ваше сообщение. Вы можете пометить его и попросить его быть отстраненным от вашей учетной записи, если хотите. – Undo

ответ

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; 
    } 
+0

Зачем удалять приложение? Я бы переместил VolleySingleton в класс приложения –

+0

Из документа Google: «Обычно нет необходимости в подклассе Application. В большинстве случаев статические синглтоны могут обеспечивать такую ​​же функциональность более модульным способом» (http://developer.android .com/intl/es/reference/android/app/Application.html) – cherif

+0

Gotcha. Обычно я просто по умолчанию добавляю расширения приложения, потому что бросать вокруг синглонов - это плохая практика –

0

Предполагая, что вы заявили приложения в манифесте, используя android:name=". MyApplicationSingleton" в пределах application, то этот метод не нужен.

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

Контекст приложения являетсяMyApplicationSingleton потому Application extends Context в Android.

Вызов этого метода на необъявленной Application из отсутствует явное определение, однако, будет бросать NullPointerException


Кроме того, это звучит, как вы штрафной полностью следовать README

Смежные вопросы