How to retrieve snapshot of map from place-picker activity? - java

I'm creating an app which picks places from the Google maps and stores the address in the database. I also want to store the snapshot of the picked place in the storage, so I can display the data with corresponding snapshot.
When I select a place from the map, the place-picker activity shows the following dialog:
Here in the dialog, the address, latitude and longitude and also the snapshot is shown. I know how to get address and latLng. but don't know how to store that displayed snapshot.
Here is my method which retrieves everything other than that image:
//opening place picker activity.
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
tv4.setText(place.getLatLng().toString()+"\n"+name+"\n"+address+"\n"+attributions);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
I don't know how to get the image and store it in external or internal storage. Is it possible? I've to take snapshot as explained in this link?
EDIT
I have the following activity, which is calling activity of place-picker:
Main2Activity.java:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import android.database.Cursor;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.OnMapReadyCallback;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback{
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private GoogleApiClient mGoogleApiClient;
public TextView tv4;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
private Toolbar toolbar;
private GoogleMap mMap;
private boolean flag = false;
DatabaseHelper myDb;
EditText newevent;
Button submit;
Button viewremainders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
myDb =new DatabaseHelper(this);
newevent=(EditText)findViewById(R.id.newEvent);
submit=(Button)findViewById(R.id.submit);
viewremainders=(Button)findViewById(R.id.view);
toolbar = (Toolbar)findViewById(R.id.app_bar0);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true); //for back button to main activity.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
tv4 = (TextView)findViewById(R.id.textView4);
pickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(Main2Activity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
AddData();
viewremainders();
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
}
//method for adding data in Database.
public void AddData(){
submit.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted =myDb.insertData(newevent.getText().toString(),tv4.getText().toString());
if(isInserted==true)
Toast.makeText(Main2Activity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Main2Activity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
//Method for view all data from database.
public void viewremainders(){
viewremainders.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
Cursor res= myDb.getAllData();
if(res.getCount()==0)
{
Showmessage("Error","No remainders found");
return;
}
StringBuffer buffer=new StringBuffer();
while(res.moveToNext())
{
buffer.append("Id : " +res.getString(0)+"\n");
buffer.append("Event : " +res.getString(1)+"\n");
buffer.append("Location : " +res.getString(2)+"\n");
}
Showmessage("Data",buffer.toString());
}
}
);
}
public void Showmessage(String title,String message)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
//opening place picker activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
// tv4.setText(place.getLatLng().toString()+"\n"+name+"\n"+address+"\n"+attributions); To get latitide and longitudes.
tv4.setText(address+"\n"+attributions);
/* LatLngBounds selectedPlaceBounds = PlacePicker.getLatLngBounds(data);
// move camera to selected bounds
CameraUpdate camera = CameraUpdateFactory.newLatLngBounds(selectedPlaceBounds,0);
mMap.moveCamera(camera);
// take snapshot and implement the snapshot ready callback
mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
Bitmap bitmap=null;
public void onSnapshotReady(Bitmap snapshot) {
// handle snapshot here
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/ing.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Toast.makeText(Main2Activity.this,"dsfds",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(Main2Activity.this,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});*/
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void capture(){
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES).toString();
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(Environment.getExternalStorageDirectory().toString()+"/"+"lllll.jpg");
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
//Methods for toolbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
}

Since you are able to get the long and lat coordinates, you can get the map image by using the Google maps api.
Here's the link with examples and docs:
https://developers.google.com/maps/documentation/static-maps/intro
I assume this is what the dialog is doing in the background.
If that does not work, or you want something more exact, I suggest using Wireshark to monitor exactly what data is being sent and received.
I just ran a test with your map locations, and with this url:
https://maps.googleapis.com/maps/api/staticmap?center=37.430610,%20-121.972090&zoom=17&size=400x400&key=[myAPIKey]
I got this image:
Using the coords from your dialog:
Using https://maps.googleapis.com/maps/api/staticmap?markers=37.414333,-122.076444&zoom=17&size=400x250&key=[myKey]

