Implementing google places autocomplete in android - java

Im creating an android app where im reusing the google places api to get the autocomplete function. I way i have succesfully implemented functionality is by using this code.
int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
...
try {
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
This code is launched when the user clicks on a menu_button from a popupmenu in the firstscreen (mainscreen)
This code is able to do what i want it to do, but i dont know how to edit the fragment it creates. I want to set a hint thats different from "search" which is by default. The reason i used this code was because its able to create a sort of dialog or dim the background and creating the the autocompletefragment on top of the first screen which is what i want. Is there an another way to implement the autocomplete?
tl:dr
I want to use the google places autocomplete, and i want it to pop up like a dialog (Dim the first screen and the searchbar goes on top of the first screen).
Does anyone have a solution?

Related

Alternative for toast when using widgets in Android 12 as toasts are now truncated

hope someone can point me in the right direction.
I have created an app with a widget. The widget is a simple button that runs a bit of code and then returns a message to the user via a toast. However, I realise in Android 12 toasts are now truncated to two lines and often the message is longer. I'm not keen on snackbars but appreciate my main app can be converted to use them but what should I use to do the same job via a widget?
Snackbars require a layout view to work but I can't figure out how to retirve it from teh widget code. I could use an alertdialogue but although the code compiles they simple don't seem to show up. I'm open to suggestions here...
What is the best way of popping up a message on the homescreen when a widget is pressed? Is there any way of telling the app not to truncate toasts or if not what's the best alternative?
Many thanks
Nat
Finally worked out how to do this myself... Its kinda obvious when you know but isn't that always the way?
Create a new activity. You can make it look like a dialog by using this theme in your manifest - android:theme="#style/Theme.AppCompat.Dialog". Then from your widget simply call showmessage as outlined below...
public void showamessage (String thetitle, String themessage) {
PendingIntent pendingIntent;
Intent intent = new Intent();
intent.setClass(thecontext,MessageActivity.class);
intent.putExtra("TheTitle",thetitle);
intent.putExtra("TheMessage",themessage);
pendingIntent = PendingIntent.getActivity(thecontext, 0, intent, FLAG_IMMUTABLE);
try {
pendingIntent.send(thecontext, 0, intent);
} catch (PendingIntent.CanceledException e) {
System.out.println( "Sending pendingintent failed: " );
}
}

How to click button inside method Adapter in RecyclerView?

I am working on stripe-terminal-android-app, to connect to BBPOS 2X Reader device,
wanted to click-item from list,(recyclerView).
I am trying to do:
when list of devices appears(readers), I am checking if readers.size()==1, then click first-device from list,else show recyclerView();
I have very less experience in Android(coming from JS, PY), :)
After going through debugger to understand flow of program-running, I used F8 key, or stepOver the functions one by one,
and where value is assigned to convert in displayble-format in adapter as here.
public ReaderAdapter(#NotNull DiscoveryViewModel viewModel) {
super();
this.viewModel = viewModel;
if (viewModel.readers.getValue() == null) {
readers = new ArrayList<>();
} else {
readers = viewModel.readers.getValue();
if(readers.size() == 1){
Log.e(TAG, "readers.size() is 1 "+ readers.size());
}
}
}
then in ReaderHolder-file, values are bind() as
void bind(#NotNull Reader reader) {
binding.setItem(reader);
binding.setHandler(clickListener);
binding.executePendingBindings();
}
}
I tried assigining button and manually clicking when only-one device appears, by clicing on reader[0], can't do that by findViewById inside Adapter file, to call onClick() method manually,
I tired another StackOverflow's answer but didn't understood, from here.
Main fragment is discovery-fragment,
how can I click first-device by checking readers.size()==1, then click onClick()?
my final-goal is to automate, whole stripe-terminal-payment process on android.
extra-info:
I am fetching data from python-odoo server, then using url, will open app through browser, (done this part), then device will be selected automatically as everytime-no any devices will be present except one,
so will automatically select that from recyclerView, then proceed.
I have asked for help in detailed way on GitHub-issues, and started learning Android's concepts for this app(by customizing stripe's demo app, which works great, but I wanted to avoid manually clicking/selection of devices).

PlacePicker Without Opening Widget Screen

I have implemented Google Maps in my App and doing reverse geocoding when clicking on map.Im using This API. but it gives me more than one result on Single tap. I know why Google behave like this.
Then I look into PlacePicker widget for Android, but Im unable to use that widget without opening another Map screen to pick place.
What I want is that I want to use my Google Map screen to get tapped place instead of opening PlacePicker screen. I just want PlacePicker work with my implemented Map i.e want PlacePicker to respond map click and give place without opening widget if this is not possible then inform me about other solution to get exactly one and correct place on Map tap? Thank you in advance
Updated
Why Im getting closed vote for question? it is not too broad? Simply,I want to know whether is it possible to use Google Map (MapView|SuportFragment) as PlacePicker's main screen. Have look code below
int PLACE_PICKER_REQUEST = 1;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
// I don't want this line, Don't want PlacePicker to open another Map Screen to allow user to pick place.
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
now look at below code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
above code is executed when user pick a place from PlacePicker screen and that screen returns a Intent with picked place. Is there any way to make that type of 'Intent' on Google Map tap with lat,lng? so that I could get Place detail. I don't want to user reverse geocoding as it gives me many results.
I Donot know anything about the google geo api or PlacePicker api.
The google independent android standard way would be to use "ACTION_PICK" with a geo uri.
For more infos see https://github.com/k3b/k3b-geoHelper/wiki/Android-Geo-howto.
This only works if you have installed a geo-pick-aware app that supports geo-pick.
Note: you do not have to use the lib. All you need to do is to decode the geo-uri returned by activity result
I have found solution to my problem, To get rid of reverse geocoding to many results and to get clicked place I use following code
googleMap.setOnPoiClickListener(new GoogleMap.OnPoiClickListener() {
#Override
public void onPoiClick(PointOfInterest pointOfInterest) {
String SS="";
isPOI=true;
poiPlaceID=pointOfInterest.placeId;
// Then using Google PlaceDetail API with placeId, It gives me exact Location click
}
});

