send latitude, longitude to mysql by JDBC every 30 seconds - mysql

currently I want to send my GPS latitude and longitude to MYSQL by use of JDBC.
To retrieve GPS lat, long I've used the code below and I have GPS tracker code in GPSTracker class. This would toast Latitude and Longitude by any time pressing the button.
public class MainActivity extends Activity {
Button btnShowLocation;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//testDB();
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
// txtv = (TextView) findViewById(R.id.txtv);
// btnShowLocation.setOnClickListener(this);
// txtv.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
// txtv = getText().getApplicationContext(this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
}
}
To send JDBC data to MYSQL, I've used the code below which can only send the values that I giving to it in parenthesis:
public class MainActivity extends Activity {
static final String USER = "root";
static final String PASS = "root";
GPSTracker gps;
double tmplat = 0;
double tmplong = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appDB();
}
public void appDB() {
// TextView tv = (TextView) this.findViewById(R.id.txtv);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
//connection to data base.
Connection con = DriverManager.getConnection("jdbc:mysql://192.168.1.6:3306/k_sql1", USER, PASS);
//create a statement
// String result = "Database connection successfull !\n";
Statement statement = con.createStatement();
// execute sql query
String sql = ("INSERT INTO `gps-data2`(`ID`,`Latitude`,`Longitude`) VALUES (1,123.45678, 345.678901);");
// String sql = (" CREATE TABLE IF NOT EXISTS GPS_data ( ID int, Latitude Double, Longitude Double ); INSERT INTO GPS_data (`ID`,`Latitude`,`Longitude`) VALUES (1,1234.5678,56789.123456); ");
statement.executeUpdate(sql);
// System.out.println("Inserted records into the table...");
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
enter code here
Please tell me how to combine these 2 systems and send GPS data (lat, lng) to mysql by use of JDBC method. I know it maybe better to use PHP but for this project I want it by use of JDBC. Appreciate if can give me a simple applicable solution.

This is the answer what I was looking for to retrieve GPS parameters programmatically and send it to database directly by use of onClickListener.
static final String USER = "root";
static final String PASS = "root";
String sql = null;
GPSTracker gps;
double tmplat = 0;
double tmplong = 0;
Button btnShowLocation;
double latitude;
double longitude;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.show_location);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is: \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
appDB();
} else {
gps.showSettingsAlert();
}
}
});
}
protected void appDB() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/k_sql1", USER, PASS);
String result = "Database connection successfull !\n";
Statement statement = con.createStatement();
String sql = ("INSERT INTO `gps-data2`(`Latitude`,`Longitude`) VALUES (" + latitude + ", " + longitude + ");");
statement.executeUpdate(sql);
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
f

Related

trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc

