How to remove this update icon? Android Swiperefersh - android

CODE
public class YellowFragment extends Fragment implements FlowerAdapter.FlowerClickListener{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_yellow, container, false);
swipeContainer_yellow = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer_yellow);
setRetainInstance(true);
mReferSharedPreference = new ReferSharedPreference(getContext());
mlat = mReferSharedPreference.getValue("Lat", "None");
mlon = mReferSharedPreference.getValue("Lon", "None");
mCoordinatesTextLinear = (TextView) view.findViewById(R.id.tv_coordinates_linear);
if(!mlat.equals("None")){
getLinearPosts();
}
else {
Toast.makeText(getContext(), "Choose your location", Toast.LENGTH_LONG).show();
}
swipeContainer_yellow.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if(!mlat.equals("None")){
getLinearPosts();
}
else {
Toast.makeText(getContext(), "Choose your location", Toast.LENGTH_LONG).show();
}
}
});
configViews(view);
return view;
}
private void getLinearPosts() {
ReferSharedPreference preferenceCoordinates = new ReferSharedPreference(getContext());
String lat = preferenceCoordinates.getValue("Lat", "None");
String lon = preferenceCoordinates.getValue("Lon", "None");
mCoordinatesTextLinear.setText("Your Location :" + lat + " , " + lon);
mRestManager = new RestManager();
Call<List<Flower>> listCall = mRestManager.getmFlowerApiService(getActivity()).getAllFlowers(lat, lon);
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
mFlowerAdapter.clear();
List<Flower> flowerList = response.body();
for(int i =0; i<flowerList.size(); i++) {
Flower flower = flowerList.get(i);
mFlowerAdapter.addFlower(flower);
}
swipeContainer_yellow.setRefreshing(false);
}
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
}
});
}
In this code, when i swipe, if mlat is None, there is swipe updating icon and it's not disappear.
What i wanted is that if mlat has some value, do getLinearPosts();, but if mlat has None, show Toast "Choose your location".
but refershing icon do not disappear
like this
Question: How can i disappear this updating or refreshing icon when mlat is None?

After your task is completed, just call swipeContainer_yellow.setRefreshing(false) and it will hide that progressbar
As i can see you have already used it, but problem is you are assuming that your response will be perfect all the time. So instead of keeping it inside if (response.isSuccessful()), keep it outside if condition and also put it in onFailure()
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
swipeContainer_yellow.setRefreshing(false);
if (response.isSuccessful()) {
mFlowerAdapter.clear();
List<Flower> flowerList = response.body();
for(int i =0; i<flowerList.size(); i++) {
Flower flower = flowerList.get(i);
mFlowerAdapter.addFlower(flower);
}
}
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
swipeContainer_yellow.setRefreshing(false);
}
});

Related

Android Yandex Mapkit search request by point or by name always return null values,why?

