Volley Request Queue in Android Fragment (getApplicationContext may produce NullPointerException) - java

I just want to load data from my localhost using recyclerview inside fragment but nothing shows and it says getApplicationContext may produce NullPointerException.
The error is on the
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
I tried the code on main activity and it works fine.
public class UpdateFragment extends Fragment {
private static final String URL = "http://192.168.1.32/CAGELCOII_APP/api.php";
RecyclerView recyclerView;
ItemAdapter adapter;
List<Item> itemList;
public UpdateFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_update, container, false);
itemList = new ArrayList<>();
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
loadItem();
adapter = new ItemAdapter(getActivity(), itemList);
recyclerView.setAdapter(adapter);
return view;
}
private void loadItem(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0; i < products.length(); i++){
JSONObject productObject = products.getJSONObject(i);
int id = productObject.getInt("id");
String description = productObject.getString("description");
String agency = productObject.getString("agency");
String date = productObject.getString("date");
String time = productObject.getString("time");
String image = productObject.getString("image");
Item item = new Item(id, description, agency, date, time, image);
itemList.add(item);
}
adapter = new ItemAdapter(getActivity(), itemList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
}
}

You'll have to make sure your fragment isAdded() to activity when calling getActivity() otherwise you'll get a NullPointerException since getActivity() returns the activity hosting the fragment.
If you always want to use application context, due to its non-dying lifecycle you can retrieve it across the entire app using this static function:
App.java
public class App extends Application {
private static Context sAppContext;
public void onCreate() {
super.onCreate();
sAppContext = this;
}
public static Context getContext() {
return sAppContext;
}
}
AndroidManifest.xml
...
<application
android:name=".App"
...>
</application>
And you can use it in your code as:
Volley.newRequestQueue(App.getContext()).add(stringRequest);

Please Try This code
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
mRequestQueue.add(jsonObjReq);
There are two way to hit volley request:
First
use app controller class
AppController
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new ImageClass());
}
return this.mImageLoader;
}
public void addToRequestQueue(Request req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public void addToRequestQueue(Request req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
**ImageClass **
public class ImageClass extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public ImageClass() {
this(getDefaultLruCacheSize());
}
public ImageClass(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
manifest
<application
android:allowBackup="true"
android:name=".AppController"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
android:name=".AppController"
add in menifest
MainActivity
String url = Global.BASE_URL + "api/";
StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, response.toString());
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Error Log
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
//Pass the parameters to according to the API.
Map<String, String> params = new HashMap<String, String>();
params.put("API_HASH", "hasKey");
Log.e(TAG, "splash paramsTest----" + params);
return params;
}
};
/* ----Adding request to request queue----*/
AppController.getInstance().addToRequestQueue(jsonObjReq,
GlobalString.cancel_login_api);
Second
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
mRequestQueue.add(jsonObjReq);

Related