NetworkUtilities.java
public class NetworkUtilities {
private static final String TAG = NetworkUtilities.class.getSimpleName();
public static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
}catch (MalformedURLException e){
Log.v(TAG, "Problem building the Url");
}
return url;
}
public static String httpRequest(URL url) throws IOException{
String jsonResponse = "";
if(url ==null){
Log.v(TAG, "Url is null");
return jsonResponse;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200){
inputStream = httpURLConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
else{
Log.e(TAG, "Error response code" + httpURLConnection.getResponseCode());
}
}catch (IOException e){
Log.v(TAG, "Problem retrieving the json result", e);
}finally {
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
if(inputStream != null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader in = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bf = new BufferedReader(in);
String line = bf.readLine();
while(line != null){
output.append(line);
line = bf.readLine();
}
}
return output.toString();
}
public static List<String> extractFromJson(String jsonResponse){
if(TextUtils.isEmpty(jsonResponse)){
return null;
}
List<String> newsStories = new ArrayList<>();
try{
JSONObject baseObj = new JSONObject(jsonResponse);
JSONArray articlesArray = baseObj.getJSONArray("data");
for(int i=0;i<articlesArray.length();i++){
JSONObject currentArticle = articlesArray.getJSONObject(i);
JSONObject source = currentArticle.getJSONObject("source");
String sourceName = source.getString("name");
String title = currentArticle.getString("title");
String description = currentArticle.getString("description");
String newsStory = "Source" + sourceName + "/n" + title + "/n" + description;
newsStories.add(newsStory);
}
}catch (JSONException e){
Log.e(TAG, " Problem parsing the json string", e);
}
return newsStories;
}
NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context mContext;
private List<String> mNewsArticles;
NewsAdapter(Context context){
mContext = context;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(mContext)
.inflate(R.layout.news_list_item,parent, false);
view.setFocusable(true);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder( NewsViewHolder holder, int position) {
String currentArticle = mNewsArticles.get(position);
holder.mTextView.setText(currentArticle);
}
#Override
public int getItemCount() {
if(mNewsArticles != null){
return mNewsArticles.size();
}
return 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position :" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
}
public void setNewsData(List<String> newsData){
mNewsArticles = newsData;
notifyDataSetChanged();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private NewsAdapter mNewsAdapter;
private static final String BASE_URL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=13f428d687714c33a24f34ad6c5***87";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
mNewsAdapter = new NewsAdapter(this);
mRecyclerView.setAdapter(mNewsAdapter);
new FetchNewsArticle().execute(BASE_URL);
}
public class FetchNewsArticle extends AsyncTask<String, Void, List<String>>{
#Override
protected List<String> doInBackground(String... strings) {
String stringUrl = strings[0];
URL url = NetworkUtilities.createUrl(stringUrl);
String json = "";
try{
json = NetworkUtilities.httpRequest(url);
List<String> articles = NetworkUtilities.extractFromJson(json);
return articles;
}catch (Exception e){
e.printStackTrace();
Log.v(TAG, "Problem retrieving data");
return null;
}
}
#Override
protected void onPostExecute(List<String> strings) {
if(strings != null){
mNewsAdapter.setNewsData(strings);
}
}
}
Error
W/Zygote: Unable to open libbeluga.so: dlopen failed: library "libbeluga.so" not found.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/xample.newsfee: Accessing hidden method Landroid/view/View; >computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.newsfee: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
com.example.newsfeed V/NetworkUtilities: Problem retrieving the json result
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:46)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
2021-03-11 22:53:28.124 9391-9391/com.example.newsfeed W/Looper: PerfMonitor looperActivity : package=com.example.newsfeed/.MainActivity time=1ms latency=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running=212ms runnable=80ms io=11ms late=91ms h=android.app.ActivityThread$H w=159)
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM build : 979eaa0, I11632bc865
Build Date : 11/18/20
OpenGL ES Shader Compiler Version: EV031.32.02.00
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R1.11.00.00.604.067
Remote Branch : NONE
Reconstruct Branch : NOTHING
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Build Config : S P 10.0.6 AArch64
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
2021-03-11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: fail to open file: No such file or directory
The error seems to be: java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted.
Starting from Android 9, clear text http communication is disabled by default.
Check out the official Android documentation for this and also this question for further information.

org.json.JSONException: No value for opening_hours ,how to handle this type of error

logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)

400 error - The given location is invalid