You can use the GoogleMap.SnapshotReadyCallback
interface.
Here is a code example on how to use it:
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/some/where/to/save/it/thesnapshot.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
You can add this in your code when you show the dialog and in the same time save the snapshot. Read more about it in the link above.
I hope this will be of any help to you and good luck.

If you want to show snapshot of the picked place in the dialog first you have to save the screen of map view into bitmap.
Refer this code to converting your map view into bitmap
Bitmap screen;
View v1 = MyView.getRootView();
v1.setDrawingCacheEnabled(true);
screen= Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
From above code you can get Bitmap which You can further use in your Dialog box by setting this bitmap into image view.
But keep in mind u have to perform all operation before generating dialog and on worker thread.

You might look into maps Lite. It uses the google maps api and map views, but treats each one similar to an image rather than an interactive map. You can still choose your zoom level and add markers to the map.
declare the map in your xml like you would a regular google map fragment
but include the tag map:liteMode="true"
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:name="com.google.android.gms.maps.MapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraZoom="13"
map:mapType="normal"
map:liteMode="true"/>
or if you're creating the map programmatically you can use
GoogleMapOptions options = new GoogleMapOptions().liteMode(true);
it looks from your Activity code like you know how set up a google map, so you can then modify your onActivityResult to look like this
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
tv4.setText(place.getLatLng().toString()+"\n"+name+"\n"+address+"\n"+attributions);
// Add this line to make the lite map show the location you just chose
// and set the zoom level (10f is arbitrary)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 10f));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
More information and citations:
You can start here if you're looking for more info, there are tons of good links on this page
https://developers.google.com/maps/documentation/android-api/lite
you can also check out the Google Lite Maps Demo Activity here:
https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/LiteDemoActivity.java
And here's a great video that explains Lite Maps really well: https://youtu.be/N0N1Xkc_1pU

I faced same issue. I've tried with API key and Server key in both case I faced same error like "The Google Maps API server rejected your request... ". Finally I noticed that "Google Static Maps API" was disable from console. I just enable and everything works fine.

Related

How to open different activities depending OnInfoWindowClick