Unable to start activity ComponentInfo : Attempt to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
NullPointerException addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
(8 answers)
Closed 4 years ago.
This is a barcode scanning app. It crashes when I scanned the code. If anyone knows how to fix help me out.
It crashes after I scanned the code from the ScanActivity.java and pass the object to the TicketResultActivity.javato display the result.
error
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.movietickets/info.androidhive.movietickets.TicketResultActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void info.androidhive.movietickets.MyApplication.addToRequestQueue(com.android.volley.Request)' on a null object reference
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// making toolbar transparent
transparentToolbar();
setContentView(R.layout.activity_main);
findViewById(R.id.btn_scan).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, ScanActivity.class));
}
});
}
private void transparentToolbar() {
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
}
private void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
ScanActivity.java
public class ScanActivity extends AppCompatActivity implements BarcodeReader.BarcodeReaderListener{
BarcodeReader barcodeReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
// get the barcode reader instance
barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_scanner);
}
#Override
public void onScanned(Barcode barcode) {
// playing barcode reader beep sound
barcodeReader.playBeep();
// ticket details activity by passing barcode
Intent intent = new Intent(ScanActivity.this, TicketResultActivity.class);
intent.putExtra("code", barcode.displayValue);
startActivity(intent);
}
#Override
public void onScannedMultiple(List<Barcode> list) {
}
#Override
public void onBitmapScanned(SparseArray<Barcode> sparseArray) {
}
/*#Override
public void onCameraPermissionDenied() {
finish();
}*/
#Override
public void onScanError(String s) {
Toast.makeText(getApplicationContext(), "Error occurred while scanning " + s, Toast.LENGTH_SHORT).show();
}
}
TicketResultActivity.java
public class TicketResultActivity extends AppCompatActivity {
private static final String TAG = TicketResultActivity.class.getSimpleName();
// url to search barcode
private static final String URL = "https://api.androidhive.info/barcodes/search.php?code=";
private TextView txtName, txtDuration, txtDirector, txtGenre, txtRating, txtPrice, txtError;
private ImageView imgPoster;
private Button btnBuy;
private ProgressBar progressBar;
private TicketView ticketView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_result);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
txtName = findViewById(R.id.name);
txtDirector = findViewById(R.id.director);
txtDuration = findViewById(R.id.duration);
txtPrice = findViewById(R.id.price);
txtRating = findViewById(R.id.rating);
imgPoster = findViewById(R.id.poster);
txtGenre = findViewById(R.id.genre);
btnBuy = findViewById(R.id.btn_buy);
imgPoster = findViewById(R.id.poster);
txtError = findViewById(R.id.txt_error);
ticketView = findViewById(R.id.layout_ticket);
progressBar = findViewById(R.id.progressBar);
String barcode = getIntent().getStringExtra("code");
// close the activity in case of empty barcode
if (TextUtils.isEmpty(barcode)) {
Toast.makeText(getApplicationContext(), "Barcode is empty!", Toast.LENGTH_LONG).show();
finish();
}
// search the barcode
searchBarcode(barcode);
}
/**
* Searches the barcode by making HTTP call
* Request was made using Volley network library but the library is
* not suggested in production, consider using Retrofit
*/
private void searchBarcode(String barcode) {
// making volley's json request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
URL + barcode, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Ticket response: " + response.toString());
// check for success status
if (!response.has("error")) {
// received movie response
renderMovie(response);
} else {
// no movie found
showNoTicket();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
showNoTicket();
}
});
MyApplication.getInstance().addToRequestQueue(jsonObjReq);
}
private void showNoTicket() {
txtError.setVisibility(View.VISIBLE);
ticketView.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
/**
* Rendering movie details on the ticket
*/
private void renderMovie(JSONObject response) {
try {
// converting json to movie object
Movie movie = new Gson().fromJson(response.toString(), Movie.class);
if (movie != null) {
txtName.setText(movie.getName());
txtDirector.setText(movie.getDirector());
txtDuration.setText(movie.getDuration());
txtGenre.setText(movie.getGenre());
txtRating.setText("" + movie.getRating());
txtPrice.setText(movie.getPrice());
Glide.with(this).load(movie.getPoster()).into(imgPoster);
if (movie.isReleased()) {
btnBuy.setText(getString(R.string.btn_buy_now));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
} else {
btnBuy.setText(getString(R.string.btn_coming_soon));
btnBuy.setTextColor(ContextCompat.getColor(this, R.color.btn_disabled));
}
ticketView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
} else {
// movie not found
showNoTicket();
}
} catch (JsonSyntaxException e) {
Log.e(TAG, "JSON Exception: " + e.getMessage());
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// exception
showNoTicket();
Toast.makeText(getApplicationContext(), "Error occurred. Check your LogCat for full report", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private class Movie {
String name;
String director;
String poster;
String duration;
String genre;
String price;
float rating;
#SerializedName("released")
boolean isReleased;
public String getName() {
return name;
}
public String getDirector() {
return director;
}
public String getPoster() {
return poster;
}
public String getDuration() {
return duration;
}
public String getGenre() {
return genre;
}
public String getPrice() {
return price;
}
public float getRating() {
return rating;
}
public boolean isReleased() {
return isReleased;
}
}
}
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class
.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
To initialize MyApplication properly you have to add the following in the AndroidManifest.xml
<application android:name="com.package.subpackage.MyApplication">
...
</application>

Android volley singleton getInstance(this) fails when performing a http request

Am new to android and i have just checked out volley android library and i want to use it in my custom http request bu this fails with error in android studio at .getInstance
I have tried the following
So am using android studio and have the following folder structure
com.geowan .....
frontend
1.LoginActivity
helpers
ApiSingleTon
So in my ApiSingleton i have
public class ApiSingleton {
private static ApiSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private ImageLoader mImageLoader;
private ApiSingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
....stuff copy pasted from volley docs on IMage disc cache loader
}
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;
}
}
Now to my java login code i have
ApiSingleton singleton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
trylogin(); //login method
}
});
}
tryLogin(){ //trying to emulate a http request
//proceed with authentication
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, loginurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
Log.i(TAG, error.toString());
}
});
}
singleton.getInstance(this).addToRequestQueue(jsonObjectRequest); //fails
The above throws an error at
singleton.getInstance(this)
Where could i be going wrong.
First I guess you Need To Read More About Singleton
Second
singleton.getInstance(this)
this Means You Have A Function Called getInstance return the class type in your class
So I guess You Need to Add this
public static synchronized AppSingleton getInstance(Context context) {
if (mAppSingletonInstance == null) {
mAppSingletonInstance = new AppSingleton(context);
}
return mAppSingletonInstance;
}