This is my example where I am tapping on the map to get the tapped point coordinates and to send a search request to know more details about that place, for example, city, street. But the response is always null values.
public class MainActivity extends AppCompatActivity implements CameraListener, InputListener, Session.SearchListener {
private ActivityMainBinding binding;
private SearchManager searchManager;
private Session searchSession;
private SearchOptions searchOptions;
private MapObjectCollection mapObjectCollection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapKitFactory.setApiKey("your api key");
MapKitFactory.initialize(this);
searchOptions = new SearchOptions();
searchOptions.setSearchTypes(SearchType.GEO.value);
searchOptions.setGeometry(true);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.mapview.getMap().setNightModeEnabled((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES);
searchManager = SearchFactory.getInstance().createSearchManager(SearchManagerType.COMBINED);
binding.mapview.getMap().addCameraListener(this);
binding.mapview.getMap().addInputListener(this);
mapObjectCollection = binding.mapview.getMap().getMapObjects();
binding.mapview.getMap().move(
new CameraPosition(new Point(55.751574, 37.573856), 11.0f, 0.0f, 0.0f),
new Animation(Animation.Type.SMOOTH, 0),
null);
}
#Override
protected void onStop() {
super.onStop();
binding.mapview.onStop();
MapKitFactory.getInstance().onStop();
}
#Override
protected void onStart() {
super.onStart();
binding.mapview.onStart();
MapKitFactory.getInstance().onStart();
}
public void submitQueryByName(String query) {
searchSession = searchManager.submit(
query,
Geometry.fromPoint(new Point(40.177200, 44.503490)),
searchOptions,
this);
}
public void submitQueryByPoint(Point point) {
searchSession = searchManager.submit(
point,
11,
searchOptions,
this);
}
#Override
public void onCameraPositionChanged(#NonNull Map map, #NonNull CameraPosition cameraPosition, #NonNull CameraUpdateReason cameraUpdateReason, boolean finished) {
Log.e("onCameraPositionChanged"," cameraPosition: "+cameraPosition+" cameraUpdateReason: "+cameraUpdateReason+" finished: "+finished);
}
#Override
public void onMapTap(#NonNull Map map, #NonNull Point point) {
MapObjectCollection mapObjects = binding.mapview.getMap().getMapObjects();
mapObjects.clear();
PlacemarkMapObject placemarkMapObject = mapObjectCollection.addPlacemark(new Point(point.getLatitude(), point.getLongitude()),
ImageProvider.fromResource(this, R.mipmap.marker_flag));
submitQueryByPoint(point);
Log.e("onMapTap", "point lat - lang: " + point.getLatitude() + " : " + point.getLongitude());
}
#Override
public void onMapLongTap(#NonNull Map map, #NonNull Point point) {
Log.e("onMapLongTap","onMapLongTap");
}
#Override
public void onSearchResponse(#NonNull Response response) {
try {
Log.e("Search", "Response: " + response);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
public void onSearchError(#NonNull Error error) {
String errorMessage = "unknown_error_message";
if (error instanceof RemoteError) {
errorMessage = "remote_error_message";
} else if (error instanceof NetworkError) {
errorMessage = "network_error_message";
}
Log.e("Response error", " error: " + errorMessage);
}
}
In the onMapTap method, I get the tapped point coordinates and send a search request by point
#Override
public void onMapTap(#NonNull Map map, #NonNull Point point) {
MapObjectCollection mapObjects = binding.mapview.getMap().getMapObjects();
mapObjects.clear();
PlacemarkMapObject placemarkMapObject = mapObjectCollection.addPlacemark(new Point(point.getLatitude(), point.getLongitude()),
ImageProvider.fromResource(this, R.mipmap.marker_flag));
submitQueryByPoint(point);
Log.e("onMapTap", "point lat - lang: " + point.getLatitude() + " : " + point.getLongitude());
}
**Response is always null values. What I do wrong?
This is a GitHub whole project for this example https://github.com/davmehrabyan/YandexMapSearch **

application blank after move to another fragment using bottom navigation view

I tried to build an app that have 5 fragment that displayed using bottom navigation view. I use volley to get the data from database. i have a problem with calling the data. at fragment A. i call the web service and got some data and then display it using recyclerview. But if i move to another fragment ( lets say fragment B) and went back to the fragment A. the data is lost and it just show the standard ui like search widget,spinner widget. All i want to ask is :
where should i put the code to call web service for all my fragment. On the activity that handle the fragment or just on the fragment?
why volley doesn't call data again when i back to the fragment?
this is the code of my mainactivity that contain bottom navigation view with 5 fragments:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkStatusAvialable (getApplicationContext())) {
bottomNavigationView=(BottomNavigationView)findViewById(R.id.main_nav);
frameLayout=(FrameLayout) findViewById(R.id.main_frame);
herbal= new herbal();
crude = new crude();
database=new database();
analysis=new analysis();
compound=new compound();
setFragment(herbal);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
default:
return false;
}
}
});
} else {
Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
this is the example in my fragment which calling web service and then display it using recycler view:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
herbalModels = new ArrayList<>();
kampoModels = new ArrayList<>();
searchHerbal = (EditText) rootView.findViewById(R.id.search_herbal);
searchHerbal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchHerb();
}
});
loadData = (ProgressBar) rootView.findViewById(R.id.loadRecyclerView);
RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
sortData(rootView);
get20DataJamu();
get20DataKampo();
StartRecyclerViewJamu(rootView);
return rootView;
}
private void searchHerb() {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
searchHerbs searchHerbs = new searchHerbs();
ft.replace(R.id.main_frame, searchHerbs);
ft.commit();
}
private void StartRecyclerViewKampo(View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
kampoAdapter = new kampoAdapter(mRecyclerView, getActivity(), kampoModels);
mRecyclerView.setAdapter(kampoAdapter);
kampoAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
kampoModels.add(null);
kampoAdapter.notifyItemInserted(kampoModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
kampoModels.remove(kampoModels.size() - 1);
kampoAdapter.notifyItemRemoved(kampoModels.size());
//add items one by one
int start = kampoModels.size();
int end = start + 20;
loadMoreKampo(start, end);
}
}, 5000);
}
});
}
private void loadMoreKampo(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
kampoAdapter.notifyItemInserted(kampoModels.size());
} catch (JSONException e) {
}
}
kampoAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void get20DataKampo() {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponsekampo" + jsonArray.toString());
Log.d(TAG, "lengthresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerrorkampo" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void StartRecyclerViewJamu(final View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new herbalAdapter(mRecyclerView, getActivity(), herbalModels);
mRecyclerView.setAdapter(mAdapter);
loadData.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mAdapter.notifyDataSetChanged();
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
herbalModels.add(null);
mAdapter.notifyItemInserted(herbalModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
herbalModels.remove(herbalModels.size() - 1);
mAdapter.notifyItemRemoved(herbalModels.size());
//add items one by one
int start = herbalModels.size();
int end = start + 20;
loadMoreJamu(start, end);
}
}, 5000);
}
});
}
private void get20DataJamu() {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
Log.d(TAG, "lengthonresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void loadMoreJamu(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
mAdapter.notifyItemInserted(herbalModels.size());
} catch (JSONException e) {
}
}
mAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void sortData(final View rootView) {
final Spinner spinner = (Spinner) rootView.findViewById(R.id.filter_herbal);
// Create an ArrayAdapter using the string array and a default spinner layout
List<categoriesHerbal> itemList = new ArrayList<categoriesHerbal>();
itemList.add(
new categoriesHerbal(
"1",
"Jamu"
)
);
itemList.add(
new categoriesHerbal(
"2",
"Kampo"
)
);
ArrayAdapter<categoriesHerbal> spinnerAdapter = new ArrayAdapter<categoriesHerbal>(getActivity(), android.R.layout.simple_spinner_item, itemList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewJamu(rootView);
} else {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewKampo(rootView);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
move your data code in separate class and call it wherever needed.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
/*default:
return false;*/ //no need for this one
}
return true; /*you forget'it*/
}