I am busy creating an application in Android Studio that uses Maps API.
I have successfully created OnInfoWindowClickListener to my Google Map. I have 2 different markers I set on my Google Map, but I want to set thousands of markers eventually.
When a user clicks on the Info Window, it must open a new activity.
So example, if a user clicks on 'Marker A', then 'Activity A' must open. Or if a user clicks on 'Marker B', then 'Activity B' must open. Or if a user clicks on 'Marker C', then 'Activity C' must open.
I have attempted to use the 'if statement & else if statement' in my code, but when I click on the Marker's Info Window, nothing happens?
package com.msp.googlemapsproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity {
static final LatLng CapeTown = new LatLng(-29.759933, 30.801030);
static final LatLng Durban = new LatLng(-29.858680, 31.021840);
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
final Marker marker_CapeTown = googleMap.addMarker(new MarkerOptions().position(CapeTown).title("Cape Town"));
final Marker marker_Durban = googleMap.addMarker(new MarkerOptions().position(Durban).title("Durban"));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (googleMap.equals("Durban")) {
Intent intent = new Intent(MainActivity.this, Durban.class);
startActivity(intent);
}
else if (googleMap.equals("Cape Town")) {
Intent intent = new Intent(MainActivity.this, CapeTown.class);
startActivity(intent);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
you are checking like this in your if clause:
if (googleMap.equals("Durban")) {
Intent intent = new Intent(MainActivity.this, Durban.class);
startActivity(intent);
}
but you should check on the marker of the public void onInfoWindowClick(Marker marker) method.
do something like this:
if (marker.getTitle().equals("Durban")) {
Intent intent = new Intent(MainActivity.this, Durban.class);
startActivity(intent);
}

My MainMenu.class in Android has this error that keeps saying one of my Strings is null using shared preferences

The MainMenu class keeps throwing an error on a String that says its null and I am having the hardest time figuring this out.
It is throwing at NameText.setText() of this MainMenu class.
I am going to feel stupid if this is something easy to fix lol
MainMenu.class :
package com.example.basicrecipes;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class MainMenu extends Activity implements OnClickListener {
public static final String RecipeNamesPref = "RecipeNames";
public static final String NamePref = "Name";
public static final String DescriptionPref = "Description";
public static final String PrefSteps = "How to Prepare";
public static final String CuisinePref = "American";
public static String SelectedRecipe = "SelectedRecipe";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View aboutButton = findViewById(R.id.main_about_button);
aboutButton.setOnClickListener(this);
Button newRecipe = (Button) this.findViewById(R.id.main_new_button);
newRecipe.setOnClickListener(this);
Button exitApp = (Button) this.findViewById(R.id.main_exit_button);
exitApp.setOnClickListener(this);
Button listRecipe = (Button) this.findViewById(R.id.main_list_button);
listRecipe.setOnClickListener(this);
SharedPreferences selectedRecipe;
selectedRecipe = getSharedPreferences(MainMenu.SelectedRecipe, RecipeEntry.MODE_PRIVATE);
SelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
if ("New Recipe" != SelectedRecipe) {
SharedPreferences thisRecipe = getSharedPreferences(SelectedRecipe + "_Detail", RecipeEntry.MODE_PRIVATE);
EditText NameText = (EditText) this.findViewById(R.id.name_new);
NameText.setText(thisRecipe.getString(MainMenu.NamePref, ""));
EditText DescriptionText = (EditText) this.findViewById(R.id.description_new);
DescriptionText.setText(thisRecipe.getString(MainMenu.DescriptionPref, ""));
EditText TextSteps = (EditText) this.findViewById(R.id.new_steps);
TextSteps.setText(thisRecipe.getString(MainMenu.PrefSteps, ""));
Spinner CuisineSelect = (Spinner) this.findViewById(R.id.cuisine_new);
CuisineSelect.setSelection(thisRecipe.getInt(MainMenu.CuisinePref, 0));
}
}
#Override
public void onClick(View thisView) {
switch (thisView.getId()) {
case R.id.main_about_button:
Intent showAbout = new Intent(this, About.class);
startActivity(showAbout);
break;
case R.id.main_list_button:
Intent doMenuClick = new Intent(this, RecipeList.class);
startActivity(doMenuClick);
break;
case R.id.main_new_button:
doMenuClick = new Intent(this, RecipeNew.class);
startActivity(doMenuClick);
break;
case R.id.main_exit_button:
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.menu, menu);
// menu.findItem(R.id.main_menu_search).setIntent(new Intent(this, SearchRecipe.class));
menu.findItem(R.id.main_menu_options).setIntent(new Intent(this, Options.class));
menu.findItem(R.id.main_menu_new).setIntent(new Intent(this, RecipeEntry.class));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem itm) {
super.onOptionsItemSelected(itm);
Intent menuIntent = itm.getIntent();
if (menuIntent != null)
startActivity(menuIntent);
return true;
}
}
Problem lies here :
if ("New Recipe" != SelectedRecipe) {
Comparing string like this is only comparing the Object type, not the String value itself.
I'm making a wild guess that the SharedPreferences SelectedRecipe_Detail does not exist.
Hence, NPE is thrown when you are trying to getString() from it.
Solution :
Do your checking as below :
if(!"New Recipe".equals(SelectedRecipe)) {
Found the problem
You are using SelectedRecipe as constant
public static String SelectedRecipe = "SelectedRecipe";
and then you are updating its value in
SelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
then you are using it again which makes it wrong
SharedPreferences thisRecipe = getSharedPreferences(SelectedRecipe + "_Detail", RecipeEntry.MODE_PRIVATE);
Change below code
String SelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
if ("New Recipe" != SelectedRecipe) {
to
String retSelectedRecipe = selectedRecipe.getString(MainMenu.SelectedRecipe, "New Recipe");
if (!"New Recipe".equals(retSelectedRecipe) ) {
I think I know what the problem is.
I got this book:
The Complete Idiots Guide to Android App Development
This was released in 2011 and I am pretty sure things have changed since then.
I recommend that you DO NOT GET THIS BOOK!!! WARNING!!!
This Book is VERY POORLY MADE!!!
Through out the whole book the variables change and things get switch around and not just that, he does not specify a lot of important detail about anything. It is very Half Assed!!!

Using facebook graph api to retrieve feeds of a page

I am developing an application for a customer, and I have read in app (android platform) posts which he (customer) publishes on a fan page.
I created the method below and when I use the keyword /me runs and got the output to my personal information, but when I use the keyword "729745317037227/feed/" the app closes and returns nothing.
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"729745317037227/feed/",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Toast.makeText(
getApplicationContext(),
response.getJSONObject()
+ "",
Toast.LENGTH_SHORT).show();
}
}
).executeAsync();
The entire code, I'm putting in the main, for now I'm just trying to make queries and display the results for later use in fragments.
Main class
package com.clubee.marketnow;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.Profile;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends Activity {
private TextView mainTextView;
private static final int request_code = 5;
public CallbackManager mCallbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
mCallbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
mainTextView = (TextView) findViewById(R.id.lol);
loginButton.setReadPermissions("user_friends");
LoginManager.getInstance().logOut(); //ensures that whenever we start the app we're logged out
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile curProfile = Profile.getCurrentProfile();
startNewIntent(curProfile);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"729745317037227/feed/",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Toast.makeText(
getApplicationContext(),
response.getJSONObject()
+ "",
Toast.LENGTH_SHORT).show();
}
}
).executeAsync();
}
#Override
public void onCancel() {
// App code
mainTextView.setText("Status: Logging in cancelled");
}
#Override
public void onError(FacebookException exception) {
// App code
mainTextView.setText("Status: EXCEPTION: " + exception.toString());
}
});
}
private void startNewIntent(Profile elUsero){
Intent i = new Intent(this, RetornoFacebook.class);
i.putExtra("firstName", elUsero.getFirstName());
i.putExtra("lastName", elUsero.getLastName());
i.putExtra("picURI", elUsero.getProfilePictureUri(1500,1500).toString());
startActivityForResult(i, request_code);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
if ((requestCode == request_code) && (resultCode == RESULT_OK)) {
LoginManager.getInstance().logOut();
mainTextView.setText("Status: Logged Out!");
}
}
}
Can anyone help me understand how I do to return the feed of a fan page?
I am racking my brain for weeks with this and do not know where I am going wrong. I have read a million times the fb documentation, and the max I got it the current result.
PS: When I do research in graph api explorer, using the same key (729745317037227/feed/), the return is a success.
tks a lot
The issue could be because of the type of access token that you are using.
"/me runs and got the output to my personal information": Call to this edge needs a User Access Token with the appropriate permissions.
"when I use the keyword "729745317037227/feed/" the app closes and returns nothing": Call to this edge needs a Page Access Token with the appropriate permissions. You might be using a User Access Token here.
Page Access Token – These access tokens are similar to user access
tokens, except that they provide permission to APIs that read, write
or modify the data belonging to a Facebook Page.