Loading Images from Web Directory, display in ImageView

I am trying to write a simple application that loads images that are stored in a web directory I've created. I want the application to grab ALL of the images that are stored in said directory and display them in a layout.
The code below works for only certain type of URLs(mainly tinypic, but not photobucket, imageshack etc) and also not for directories.
I've my image names formatted in sequence like image1.png, image2.png, etc. so that the code snippet and the downloadFile()-method would work.
But, I'm not sure how I would grab all the images from the server simultaneously because this only grabs one image at a time, sets it as a bitmap and then displays it in an IV. I'm pretty new to Android so some help in the right direction would be appreciated.
public class NewWallpapersActivity extends Activity {
ImageView imView1;
String imageUrl="http://i133.photobucket.com/albums/q44/slimjady/Wallpapers";
Random r= new Random();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.newwallpapers);
Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView1 = (ImageView)findViewById(R.id.IV1);
}
View.OnClickListener getImgListener = new View.OnClickListener(){
public void onClick(View view) {
//i tried to randomize the file download, in my server i put 4 files with name like
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt(4);
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}
};
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl = null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView1.setImageBitmap(bmImg);
} catch (IOException e) {
String exception = "Erro: An Exception Was Thrown";
Toast errortoast = Toast.makeText(this, exception, Toast.LENGTH_SHORT);
errortoast.show();
e.printStackTrace();
}
}
}
Here are some thoughts on this one:
Displaying all Images
Since you want to display all Images from within a single folder, I would suggest you to have a Directory-Activity, which displayes all the images in the given directory and one Image-Activity which displays only one single Image.
To proper present this I would suggest using a GridView to display all the Images and a normal Activity with a full-screen ImageView to display the single Image.
You could also use the Gallery-widget to "combine" both those ideas.
Not letting the user wait
One of the bigger problems with your approach is, that the images are getting downloaded on the UI-Thread.
Depending on the size of all or on single image and the available connection-speed, Downloading the image can take a while. While the images are getting downloaded, the UI-Thread will wait for your downloadStuff()-method to return and the UI will freeze. This might create the illusion that your App just crashed.
So, you'll want to do the downloading in a separate thread. Android has a handy wrapper for this called an AsyncTask.
As a little bonus to show your user that the process might take a while you can use a ProgressDialog to illustrate this (on the UI-Thread).
Knowing whats in a directory
Now we come to the point where we have to face some limitations. If you want to use Picture-Hosters like the ones you listed above, you'll need to check if they offer you an API (or something equal) to get a list of Images (or their URLs) from a certain directory/album (look for a "API"-link on the front-page).
If you host the images on your own Server, you should be able to create a little PHP-script (or whatever script/programming language you prefer), which then lists all image-files in the directory and presents them in an easy-to-parse way (either JSON or XML).
This should enable you to get a list of URLs to the Image-files you want to display.

how to add simple code to an android application

I have some confusion regarding where you put regular java code in an android application.
I'm using the Eclipse SDK and by default when you create an application it makes a .java file with an OnCreate() method. Is this where I would put my code, inside this method?
Right now in my layout I have an imageButton, once this button is clicked I want to open a new WebView page that gets it's HTML code from the index.html file found in the assets folder. This is what I have so far...
Button button = (Button)findViewById(R.id.imagebutton1);
if(button.isPressed())
{
WebView webview = new WebView(null);
setContentView(webview);
try {
InputStream fin = getAssets().open("index.html");
byte[] buffer = new byte[fin.available()];
fin.read(buffer);
fin.close();
webview.loadData(new String(buffer), "text/html", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
I have this block of code at the end of the onCreate() method right under the line:
setContentView(R.layout.main);
However, once I run the program it crashes and tells me that it failed to start. I'm assuming that it has to do with the fact that the code is in the onCreate. I know that its not where I'm supposed to put it, but I can't think of anywhere else the code should go. Am I supposed to make a new .java file and have a main method there? I'm currently taking classes for C++ and C# so this android thing is still new to me.
Have you done the tutorials? If not I would start there to learn about the basics of creating and working with an Android Activity. Once you have worked your way through them, read the application fundamentals to understand the lifecycle more fully.
You shouldn't be calling setContentView more than once in onCreate. The WebView should be in your main.xml layout file or else launch a new Activity that's layout contains the WebView. And also to hand the onClick on the button you need to call setOnClickListener().
Please see Handling UI Events.
Also, if your program crashes, it would be helpful if you provided error messages from logcat.

Categories

Resources