Socket IO runOnUiThread doesn't work

I have trouble with runOnUiThread in socket io. I use this library. I have listener for some event. If I get this event I change the image. But when I get event image stay as before and I don't understand why it's happen. Maybe someone help or explain me what I'm doing wrong. Thanks in advance. This is my code
private void online(){
SocketService.getSocket().on("online", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "online");
onlineOffline.setImageResource(R.drawable.online);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
private void offline() {
SocketService.getSocket().on("offline", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "offline");
onlineOffline.setImageResource(R.drawable.offline);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
EDIT!
Socket connected successfully and I can see message online/offline in the log. Also I debug code and don't show error. Full code
public class ProfileList extends Fragment implements View.OnClickListener{
private int pos=0;
private DecodeBitmap decodeBitmap=new DecodeBitmap();
private ArrayList<String> online = new ArrayList<>();
private ImageView onlineOffline;
private RelativeLayout callToRegion;
private Button callTo;
private Activity activity;
static ProfileList newInstance(int position, ArrayList<String> online) {
ProfileList pageFragment = new ProfileList();
Bundle arguments = new Bundle();
arguments.putInt("page", position);
arguments.putStringArrayList("online", online);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pos = getArguments().getInt("page");
online = getArguments().getStringArrayList("online");
Log.d("myLogs", "page pos: " + pos);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.profile_list_layout, container, false);
Log.d("myLogs","fragment onCreateView pos "+ pos);
callToRegion = (RelativeLayout) rootView.findViewById(R.id.callToRegion);
callTo = (Button) rootView.findViewById(R.id.callTo);
ImageView mainProfileIcon = (ImageView) rootView.findViewById(R.id.mainProfileIcon);
onlineOffline = (ImageView) rootView.findViewById(R.id.onlineOffline);
if(CallPageFragment.online.get(0).equals("empty")){
new LoadDataFromDatabase("relatives", getActivity(), "");
}
if(LoadDataFromDatabase.relativesData.size()==0){
DialogFragment dlgFragment = new ErrorPopupFragment();
int REQUEST_CODE_DIALOG = 101;
dlgFragment.setTargetFragment(this, REQUEST_CODE_DIALOG);
dlgFragment.setCancelable(true);
String dialogTitle = "error_dialog";
dlgFragment.show(getFragmentManager(), dialogTitle);
activity.onBackPressed();
}
else {
callTo.setText(LoadDataFromDatabase.relativesData.get(pos).getFirstName());
File imgFile = new File(LoadDataFromDatabase.relativesData.get(pos).getAvatar());
if (imgFile.exists()) {
mainProfileIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
mainProfileIcon.setImageBitmap(decodeBitmap.decodeSampledBitmapFromResource(LoadDataFromDatabase.relativesData.get(pos).getAvatar(), 300, 300));
}
}
Log.d("myLogs", "all relatives online" + online);
Log.d("myLogs", "all relatives" + LoadDataFromDatabase.relativesData.get(pos).getRelativesId());
if(online.size()==0){
onlineOffline.setImageResource(R.drawable.offline);
Log.d("myLogs", "online false");
}
else {
Log.d("myLogs", "online true " + pos + " " + LoadDataFromDatabase.relativesData.get(pos).getRelativesId());
for(int i=0;i<online.size();i++) {
if (LoadDataFromDatabase.relativesData.get(pos).getRelativesId().equals(online.get(i))) {
Log.d("myLogs", "online id " + LoadDataFromDatabase.relativesData.get(pos).getRelativesId() + " " + online.get(i) + " pos: " + pos);
onlineOffline.setImageResource(R.drawable.online);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
break;
}
else {
onlineOffline.setImageResource(R.drawable.offline);
callTo.setEnabled(false);
}
}
}
try {
MainActivity.textClock.setVisibility(View.VISIBLE);
}
catch(Throwable e) {
Log.d("myLogs", "WTF???!!!!", e);
}
online();
offline();
return rootView;
}
#Override
public void onClick(View v) {
CallPageFragment.currentPosition=pos;
Log.d("myLogs","save currentPosition " + CallPageFragment.currentPosition);
Bundle bundle = new Bundle();
bundle.putString("firstName", LoadDataFromDatabase.relativesData.get(pos).getFirstName());
bundle.putString("avatar", LoadDataFromDatabase.relativesData.get(pos).getAvatar());
bundle.putString("id", LoadDataFromDatabase.relativesData.get(pos).getRelativesId());
Fragment fragment = new CallToFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = activity.getFragmentManager();
fragmentManager.beginTransaction().addToBackStack(null).replace(R.id.content_frame, fragment).commit();
}
private void online(){
SocketService.getSocket().on("online", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "online");
onlineOffline.setImageResource(R.drawable.online);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
private void offline() {
SocketService.getSocket().on("offline", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "offline");
onlineOffline.setImageResource(R.drawable.offline);
callTo.setOnClickListener(ProfileList.this);
callToRegion.setOnClickListener(ProfileList.this);
}
});
}
});
}
#Override
public void onStop() {
super.onStop();
SocketService.getSocket().off("online");
SocketService.getSocket().off("offline");
}
}
I have already solved my issue. I dont know why, but runOnUiThread works fine. I three days tried to find whats wrong with my code and than it have just work. It's fully working code
private void online(){
if (SocketService.getSocket() != null)
SocketService.getSocket().on("online", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.d("myLogs", "online");
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "online");
onlineOffline.setImageResource(R.drawable.online);
callToRegion.setOnClickListener(ProfileList.this);
tvHelpDescription.setText("To call " + LoadDataFromDatabase.relativesData.get(pos).getFirstName() + " " +
LoadDataFromDatabase.relativesData.get(pos).getLastName() + " tap here");
CallPageFragment.arrow.setVisibility(View.VISIBLE);
}
});
}
});
else{
Log.e("myLogs", "Socket is null");
}
}
private void offline() {
if(SocketService.getSocket() != null) {
SocketService.getSocket().on("offline", new Emitter.Listener() {
#Override
public void call(Object... args) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("myLogs", "offline");
onlineOffline.setImageResource(R.drawable.offline);
callToRegion.setOnClickListener(null);
tvHelpDescription.setText("You can't call " + LoadDataFromDatabase.relativesData.get(pos).getFirstName() + " " +
LoadDataFromDatabase.relativesData.get(pos).getLastName() + " because she offline");
CallPageFragment.arrow.setVisibility(View.INVISIBLE);
}
});
}
});
}
else{
Log.e("myLogs", "Socket is null");
}
}