Android class that contain a list of objects

I'm new with Android and Java.
I create a class that contain a list of materials and the user can add new materials from another Dialog activity.
When the user add a new material from the Dialog activity he loses the old material.
Obviously this happends because every time that the app call the activity receiver, the activity instantiates the class again (this is the problem?).
This is the code of the activity that receive data from the Dialog
package com.ddz.diarioscolastico;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ActivitySetOrario extends ActionBarActivity {
TextView textView;
DataBase DB = new DataBase();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_orario);
}//Fine oncreate
//Prende indietro la materia aggiunta dall'ActivityAddMateria
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result = data.getStringExtra("result");
Materia materia;
materia = new Materia();
materia.setMateria(result);
materia.setColor(getResources().getColor(R.color.verde));
DB.getMaterie().add(materia);
LinearLayout mLayout = (LinearLayout) findViewById(R.id.contenitorematerie);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
params.setMargins(30, 0, 0, 0);
for(int i=0; i< DB.getMaterie().size(); i++)
{
textView = new TextView(this);
textView.setText(DB.getMaterie().get(i).getMateria());
textView.setBackgroundColor(DB.getMaterie().get(i).getColor());
textView.setLayoutParams(params);
mLayout.addView(textView);
}
}
if (resultCode == RESULT_CANCELED) {
//Nessuna materia inserita
}
}
}//onActivityResult
#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_set_orario, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.draw_orario:
addMateria();
return true;
case R.id.save_data_orario:
//SERIALIZZO I DATI CHE DOVRA PRENDERE ActivityOrario
//FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
//ObjectOutputStream os = new ObjectOutputStream(fos);
//os.writeObject(this);
//os.close();
//fos.close();
backToOrario();
return true;
case R.id.exit_orario:
//Torno alla schermata orario annullo ogni modifica NON SERIALIZZO
backToOrario();
finish();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Torna alla ActivityOrario
public void backToOrario(){
Intent myIntent = new Intent(ActivitySetOrario.this, ActivityOrario.class);
startActivity(myIntent);
}
public void addMateria(){
//StartActivityForResult perchè mi aspetto la materia inserita dall'altra activity
Intent myIntent = new Intent(ActivitySetOrario.this, ActivityAddMateria.class);
ActivitySetOrario.this.startActivityForResult(myIntent, 1);
}
}
DataBase DB = new DataBase(); every time call this new DataBase and I lose the old data!
Is this the problem?
I try to use a global variable, but I don't know where I need to instantiate the class only one time!
package com.ddz.diarioscolastico;
import android.app.Application;
class MyApp extends Application {
public DataBase DB = new DataBase();
public DataBase getState(){
return DB;
}
public void setState(){
DB = new DataBase();
}
}
Sorry for the bad english, if you need more explanations let me know!
You can either store them in some other class with a static modifier, or use SharedPreferences or some database.

