MapView Null Pointer Exception - java

I've finished my Hello MapView tutorial but there is a problem in application when I touch the market it just force closes and in LogCat shows java.lang.NullPointerException .
Here is the code:
package rs.iz.stevy.wifi;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
public class WiFiKupacicaActivity extends MapActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapa= (MapView) findViewById(R.id.Mapa1);
mapa.setBuiltInZoomControls(true);
mapa.setSatellite(true);
List<Overlay> mapOverlays = mapa.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.green);
MapOverlay itemizedoverlay = new MapOverlay(drawable);
GeoPoint point = new GeoPoint(19240000,-99120000);
OverlayItem overlayitem = new OverlayItem(point, "Hello","Just don't force close");
GeoPoint point2 = new GeoPoint(35410000, 139460000);
OverlayItem overlayitem2 = new OverlayItem(point2, "Sekai, konichiwa","Japan!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
itemizedoverlay.addOverlay(overlayitem2);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
And the second class:
package rs.iz.stevy.wifi;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import android.app.AlertDialog;
import android.content.Context;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class MapOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem>mOverlays= new ArrayList<OverlayItem>();
private Context mContext;
public MapOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i); }
#Override
public int size() {
return mOverlays.size();
}
//itemizedoverlay.addOverlay(overlayitem);
//mapOverlays.add(itemizedoverlay);
//#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
I think problem is probably somewhere about context = mContext; but I can't find where error could be. Please I'll appreciate any help.

Yes it is the context, the onTap method doesn't know what it is, so replace:
public MapOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
with
public MapOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
and your calls to the constructor
with
MapOverlay itemizedoverlay = new MapOverlay(drawable, this);

Related