I get Null Pointer Exception when Android OS kills my app

I have a simple weather app that uses fragments to display the current, hourly and daily weather. I have noticed that when I open a heavy app (game) and then I try to open the my app it crashes with the null pointer exception because a fragment (maybe all of the 3) is not attached to the fragment manager.
I have experienced this crash many times but with no luck finding a solution to the problem. I have including a if-else statement to check if the fragment is attached (see the log). Why might I be getting the NPE?
Here is my log:
Getting first location updates...
01-22 22:02:05.362 14082-14082/koemdzhiev.com.stormy V/MainActivity: Locality: Aberdeen, CountryName United Kingdom
01-22 22:02:05.749 14082-14115/koemdzhiev.com.stormy D/MainActivity: OnResponse_ scheduledFuture is CANCELED
01-22 22:02:05.757 14082-14082/koemdzhiev.com.stormy D/MainActivity: isSuccessful - run on UNI threth (update display)...
01-22 22:02:05.787 14082-14082/koemdzhiev.com.stormy D/MainActivity: mCurrent fragment is NOT attached!
01-22 22:02:05.788 14082-14082/koemdzhiev.com.stormy D/AndroidRuntime: Shutting down VM
01-22 22:02:05.789 14082-14082/koemdzhiev.com.stormy E/AndroidRuntime: FATAL EXCEPTION: main
Process: koemdzhiev.com.stormy, PID: 14082
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:103)
at android.widget.Toast.makeText(Toast.java:260)
at koemdzhiev.com.stormy.ui.Hourly_forecast_fragment.setUpHourlyFragment(Hourly_forecast_fragment.java:128)
at koemdzhiev.com.stormy.ui.MainActivity$3$3.run(MainActivity.java:247)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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)
The problematic method in MainActivity:
public void getForecast(double latitude, double longitude) {
//scedule no response from the server task...
mScheduledFuture = exec.schedule(mNotAbleToGetWeatherDataTask,12, TimeUnit.SECONDS);
Log.d(TAG, "getForecast initiated...");
String API_KEY = "API_KEY";
String forecast = "https://api.forecast.io/forecast/" + API_KEY + "/" + latitude + "," + longitude + "?units=si";
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecast)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleSwipeRefreshLayoutsOff();
}
});
//on response from the server cansel the noResponseFromServer task
//on response from the server cansel the noResponseFromServer task
Log.d(TAG,"OnFailure_ scheduledFuture is CANCELED");
mScheduledFuture.cancel(true);
alertUserAboutError();
}
//when the call to the Okhttp library finishes, than calls this method:
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleSwipeRefreshLayoutsOff();
}
});
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "isSuccessful - run on UNI threth (update display)...");
if(mCurrent_forecast_fragment.isAdded()){
Log.d(TAG, "mCurrent fragment is attached!");
mCurrent_forecast_fragment.updateDisplay();
}else{
Toast.makeText(MainActivity.this, "mCurrent is not attached!", Toast.LENGTH_SHORT).show();
Log.d(TAG, "mCurrent fragment is NOT attached!");
adapter = null;
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs, mCurrent_forecast_fragment,
mHourly_forecast_fragment, mDaily_forecast_fragment);
}
mHourly_forecast_fragment.setUpHourlyFragment();
mDaily_forecast_fragment.setUpDailyFragment();
toggleSwipeRefreshLayoutsOff();
//set the isFirstTime to true so that the next refresh wont get location
isFirstTimeLaunchingTheApp = false;
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught:", e);
}
//on response from the server cansel the noResponseFromServer task
Log.d(TAG,"OnResponse_ scheduledFuture is CANCELED");
mScheduledFuture.cancel(true);
}
});
} else {
toggleSwipeRefreshLayoutsOff();
alertForNoInternet();
Log.d(TAG, "Alert No Internet" + 220);
//is there is no internet cancel the noResponseFromServer task
Log.d(TAG, "No internet _ scheduledFuture is CANCELED");
mScheduledFuture.cancel(true);
}
}
This is mCurrent fragment code (line 247 is this code:
mHourly_forecast_fragment.setUpHourlyFragment (in main activity))
public class Current_forecast_fragment extends Fragment {
private static final String TAG = "MainActivity";
private MainActivity mActivity;
TextView mTimeLabel;
TextView mTemperatureLabel;
TextView mHumidityValue;
TextView mPrecipValue;
TextView mSummaryLabel;
TextView mLocationLabel;
TextView mWindSpeedValue;
TextView mFeelsLike;
ImageView mIconImageView;
ImageView mDegreeImageView;
public SwipeRefreshLayout mSwipeRefreshLayout;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = ((MainActivity) getActivity());
// Log.d(mActivity.getClass().getSimpleName(),"OnCreateFragment");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "OnResume - Current Fragment called");
mActivity = ((MainActivity) getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.current_forefast_fragment, container, false);
mTimeLabel = (TextView)v.findViewById(R.id.timeLabel);
mTemperatureLabel = (TextView)v.findViewById(R.id.temperatureLabel);
mHumidityValue = (TextView)v.findViewById(R.id.humidityValue);
mPrecipValue = (TextView)v.findViewById(R.id.precipValue);
mSummaryLabel = (TextView)v.findViewById(R.id.summaryLabel);
mLocationLabel = (TextView)v.findViewById(R.id.locationLabel);
mWindSpeedValue = (TextView)v.findViewById(R.id.windSpeedValue);
mFeelsLike = (TextView)v.findViewById(R.id.feels_like_label);
mIconImageView = (ImageView)v.findViewById(R.id.iconImageView);
mDegreeImageView = (ImageView)v.findViewById(R.id.degreeImageView);
mSwipeRefreshLayout = (SwipeRefreshLayout)v.findViewById(R.id.current_swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.blue, R.color.green);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.d("TAG", "Swiping in current!");
//if there is internet and if the mSwipeRefreshLayout in the Hourly and daily fragments are not already running...
if (mActivity.isNetworkAvailable()) {
if (!mActivity.mHourly_forecast_fragment.mSwipeRefreshLayout.isRefreshing() && !mActivity.mDaily_forecast_fragment.mSwipeRefreshLayout.isRefreshing()) {
if (mActivity.isLocationServicesEnabled()) {
if (mActivity.latitude != 0.0 && mActivity.longitude != 0.0) {
mActivity.getForecast(mActivity.latitude, mActivity.longitude);
} else {
mActivity.getLocation();
}
}else{
mActivity.alertForNoLocationEnabled();
}
}else{
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(mActivity, "currently refreshing...", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(mActivity, "No Internet Connection!", Toast.LENGTH_LONG).show();
mSwipeRefreshLayout.setRefreshing(false);
}
}
});
//Start the swipe refresh layout on start up is internet available
if(mActivity.isNetworkAvailable())
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
Log.d("TAG","running swiping...");
}
});
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG, "OnDestroyView - Current Fragment called");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "OnDestroy - Current Fragment called");
}
public void updateDisplay() {
if(mActivity != null) {
Current current = mActivity.mForecast.getCurrent();
//setting the current weather details to the ui
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("At " + current.getFormattedTime() + " it is");
mHumidityValue.setText(current.getHumidity() + "%");
mPrecipValue.setText(current.getPrecipChange() + "%");
mSummaryLabel.setText(current.getSummery());
mWindSpeedValue.setText(current.getWindSpeed() + "");
mFeelsLike.setText("Feels like: " + current.getFeelsLike());
mLocationLabel.setText(mActivity.locationName);
Drawable drawable = ContextCompat.getDrawable(mActivity, current.getIconId());
mIconImageView.setImageDrawable(drawable);
}else{
Toast.makeText(getActivity(),"Could not update data at this time! Please, try again.",Toast.LENGTH_LONG).show();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
}
Line 128 in Hourly Activity:
public void setUpHourlyFragment(){
if (mActivity != null) {
// Toast.makeText(mActivity, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show();
//set to null to reset the old one and set a new adapter bellow...
mListView.setAdapter(null);
Hour[] hourlyForecast = mActivity.mForecast.getHourlyForecast();
mHours = Arrays.copyOf(hourlyForecast, hourlyForecast.length, Hour[].class);
HourListAdapter adapter = new HourListAdapter(mActivity, mHours);
mListView.setEmptyView(mEmptyTextView);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Hour h = mHours[position];
String time = h.getHour();
String temperature = h.getTemperature()+"";
String summary = h.getSummary();
String message = String.format("At %s it will be %s and %s",time,temperature,summary);
Toast.makeText(mActivity, message, Toast.LENGTH_LONG).show();
//play animations
YoYo.with(Techniques.Shake).duration(200).playOn(view);
}
});
}else{
//LINE 128 bellow...
Toast.makeText(getActivity(),"Main Activity is null in Hourly Fragment",Toast.LENGTH_LONG).show();
}
}
}
Please use instance of mActivity instead of getActivity() inside Toast (Line : 128).
`Toast.makeText(getActivity(),"Main Activity is null in Hourly Fragment",Toast.LENGTH_LONG).show();}`
As for extra check, provide a null check before making Toast on mActivity.