Volley error occurs while swiping between fragments/viewpager

In my activity all tabs are created as dynamic. Each swiping json data is called. The volley error occurs after a number of swiping. After this , no data is available on fragment and any of the other pages. This is my code
fragmentParent.addPage(jsonObject.getString("name"),jsonObject.getString("cat_id"),shop_id);
public class FragmentParent extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter1 adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
adapter = new ViewPagerAdapter1(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
}
public void addPage(String pagename, String id,String shop_id) {
Bundle bundle = new Bundle();
bundle.putString("data", id);
bundle.putString("shop_id", shop_id);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
public class FragmentChild extends Fragment {
String childname,shoppe_id;
RecyclerView imgflag;
CategoryItemAdapter categoryItemAdapter;
HttpStack stack;
List<ShopDetails> cat_item_list;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
shoppe_id=bundle.getString("shop_id");
stack = new HurlStack();
imgflag=(RecyclerView)view.findViewById(R.id.imgflag);
cat_item_list = new ArrayList<ShopDetails>();
categoryItemAdapter = new CategoryItemAdapter(getActivity(),cat_item_list);
GridLayoutManager layoutManager
= new GridLayoutManager(getActivity(),1, GridLayoutManager.VERTICAL,false);
imgflag.setLayoutManager(layoutManager);
imgflag.setAdapter(categoryItemAdapter);
getCategoryItem(childname);
return view;
}
public void getCategoryItem(String cat_id)
{
stack = new HurlStack(null, createSslSocketFactory());
final RequestQueue requestQueue = Volley.newRequestQueue(getActivity(),stack);
String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("0 results"))
{
}
else
{
try {
JSONArray jsonArray=new JSONArray(response);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
ShopDetails shopDetails=new ShopDetails();
shopDetails.setItem_name(jsonObject.getString("item_name"));
shopDetails.setItem_image(jsonObject.getString("image"));
shopDetails.setItem_price(jsonObject.getString("price"));
shopDetails.setItem_desc(jsonObject.getString("ingredients"));
cat_item_list.add(shopDetails);
}
if(cat_item_list!=null)
{
categoryItemAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Unable to connect. Please check your connection.", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("shoppe_id", shoppe_id);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
stringRequest.setShouldCache(false);
requestQueue.add(stringRequest);
}
private static SSLSocketFactory createSslSocketFactory() {
TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
SSLContext sslContext = null;
SSLSocketFactory sslSocketFactory = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, byPassTrustManagers, new SecureRandom());
sslSocketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Log.e(TAG, StringUtils.EMPTY, e);
} catch (KeyManagementException e) {
Log.e(TAG, StringUtils.EMPTY, e);
}
return sslSocketFactory;
}
public final boolean isInternetOn() {
ConnectivityManager connec = (ConnectivityManager) getActivity().getSystemService(getActivity().getBaseContext().CONNECTIVITY_SERVICE);
if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
return true;
} else if (
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
return false;
}
return false;
}
}
you need to use validation while receiving response from volley just use condition like that :
if(response!=null&&response.length()>10){
try {
JSONArray jsonArray=new JSONArray(response);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
ShopDetails shopDetails=new ShopDetails();
shopDetails.setItem_name(jsonObject.getString("item_name"));
shopDetails.setItem_image(jsonObject.getString("image"));
shopDetails.setItem_price(jsonObject.getString("price"));
shopDetails.setItem_desc(jsonObject.getString("ingredients"));
cat_item_list.add(shopDetails);
}
if(cat_item_list!=null)
{
categoryItemAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Log.e("invalid","invalide responce");
}
OR
also add condition on :
cat_id!=0 OR cat_id!=null
String url=config.api_url+"view_cat_item.php?cat_id="+cat_id;
I think it happens because when you switch fragments volley create request again and again. so you can cancel volley request when you leave from fragments by override onStop() method
#Override
public void onStop() {
super.onStop();
VolleySingleton.getInstance(getActivity()).getRequestQueue().cancelAll(VolleySingleton.TAG);
}
you can set Tag like this
jsonObjectRequest.setTag(VolleySingleton.TAG);
VolleySingleton.java
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "tagData";
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(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;
}
}

Fingerprint AuthenticationCallback in LoginActivity