Attempt to invoke virtual method [Null object reference] [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm spending the last 5 days trying solve this problem. I really do not have any idea about how to solve it. I'm getting Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference. Check my code:
RecyclerView.java
package etes.xdda.music;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
Context mContext;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(Context mContext, List<mList> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void onClick(View view) {
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private TextView tv_url;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_list);
tv_author = (TextView) itemView.findViewById(R.id.author_list);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
Note that I'm invoking MainActivity.java in this part:
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
And here's my MainActivity.java
package etes.xdda.music;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
private String player_status = "playing";
private ImageButton player_img;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
meplayer.pauseAudio();
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
meplayer.startAudio();
player_status = "playing";
}
}
});
//menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0,0,0,0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
updateLayout();
}
});
mediaPlayer.start();
}
private static void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
And the part of code that is giving crash is this:
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
#edit: I have added this piece of code, I don't know if can help
fragmentList.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
MainActivity activity;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(activity, lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
Please, help me, I have no more ideas about what I should do. Thank you
Just taking a look at your code, it looks like you are doing many things wrong. Such as this line
MainActivity a = new MainActivity();
You can't instantiate lifecycle components like Services, Activities, Fragments etc this way. Android provides you these components when you call start methods etc. The activity that is created as a result of the above line doesn't go through the lifecycle calls that an activity that is started via using startActivity. As a result, the setContentView of the activity is never called and you get this error. You have to remove this line and implement this properly and the error will go away.
Also just to add, you are actually creating a new instance of the activity when one is already running when you need to call the methods on the old instance that was started.
Edit: Try like this.
MainActivity activity;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
And then
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
Also remove static from the main activity functions

Cannot resolve symbol "GooglePlayServicesClient"

In Google play service 10.0.1, for the following code, when building it I get the error:
“GooglePlayServicesClient” cannot resolve the symbol
Any idea how to resolve this?
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationRequest;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.asyncTasks.EmployeeSerchResult;
import com.shuan.Project.asyncTasks.GetEmployeeSerach;
import com.shuan.Project.employer.PostViewActivity;
import java.util.List;
import java.util.Locale;
public class EmplyeeSearchActivity extends AppCompatActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private Toolbar toolbar;
private Common mApp;
private Boolean flag = false;
private LocationClient mLocationClient;
private ProgressDialog pDialog;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
private ProgressBar progressBar;
private ListView list;
private AutoCompleteTextView preferSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
mApp = (Common) getApplicationContext();
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
setTheme(R.style.Junior);
} else {
setTheme(R.style.Senior);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emplyee_search);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
toolbar.setBackgroundColor(getResources().getColor(R.color.junPrimary));
} else {
toolbar.setBackgroundColor(getResources().getColor(R.color.senPrimary));
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
mLocationRequest = new LocationRequest();
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
list = (ListView) findViewById(R.id.ser_res);
preferSearch = (AutoCompleteTextView) findViewById(R.id.prefered_serach);
new GetEmployeeSerach(EmplyeeSearchActivity.this, progressBar, preferSearch).execute();
preferSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_SEARCH){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
preferSearch.dismissDropDown();
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, preferSearch.getText().toString(),
"all").execute();
}
return false;
}
});
preferSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
TextView txt = (TextView) view.findViewById(R.id.display);
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
preferSearch.setText(txt.getText().toString());
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, txt.getText().toString(),
txt1.getText().toString()).execute();
}
});
preferSearch.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) {
}
#Override
public void afterTextChanged(Editable s) {
list.setAdapter(null);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
Intent in = new Intent(getApplicationContext(), PostViewActivity.class);
in.putExtra("jId", txt.getText().toString());
in.putExtra("apply", "no");
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.emp_search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.gps) {
flag = gpsStatus();
if (flag) {
new displayCurrentLocation().execute();
} else {
showGpsAlert();
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public class displayCurrentLocation extends AsyncTask<String, String, String> {
String location;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EmplyeeSearchActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Searching");
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Location currentLocation = mLocationClient.getLastLocation();
Geocoder geocoder = new Geocoder(EmplyeeSearchActivity.this, Locale.getDefault());
Location loc = currentLocation;
List<android.location.Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
final android.location.Address address = addresses.get(0);
location = address.getLocality();
}
} catch (Exception e) {
}
return location;
}
#Override
protected void onPostExecute(final String s) {
super.onPostExecute(s);
pDialog.cancel();
Intent in = new Intent(getApplicationContext(), EmployeeSearchResultActivity.class);
in.putExtra("loc", s);
startActivity(in);
}
}
private void showGpsAlert() {
AlertDialog.Builder build = new AlertDialog.Builder(EmplyeeSearchActivity.this);
build.setTitle("Alert")
.setMessage("Turn On your GPS! Find the Jobs & companies")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);
dialog.cancel();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "Can't Find Employer", Toast.LENGTH_SHORT).show();
}
}).show();
}
private Boolean gpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStus) {
return true;
} else {
return false;
}
}
}
as mentioned in this answer i guess GooglePlayServiceClient and has become outdated so remove it and use GoogleApiClientinstead.Also LocationServices.API, and FusedLocationProviderApi were introduced.
Usage of GoogleApiClient :
To use GoogleApiClient the first thing to change is the interface, the activity or service is implementing
//old code of GooglePlayServiceClient :
public class LocationMonitoringService extends Service implements GooglePlayServicesClient.ConnectionCallbacks
//replace the above ^ code with this: new code for GoogleApiClient
public class LocationMonitoringService extends Service implements GoogleApiClient.ConnectionCallbacks
in GooglePlayServiceClient, mLocationClient was just a regular class constructor.
inGoogleApiClient a Builder is used like :
//old code of GooglePlayServiceClient :
LocationClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
replace it^ with new builder code of GoogleApiClient :
GoogleApiClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationClient.connect();
}
Examples :
Requesting location :
Old code was just a simple call like
mLocationClient.requestLocationUpdates(mLocationRequest, locationListener);
in GoogleApiClient we use FusedLocatonApi like :
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, locationListener);
This post shows you a implementation of most of the methods like :onConnected onConnectionFailed onConnectionSuspended etc.

Android - GMapsV2 - Why is my activity not drawing the polyline?