Unable to implement custom touch listener on google map support fragment android

I am trying to handle events apart from the onCamerachange Listener such as knowing the event when the camera is dragged and released. For that I have taken help of a custom touch fragment and touch wrapper to manage the touch events but without success.
Here is my main activity code :
public class PickupActivity extends LocationUtils implements OnMapReadyCallback, AddressSearchAdapter.ClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LatLng center;
private TextView pickupMarker;
private LinearLayout markerLayout, addressBox, confirmPickupLayout;
private EditText address, pincodeText, landmarkText;
private ImageView currentLocationButton;
private LatLng latLng, latLng1;
private JSONArray addressComponents, typesArray;
String formattedAddress;
String currentLatitude, currentLongitude;
private Toolbar toolbar;
private SharedPreferenceClass preferenceClass;
private String pincode, gPlaceId, city, country, state, premise, route, enteredText, pickupLat, pickupLong, currentGplaceId;
private AddressSearchAdapter mAdapter;
private RecyclerView mRecyclerView;
private ArrayList<com.packr.classes.Address> addressArrayList = new ArrayList<>();
private JSONObject locationObject, geometryObject;
private com.packr.classes.Address mAddress;
private int pickupToastVisible = 0;
private Boolean pickupLocationSet = false, isAddressTextEmpty = false;
private Button confirmPickupButton;
private Double a, b, x, y;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pickup);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initialize();
onClick();
onSearchTextChanged();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setLayoutManager(new MyLinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mAdapter = new AddressSearchAdapter(getApplicationContext(), this);
mAdapter.setClickListener(this);
mRecyclerView.setAdapter(mAdapter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Set Pickup Location");
setSupportActionBar(toolbar);
}
/**
* function to load map. If map is not created it will create it for you
* */
#Override
public void onResume() {
super.onResume();
}
public void initialize() {
confirmPickupLayout = (LinearLayout) findViewById(R.id.confirmPickupLayout);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
pickupMarker = (TextView) findViewById(R.id.locationMarkertext);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
address = (EditText) findViewById(R.id.addressText);
currentLocationButton = (ImageView) findViewById(R.id.current_location);
addressBox = (LinearLayout) findViewById(R.id.addressBox);
pincodeText = (EditText) findViewById(R.id.pincodeText);
landmarkText = (EditText) findViewById(R.id.landmarkText);
confirmPickupButton = (Button) findViewById(R.id.confirmPickup);
}
public void onClick() {
}
public void onSearchTextChanged() {
address.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() == 0 || s == "") {
isAddressTextEmpty = true;
if (mRecyclerView.getVisibility() == View.VISIBLE) {
mRecyclerView.setVisibility(View.GONE);
}
}
if (s.length() < 16) {
mRecyclerView.setVisibility(View.VISIBLE);
enteredText = s.toString().replace(" ", "");
if (isAddressTextEmpty) {
sendAutocompleteJsonRequest();
}
}
final List<com.packr.classes.Address> filteredModelList = filter(addressArrayList, s.toString());
mAdapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onMapReady(GoogleMap map) {
TouchableMapFragment mFragment;
mFragment = new TouchableMapFragment();
new MapStateListener(map,mFragment,this){
#Override
public void onMapTouched() {
// Map touched
L.m("touched");
}
#Override
public void onMapReleased() {
// Map released
L.m("released");
}
#Override
public void onMapUnsettled() {
// Map unsettled
L.m("unSettled");
}
#Override
public void onMapSettled() {
// Map settled
L.m("settled");
}
};
mMap = map;
map.setMyLocationEnabled(false);
currentLatitude = preferenceClass.getCurrentLatitude();
currentLongitude = preferenceClass.getCurrentLongitude();
a = Double.parseDouble(currentLatitude);
b = Double.parseDouble(currentLongitude);
latLng = new LatLng(Double.parseDouble(currentLatitude), Double.parseDouble(currentLongitude));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory
.fromResource(R.drawable.current_location_marker)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.moveCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(preferenceClass.getPickupAddress());
pincodeText.setText(preferenceClass.getPickupPincode());
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
if (confirmPickupLayout.getVisibility() == View.VISIBLE) {
confirmPickupLayout.setVisibility(View.GONE);
slideOutTowardsBottom();
}
center = mMap.getCameraPosition().target;
currentLatitude = String.valueOf(center.latitude);
currentLongitude = String.valueOf(center.longitude);
latLng1 = new LatLng(center.latitude, center.longitude);
Log.e("Coordinates", String.valueOf(center.latitude) + "," + String.valueOf(center.longitude) + latLng1);
pickupMarker.setText(" Set your Location ");
if (!pickupLocationSet) {
float[] distances = new float[1];
Location.distanceBetween(center.latitude, center.longitude, a, b, distances);
System.out.println("Distance: " + distances[0]);
if (distances[0] > 1000.0) {
sendJsonRequest();
L.m("called");
a = center.latitude;
b = center.longitude;
}
}
}
});
}
public void sendJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
//console test
parseJsonResponse(jsonObject);
if (formattedAddress == null) {
address.setText("Obtaining Address");
} else {
address.setText(formattedAddress);
}
Log.e("error", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
} else if (volleyError instanceof ServerError) {
} else if (volleyError instanceof NetworkError) {
} else if (volleyError instanceof ParseError) {
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
requestQueue.add(jsonObjectRequest);
}
public String getRequestUrl() {
return KEY_GEOCODE_URL +
currentLatitude + KEY_COMMA + currentLongitude +
KEY_SENSOR;
}
public void parseJsonResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(0);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
preferenceClass.savePickupGplaceId(gPlaceId);
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
pincodeText.setText(pincode);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getAutocompleteRequestUrl() {
return KEY_AUTOCOMPLETE_API.concat(enteredText);
}
public void sendAutocompleteJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getAutocompleteRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
mAdapter.setAddressArrayList(addressArrayList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
} else if (volleyError instanceof AuthFailureError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ServerError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof NetworkError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ParseError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
private void parseJSONResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(i);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
if (resultListObject.has(KEY_LOCATION) && !(resultListObject.isNull(KEY_LOCATION))) {
locationObject = resultListObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
if ((resultListObject.has(KEY_GEOMETRY)) && !(resultListObject.isNull(KEY_GEOMETRY))) {
geometryObject = resultListObject.getJSONObject(KEY_GEOMETRY);
if (geometryObject.has(KEY_LOCATION) && !(geometryObject.isNull(KEY_LOCATION))) {
locationObject = geometryObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_CITY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
city = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_COUNTRY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
country = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_STATE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
state = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_PREMISE)) {
premise = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_ROUTE)) {
route = addressComponentsObject.getString(KEY_LONG_NAME);
}
}
}
if (country.contentEquals("India") && city.contentEquals("Kolkata")) {
mAddress = new com.packr.classes.Address();
mAddress.setFormattedAddress(formattedAddress);
mAddress.setCity(city);
mAddress.setCountry(country);
mAddress.setPincode(pincode);
mAddress.setState(state);
mAddress.setStreet(premise);
mAddress.setRoute(route);
mAddress.setLatitude(currentLatitude);
mAddress.setLongitude(currentLongitude);
mAddress.setGplaceId(gPlaceId);
addressArrayList.add(mAddress);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private List<com.packr.classes.Address> filter(List<com.packr.classes.Address> models, String query) {
query = query.toLowerCase();
final List<com.packr.classes.Address> filteredModelList = new ArrayList<>();
for (com.packr.classes.Address model : models) {
final String text = model.getFormattedAddress().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public void slideInFromBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_in_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
public void slideOutTowardsBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_out_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
// to check whether location services are enable or not
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
#Override
public void itemClicked(View view, int position) {
hideKeyboard();
confirmPickupLayout.setVisibility(View.VISIBLE);
slideInFromBottom();
mRecyclerView.setVisibility(View.GONE);
pickupLat = addressArrayList.get(position).getLatitude();
pickupLong = addressArrayList.get(position).getLongitude();
preferenceClass.savePickupLatitude(currentLatitude);
preferenceClass.savePickupLongitude(currentLongitude);
String pincode = addressArrayList.get(position).getPincode();
currentGplaceId = addressArrayList.get(position).getGplaceId();
preferenceClass.savePickupGplaceId(currentGplaceId);
latLng = new LatLng(Double.parseDouble(pickupLat), Double.parseDouble(pickupLong));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(formattedAddress);
if (pincode != null) {
pincodeText.setText(pincode);
}
}
public Boolean validationCheck() {
if (address.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a pickup address");
} else if (pincodeText.getText().length() != 6) {
L.t(getApplicationContext(), "Pincode must contain 6 digits");
} else if (landmarkText.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a landmark");
} else return true;
return false;
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Here is the code for the custom Touch fragement. I have extended MapSupportFragment
public class TouchableMapFragment extends MapFragment {
private View mOriginalContentView;
private TouchableWrapper mTouchView;
public void setTouchListener(TouchableWrapper.OnTouchListener onTouchListener) {
mTouchView.setTouchListener(onTouchListener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
L.m("called");
mOriginalContentView = super.onCreateView(inflater, parent,
savedInstanceState);
mTouchView = new TouchableWrapper(getActivity());
mTouchView.addView(mOriginalContentView);
return mTouchView;
}
#Override
public View getView() {
return mOriginalContentView;
}
}
Here is the code for the touchWrapper
public class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
public void setTouchListener(OnTouchListener onTouchListener) {
this.onTouchListener = onTouchListener;
}
private OnTouchListener onTouchListener;
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onTouchListener.onTouch();
break;
case MotionEvent.ACTION_UP:
onTouchListener.onRelease();
break;
}
return super.dispatchTouchEvent(event);
}
public interface OnTouchListener {
void onTouch();
void onRelease();
}
}
Please help.

Categories

Resources