I am trying to retrieve JSON data via an API and parsing it into my Android. I am trying to log the JSON data retrieved but I keep getting a "400 error - given location is invalid." The parameters to access the API seem correct but I am not sure why I can't retrieve the data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temperatureLabel = (TextView) findViewById(R.id.temperatureLabel);
timeLabel = (TextView) findViewById(R.id.timeLabel);
refreshButton = (ImageView) findViewById(R.id.refreshImage);
final double latitude = -104.8319;
final double longtitude = 39.7294;
refreshButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWeatherForecast(latitude, longtitude);
}
});
getWeatherForecast(latitude, longtitude);
}
public void getWeatherForecast(double latitude, double longtitude) {
String apiKey = "SECRET-KEY;
String forecastURL = "https://api.darksky.net/forecast/" + apiKey + "/" + latitude + ","
+ longtitude;
if (isNetworkAvailable()) {
//Build and HTTP request
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastURL).build();
//Make an Api call
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
alertUserError();
}
});
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.e(TAG, "JASON DATA" + jsonData);
if (response.isSuccessful()) {
mcurrentWeather = getCurrentWeatherDetails(jsonData);
// You want to update the display In the UI.
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "API call failed", Toast.LENGTH_LONG).show();
}
});
}
} catch (IOException e) {
Log.e(TAG, "Exception Caught");
} catch (JSONException e) {
Log.e(TAG, "JSONexception Caught");
}
}
});
} else {
alertUserError();
}
}
If you are trying to check what request you send to the API and what the API sends to you, then you should implement OkHttp logging interceptor. It's simple and easy to work with it.
First of all, I have deleted your secret key from your answer and replaced it with "SECRET-KEY". DarkSky is only free 1000 requests per day, so someone could grab that key and reuse it. You'd have to pay for it.
I would to go to https://darksky.net/dev/account and reset the secret key to avoid risks.
Second, your coordinates are swapped. You currently have
final double latitude = -104.8319;
final double longtitude = 39.7294;
String forecastURL = "https://api.darksky.net/forecast/" + apiKey + "/"
+ latitude + ","
+ longtitude;
That result of:
https://api.darksky.net/forecast/SECRET-KEY/-104.8319,39.7294?exclude=minutely,hourly,daily,flags,alerts
is then "400, Location invalid" because there is no location in the world with latitude -104 and longitude 39.
The correct one is
final double latitude = 39.7294;
final double longtitude = -104.8319;
Then your urlString is:
https://api.darksky.net/forecast/SECRET-KEY/39.7294,-104.8319?exclude=minutely,hourly,daily,flags,alerts
which outputs in the browser:
{
"latitude":39.7294,
"longitude":-104.8319,
"timezone":"America/Denver",
"currently":{
"time":1583068320,
"summary":"Mostly Cloudy",
"icon":"partly-cloudy-night",
"nearestStormDistance":9,
"nearestStormBearing":145,
"precipIntensity":0,
"precipProbability":0,
"temperature":37.32,
"apparentTemperature":33.14,
"dewPoint":18.62,
"humidity":0.46,
"pressure":1011.5,
"windSpeed":5.24,
"windGust":7.61,
"windBearing":157,
"cloudCover":0.87,
"uvIndex":0,
"visibility":10,
"ozone":309},
"offset":-7
}
P.S: Notice I included the exclude query item to shorten the response to show the example. Delete that part and you will have all the response, with minutely, daily and so on fields.

JavaFx combobox from mysql

Good Day I am completely new to coding. I am building an app which uses a combobox besides other library items. The problem I am facing is that while attempting to populate combobox items from a Mysql Db the item values get duplicated each time the drop down is clicked.
How I can keep this from happening ? I do understand that my approach itself could be erroneous.
#FXML
public void getStation() {
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
comboBoxStation.getItems().add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
Ok so I moved the function to the initialize() method in the controller and created an Observabale list called station
private ObservableList<String> stationsList = FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle rb) {
//
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
stationsList.add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
and then left only this line in the original function....seems to be working.
#FXML
private void getStation() {
comboBoxStation.setItems(stationsList);
}

Null map returned from supportmapfragment

I am trying to use Google Maps API v2 in my Android application. I have added the map fragment programmatically using following code and then I try getting the GoogleMap from my SupportMapFragment, but I always get null result back even though the map shows up on screen fine...Any help is highly appreciated!!!!!!!
Thanks
public class MapActivity extends BaseFragmentActivity {
private SchoolType mSchoolType=SchoolType.ALL;
private GoogleMap mMap;
private UiSettings mUiSettings;
private SupportMapFragment mMapFragment;
private static final String MAP_FRAGMENT_TAG = "map";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.map_activity);
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
if(mMapFragment==null)
addMapFragment();
setUpMapIfNeeded();
}
catch(Exception ex){
System.err.println("Exception: " + ex.getMessage());
}
}
private void addMapFragment(){
try{
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.zoomControlsEnabled(true) ;
mMapFragment = SupportMapFragment.newInstance(options);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_map_content, mMapFragment,MAP_FRAGMENT_TAG);
//transaction.addToBackStack(null);
transaction.commit();
}
catch(Exception ex){
System.err.println("Exception: " + ex.getMessage());
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = mMapFragment.getMap(); ***//ALWAYS RETUN NULL***
//mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
call setUpMapIfNeeded in onResume(), like this.
#Override
protected void onResume() {
super.onResume();
// In case Google Play services has since become available.
setUpMapIfNeeded();
}