I'm trying to get a red polyline to draw whenever the user moves. Here is the following code I have:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationSource, LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
LocationManager myLocationManager = null;
OnLocationChangedListener myLocationListener = null;
Criteria myCriteria;
Location lastLocationloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
//Register for location updates using a Criteria, and a callback on the specified looper thread.
myLocationManager.requestLocationUpdates(
0L, //minTime
0.0f, //minDistance
myCriteria, //criteria
this, //listener
null); //looper
//Replaces the location source of the my-location layer.
myMap.setLocationSource(this);
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#Override
protected void onPause() {
myMap.setLocationSource(null);
myLocationManager.removeUpdates(this);
super.onPause();
}
#Override
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
#Override
public void deactivate() {
myLocationListener = null;
}
/*#Override
public void onLocationChanged(Location location) {
if (myLocationListener != null) {
myLocationListener.onLocationChanged(location);
double lat = location.getLatitude();
double lon = location.getLongitude();
tvLocInfo.setText(
"lat: " + lat + "\n" +
"lon: " + lon);
}
}*/
#Override
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(location);
//Log.e(TAG, "Last LatLng is :"+lastLatLng);
//Log.e(TAG, "Last LatLng is :"+thisLatLng);
myMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(3).color(Color.RED));
lastLocationloc = location;
}
public static LatLng locationToLatLng(Location loc) {
if (loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
When I go to run application on an actual device nothing happens. No polyline appears. What am I doing wrong?

How to add balloons in OpenStreetMap?

How do I add balloons like those on Google Maps (such as the one shown here) into OpenStreetMap? This is my OpenStreetMap code below:
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
public class MainActivity extends Activity {
MyItemizedOverlay myItemizedOverlay = null;
private MapController myMapController;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
myMapController = mapView.getController();
myMapController.setZoom(16);
Drawable marker=getResources().getDrawable(android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new
DefaultResourceProxyImpl(getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().add(myItemizedOverlay);
GeoPoint myPoint1 = new GeoPoint(24.893379000000000000, 67.028060900000010000);
myItemizedOverlay.addItem(myPoint1, "myPoint1", "myPoint1");
GeoPoint myPoint2 = new GeoPoint(24.824796300000000000, 67.031565699999990000);
myItemizedOverlay.addItem(myPoint2, "myPoint2", "myPoint2");
}
}
import java.util.ArrayList;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IMapView;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable pDefaultMarker,
ResourceProxy pResourceProxy) {
super(pDefaultMarker, pResourceProxy);
// TODO Auto-generated constructor stub
}
public void addItem(GeoPoint p, String title, String snippet){
OverlayItem newItem = new OverlayItem(title, snippet, p);
overlayItemList.add(newItem);
populate();
}
#Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
protected OverlayItem createItem(int arg0) {
// TODO Auto-generated method stub
return overlayItemList.get(arg0);
}
#Override
public int size() {
// TODO Auto-generated method stub
return overlayItemList.size();
}
}
I was with the same question and now I found a way:
Download the osmbonuspack here: https://code.google.com/p/osmbonuspack/
Follow this code:
ArrayList<ExtendedOverlayItem> overlayItemArray = new ArrayList<ExtendedOverlayItem>();
ExtendedOverlayItem item = new ExtendedOverlayItem("Title, "Description, new GeoPoint(Double latitude, Double longitude), this);
//creates a layer with ballons
ItemizedOverlayWithBubble<ExtendedOverlayItem> poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, overlayItemArray, mapView, new CustomMapInfoWindow(mapView));
// add the layer
mapView.getOverlays().add(poiMarkers);
Create a class called CustomMapInfoWindow:
import org.osmdroid.bonuspack.overlays.DefaultInfoWindow;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.views.MapView;
public class CustomMapInfoWindow extends DefaultInfoWindow {
public CustomMapInfoWindow(MapView mapView) {
super(R.layout.bonuspack_bubble, mapView);
}
#Override
public void onOpen(ExtendedOverlayItem item) {
super.onOpen(item);
}
}
Go to OSMBONUSPACKDEMO REPOSITORY and get bonuspack_bubble.xml and the drawables into drawable-mdpi folder.
You should take a look at the osmbonuspack library, which is an add-on for osmdroid. It includes an overlay that will display popup balloons:
https://code.google.com/p/osmbonuspack/

Couldn't get connection factory client in logcat

I'm using an HTC Explorer to test my app
Everything was fine , till I altered the code to show my current location. The app works , but the following error is logged in on Logcat : Couldn't get connection factory client
Here is my code for MainActivity.java
package com.example.com.draft1;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.widget.Toast;
import com.google.android.maps.MapController;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends MapActivity {
private LocationManager lm;
public LocationListener locationListener;
// locationListener location =new MyLocationListener();
MapView mapView;
MapController mc;
GeoPoint p;
String coordinates[] = {"41.146064", "-80.642861"};
double lat=Double.parseDouble(coordinates[0]);
double lng=Double.parseDouble(coordinates[1]);
#Override
public void onCreate(Bundle savedInstanceState) {
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener =new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
p=new GeoPoint((int)(lat*1E6),(int)(lng*1E6));
mapView=(MapView)findViewById(R.id.mapView);
mc=mapView.getController();
mc.setCenter(p);
//mc.setZoom(13);
//mapView.invalidate();
//myMapController.setCenter(new GeoPoint((int)(lat*1E6),(int)(lng*1E6)));
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc) {
p=new GeoPoint((int)(loc.getLatitude()*1E6),(int)(loc.getLongitude()*1E6));
if(loc!= null) {
Toast.makeText(getBaseContext(),"Location : lat"+loc.getLatitude()+" Long "+loc.getLongitude(),Toast.LENGTH_SHORT).show();
}
mc.animateTo(p);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,int status,Bundle extras) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed()
{
//adssad
return false;
}
}
Why exactly is this happening ?
Any Possible solutions ?
I'd really appreciate some help with this
Cheers!
Random Error by Google it seems.Started working on its own :|

Categories