Button not functioning

I'm developing an app.. In my MainActivity, once the main layout appears user is given a button, which leads to another class. I ran the app on my phone, unfortunately, when i press the button nothing happens.
Below I've included the button function and the class that to be called after the button press.
package com.androidhive.googleplacesandmaps;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Places List
PlacesList nearPlaces;
// GPS Location
GPSTracker gps;
// Button
Button btnShowOnMap;
// Progress dialog
ProgressDialog pDialog;
// Places Listview
ListView lv;
// ListItems data
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// creating GPS Class object
gps = new GPSTracker(this);
// check if GPS location can get
if (gps.canGetLocation()) {
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
} else {
// Can't get user's current location
alert.showAlertDialog(MainActivity.this, "GPS Status",
"Couldn't get location information. Please enable GPS",
false);
// stop executing code by return
return;
}
// Getting listview
lv = (ListView) findViewById(R.id.list);
// button show on map
btnShowOnMap = (Button) findViewById(R.id.btn_show_map);
// calling background Async task to load Google Places
// After getting places from Google all the data is shown in listview
new LoadPlaces().execute();
/** Button click event for shown on map */
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
/**
* ListItem click event
* On selecting a listitem SinglePlaceActivity is launched
* */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SinglePlaceActivity.class);
// Sending place refrence id to single place activity
// place refrence id used to get "Place full details"
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadPlaces extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"
// If you want all types places make it as null
// Check list of types supported by google
//
String types = "hospital|pharmacy"; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 5000; // 5000 meters
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
String status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
alert.showAlertDialog(MainActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(MainActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(MainActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(MainActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(MainActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(MainActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The class PlacesMapActivity.java
package com.stenlyjoseph.myhealth;
import com.stenlyjoseph.myhealth.R;
import java.util.List;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class PlacesMapActivity extends MapActivity {
// Nearest places
PlacesList nearPlaces;
// Map view
MapView mapView;
// Map overlay items
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
// Nearplaces list
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
(int) (Double.parseDouble(user_longitude) * 1E6));
// Drawable marker icon
Drawable drawable_user = this.getResources()
.getDrawable(R.drawable.red);
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = this.getResources()
.getDrawable(R.drawable.blue);
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
Please help me to fix the problem.
Thank you
be sure to have:
import android.view.View.OnClickListener;
and the declaration of btnShowOnMap on MainActivity must be inside the onCreate() method:
Button btnShowOnMap = (Button)inflatedView.findViewById(R.id.yourbutton);
btnShowOnMap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});

Categories