How can I call the method "loginprep" of the LoginActivityClass from the FingerPrintClass?
See in the code...I wrote in where I want to call the loginprep with: "//Here I need the method loginprep() from the LoginActivity class"
FingerprintHandler.java
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
Toast.makeText((Activity)context, "Fingerprint Authentication error.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText((Activity)context, "Fingerprint Authentication help.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationFailed() {
Toast.makeText((Activity)context, "Fingerprint Authentication failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
//Here I need the method loginprep() from the LoginActivity class
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
public void loginprep() {
SharedPreferences sharedPreferencesF = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPreferencesF.getString("username", "");
String pwd = sharedPreferencesF.getString("password", "");
loginUser(urn, pwd);
}
private void launchHomeScreen() {
Intent homeActivity = new Intent (LoginActivity.this,HomeActivity.class);
LoginActivity.this.startActivity(homeActivity);
finish();
}
public void loginUser(final String urn, final String pwd){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + urn,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", urn);
editor.putString("password", pwd);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,urn);
params.put(KEY_PASSWORD,pwd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Following:
MainActivity mActivity = new MainActivity();
this is not the way Android is expecting you to create new instances of an activity, normally you wait the onCreate callback as described in the activity lifeCycle...
no following that approach you will need another way to communicate 2 different activities, what way must be taken depends on the specific arch of your application... the most commonly implemented could be using self defined interfaces and implement you custom callbacks...
You're writing a FingerPrint callback class, which means there is some onAuthenticationSucceeded method that is called when the "authentication succeeds."
How about you implement your own callback to pass back into the LoginActivity?
In other words, you'd
1) Write an interface
public interface LoginListener {
void onLoginSuccess();
void onLoginFailed();
}
2) Have the Activity implements LoginListener and have the Activity method of onLogin do your non-static stuff with the SharedPreferences,
public class LoginActivity extends AppCompatActivity
implements LoginListener {
public static final String KEY_USERNAME = "username";
public static final String KEY_PASS = "password";
private FingerprintHandler fingerprintHandler;
#Override
public void onLoginFailed() { }
#Override
public void onLoginSuccess() {
SharedPreferences sharedPrefs = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPrefs.getString(KEY_USERNAME, "");
String pwd = sharedPrefs.getString(KEY_PASS, "");
loginUser(urn, pwd);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_login);
fingerprintHandler = new FingerprintHandler(this);
}
// public void loginUser(final String urn, final String pwd){ }
}
3) Expect to pass in a LoginListener as a parameter to that separate class.
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private final Context mContext;
private LoginListener mListener;
// Constructor
public FingerprintHandler(Context context) {
mContext = context;
if (context instanceof LoginListener) {
this.mListener = (LoginListener) context;
} else {
throw new ClassCastException("FingerprintHandler: context must implement LoginListener!");
}
}
4) And you do then can use your callback from the other callback.
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
if (mListener != null) {
mListener.onLoginSuccess();
}
}

Android - NullPointerException hashCode() on a null object Reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help Me, I have Error when i want to POST JSON from my register (frmDaftar) class to WebService, error code is : java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.(Request.java:136)
public class frmDaftar extends AppCompatActivity {
Button btnDaftar, btnKembali;
EditText email, pass, nama;
AlertDialog alertDialog;
private static final String TAG = frmDaftar.class.getSimpleName();
SessionManager session;
private String EmailView;
private ProgressDialog pDialog;
private static final String Key_nama = "nama";
private static final String Key_email = "email";
private static final String Key_password = "password";
private static final String url = "Webservice_Controller.URL_DAFTAR";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frm_daftar);
btnDaftar = (Button) findViewById(R.id.btnDaftar1);
btnKembali = (Button) findViewById(R.id.btnKembali);
email = (EditText) findViewById(R.id.txtEmailDaftar);
pass = (EditText) findViewById(R.id.txtPasswordDaftar);
nama = (EditText) findViewById(R.id.txtNamaDaftar);
session = new SessionManager(getApplicationContext());
btnDaftar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnDaftar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emails = email.getText().toString().trim();
String passwords = pass.getText().toString().trim();
String namas = nama.getText().toString().trim();
registerUser(emails, passwords,namas);
//alertDialog.show();
}
});
}
});
btnKembali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(frmDaftar.this, frmLogin.class));
}
});
}
private void initCustomAlertDialog(String EmailView) {
View v = getLayoutInflater().inflate(R.layout.dialogverivikasi, null);
TextView txtEmail = (TextView) findViewById(R.id.lblemailDaftar);
//txtEmail.setText(EmailView);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setView(v);
alertDialog.setTitle("Verifikasi Email");
}
private void registerUser(final String nama, final String email, final String pass){
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Webservice_Controller.URL_DAFTAR,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
}catch (JSONException e) {
e.printStackTrace();
} {
}
//Toast.makeText(DataSent.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(DataSent.this,error.toString(),Toast.LENGTH_LONG).show();
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("name", nama);
params.put("email", email);
params.put("password", pass);;
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
Here is my AppController
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Help Me Please, This is my first android project :)
Double check that you added your app controller in your applicaiton tag. Hope it'll fix your crash.
<application
android:name="AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">

Categories

Resources