Implemented methods are not working in native interface(android) for Fused location provider - codenameone

I'm trying to apply FusedLocation provider in cn1 through native interface(android). I've implemented ConnectionCallbacks and OnConnectionFailedListener interfaces. It generates methods like onConnected(), onConnectionSuspended() and onConnectionFailed() in native android, which are not working when app is built in cn1.
Moreover, lifecycle methods like onResume, onDestroy of FusedLocationImpl etc are also not working. In the coming days, I'm planning to create the fused GPS library for general purpose as well.
PS. There are no build errors and got no any other errors when debugged.
FusedLocationImpl.java
import com.codename1.impl.android.AndroidNativeUtil;
import android.os.Bundle;
import android.location.Location;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
public class FusedLocationImpl implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private LocationRequest mLocationRequest;
public boolean isSupported() {
return true;
}
public void getFusedLocationPermission() {
if (!com.codename1.impl.android.AndroidNativeUtil.checkForPermission(Manifest.permission.ACCESS_FINE_LOCATION, "Please allow location permission")) {
}
}
public void fusedLocation() {
if (checkPlayServices()) {
buildGoogleApiClient();
}
}
public void onConnected(Bundle bundle) { // not working...
Log.i("onConnected", "GoogleApiClient connected!");
createLocationRequest();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.i("onConnected", " Location: " + mLastLocation);
}
protected void createLocationRequest() { // not working...
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(final LocationResult locationResult) {
Log.i("onLocationResult",locationResult + "");
}
#Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
Log.i("onLocationAvailability", "onLocationAvailability: isLocationAvailable = " + locationAvailability.isLocationAvailable());
}
}, null);
}
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
public void onConnectionFailed(ConnectionResult result) {
Log.i("onConnectionFailed", "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
public void onPause() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (LocationListener) this);
mGoogleApiClient.disconnect();
}
}
public void onResume() {
checkPlayServices();
}
public void onStart() {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
Log.i("onStart", "mGoogleApiClient.connect()");
}
}
public void onDestroy() {
Log.i("onDestory", "Service destroyed!");
mGoogleApiClient.disconnect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(AndroidNativeUtil.getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, AndroidNativeUtil.getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
AndroidNativeUtil.getActivity().finish();
}
return false;
}
return true;
}
protected synchronized void buildGoogleApiClient() {
Log.i("buildGoogleApiClient", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(AndroidNativeUtil.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
FusedLocation.java
public interface FusedLocation extends NativeInterface{
public void getFusedLocationPermission();
public void fusedLocation();
}
MyApplication.java
public void start() {
if (current != null) {
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.show();
Button btn = new Button("ask for permission");
FusedLocation fl = (FusedLocation) NativeLookup.create(FusedLocation.class);
Button btn1 = new Button("fused network");
hi.add(btn1);
btn1.addActionListener(e->{
if (fl != null && fl.isSupported()) {
fl.getFusedLocationPermission();
fl.fusedLocation();
System.out.println("fusedLocation");
}
});
}
PS. permission for location (ACCESS_FINE_LOCATION) succeeds. The main issue I've got is onConnected() and other implemented methods are not called. Thankyou
cn1 Location manager: this is not giving quite a performance as the native fused location provider
public final void checkGPS() {
if (Display.getInstance().getLocationManager().isGPSDetectionSupported()) {
if (Display.getInstance().getLocationManager().isGPSEnabled()) {
InfiniteProgress ip = new InfiniteProgress();
final Dialog ipDlg = ip.showInifiniteBlocking();
//Cancel after 20 seconds
Location loc = LocationManager.getLocationManager().getCurrentLocationSync(20000);
ipDlg.dispose();
if (loc != null) {
lat = loc.getLatitude();
lng = loc.getLongitude();
Dialog.show("location", "lat: " + lat + " lon: " + lng, "ok", null);
} else {
Dialog.show("GPS error", "Your location could not be found, please try going outside for a better GPS signal", "Ok", null);
}
} else {
Dialog.show("GPS disabled", "AppName needs access to GPS. Please enable GPS", "Ok", null);
}
} else {
Dialog.show("Warning", "GPS is not supported in your device", "ok", null);
}
}

I'm not sure why you aren't using the location listener which uses fused location internally when play services is enabled (the default).
You asked for permissions in the XML but didn't use the Android 6+ permissions which need a different syntax. Again, if you just use the location API this is all seamless...

Related

Incompatible types. Found: 'java.util.ArrayList<java.lang.Object>', required: 'java.util.ArrayList<UserLocation>'

So I am creating a route planner app in Android Studio and its giving me the error in the title of this question
Heres my code
import android.Manifest;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.example.destinationrouteplanner.R;
import com.example.destinationrouteplanner.adapters.UserRecyclerAdapter;
import com.example.destinationrouteplanner.models.MarkerCluster;
import com.example.destinationrouteplanner.models.User;
import com.example.destinationrouteplanner.util.MyClusterManagerRenderer;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.maps.android.clustering.ClusterManager;
import java.util.ArrayList;
public class UserListFragment extends Fragment implements OnMapReadyCallback
{
private static final String TAG = "UserListFragment";
private RecyclerView mUserListRecyclerView;
private MapView mMapView;
private ArrayList<User> mUserList = new ArrayList<>();
//private UserRecyclerAdapter mUserRecyclerAdapter;
private ArrayList<UserLocation> mUserLocations = new ArrayList<>();
private UserRecyclerAdapter mUserRecyclerAdapter;
private GoogleMap mGoogleMap;
private LatLngBounds mMapBoundary;
private UserLocation mUserPosition;
private ClusterManager mClusterManager;
private MyClusterManagerRenderer mClusterManagerRenderer;
private ArrayList<MarkerCluster> mClusterMarkers = new ArrayList<>();
public static UserListFragment newInstance() {
return new UserListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mUserList = getArguments().getParcelableArrayList(getString(R.string.intent_user_list));
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_list, container, false);
mUserListRecyclerView = view.findViewById(R.id.user_list_recycler_view);
mMapView = view.findViewById(R.id.user_list_map);
initUserListRecyclerView();
initGoogleMap(savedInstanceState);
return view;
}
private void initGoogleMap(Bundle savedInstanceState){
// *** IMPORTANT ***
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
}
private void initUserListRecyclerView() {
mUserRecyclerAdapter = new UserRecyclerAdapter(mUserList);
mUserListRecyclerView.setAdapter(mUserRecyclerAdapter);
mUserListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onStart() {
super.onStart();
mMapView.onStart();
}
#Override
public void onStop() {
super.onStop();
mMapView.onStop();
}
#Override
public void onMapReady(GoogleMap map) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
mGoogleMap = map;
addMapMarkers();
}
#Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void addMapMarkers()
{
if (mGoogleMap !=null)
{
if(mClusterManager == null)
{
mClusterManager = new ClusterManager<MarkerCluster>(getActivity().getApplicationContext(), mGoogleMap);
}
if (mClusterManagerRenderer == null)
{
mClusterManagerRenderer = new MyClusterManagerRenderer(getActivity(), mGoogleMap, mClusterManager);
mClusterManager.setRenderer(mClusterManagerRenderer);
}
for (UserLocation userLocation: mUserLocations)
{
Log.d(TAG, "AddMapMarkers: location: " + userLocation.getGeo_point().toString());
try {
String snippet = "";
if (userLocation.getUser().getUser_id().equals(FirebaseAuth.getInstance().getUid()))
{
snippet = "This is you";
}else {
snippet = "Determine route to " + userLocation.getUser().getUsername() + "?";
}
int avatar = R.drawable.cwm_logo; //Set the default avatar
try {
avatar = Integer.parseInt(userLocation.getUser().getAvatar());
}catch (NumberFormatException e)
{
Log.d(TAG, "addMapMarkers: no avatar for: " + userLocation.getUser().getUsername() + ", setting default");
}
MarkerCluster newMarkerCluster = new MarkerCluster(new LatLng(userLocation.getGeo_point().getLatitude(), userLocation.getGeo_point().getLongitude(), userLocation.getUser().getUsername(), snippet, avatar, userLocation.getUser()));
mClusterManager.addItem(newMarkerCluster);
mClusterMarkers.add(newMarkerCluster);
}catch (NullPointerException e)
{
Log.e(TAG "addMapMarkers: NullPointerException: " + e.getMessage());
}
}
mClusterManager.cluster();
setCameraView();
}
}
private void setCameraView()
{
double bottomBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double leftBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
double topBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double rightBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
}
}
I tired using the answer to this question but not working
Required type:
ArrayList
Provided:
ArrayList
no instance(s) of type variable(s) exist so that UserLocation conforms to Object

I am unable to get video to play reliably in codenameone

I am at the point of abandoning using codenameone to build an app that allows me to play video from storage or to capture and play. Its either it is playing but no video is showing (most common ) or it plays only once and thats it - the fast forward and rewind buttons not working. I don't know if this is a simulator problem/limitation or whether I just don't know what I am doing.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ixzdore.ziem.renderer.widgets;
import com.codename1.capture.Capture;
import com.codename1.components.ImageViewer;
import com.codename1.components.MediaPlayer;
import com.codename1.io.FileSystemStorage;
import com.codename1.io.Log;
import static com.codename1.io.Log.e;
import com.codename1.media.Media;
import com.codename1.media.MediaManager;
import com.codename1.ui.Container;
import com.codename1.ui.Display;
import com.codename1.ui.Image;
import com.codename1.ui.Label;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.Dimension;
import com.codename1.ui.layouts.BorderLayout;
import com.ixzdore.ziem.models.DocumentElement;
import com.ixzdore.ziem.models.ReportDocument;
import java.io.IOException;
/**
*
* #author jamesagada
*/
public class NVideo extends Widget {
private final Label _imageLabel = new Label();
private MediaPlayer _mPlayer;
private Container imageVideoContainer;
public NVideo(DocumentElement element, ReportDocument doc, Boolean isEditing) {
super(element, doc, isEditing);
imageVideoContainer = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_SCALE)) {
protected Dimension calcPreferredSize() {
return new Dimension(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth());
}
};
_mPlayer = new MediaPlayer();
setupWidgetFromProperty();
}
#Override
public void renderEdit() {
//super.initLayout();
super.setEnabled(true);
}
public void renderSummary() {
//super.initLayout();
super.setEnabled(false);
getIconContainer().remove();
revalidate();
}
#Override
public void renderView() {
//find the
//super.initLayout();
super.setEnabled(false);
getIconContainer().remove();
revalidate();
}
#Override
public void setupWidgetFromProperty() {
super.setupWidgetFromProperty();
String videoFile = documentElement.getVideoFileFromValue(documentElement.getPropertyValue());
if (videoFile != null) {
try {
Media video = MediaManager.createMedia(videoFile, true);
if (_mPlayer == null) {
_mPlayer = new MediaPlayer();
}
_mPlayer.setDataSource(videoFile);
_mPlayer.setAutoplay(true);
if (imageVideoContainer == null) {
imageVideoContainer = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_SCALE)) {
protected Dimension calcPreferredSize() {
return new Dimension(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth() );
}
};
}
getWidgetContainer().removeAll();
imageVideoContainer.add(BorderLayout.CENTER, _mPlayer);
imageVideoContainer.revalidate();
getWidgetContainer().add(imageVideoContainer);
getWidgetContainer().revalidate();
getWidgetContainer().repaint();
documentElement.setPropertyValue(videoFile);
} catch (Exception err) {
Log.e(err);
}
}
}
#Override
public void setupPropertyButtons() {
super.setupPropertyButtons();
//add a capture button and a browse button for gallery
//save captured picture and put the URL value in the propertyValue
final Widget _this = this;
_captureButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//open the capture button and take a video
String photoFile = Capture.captureVideo();
if (photoFile != null) {
try {
_mPlayer.setDataSource(photoFile);
_mPlayer.setAutoplay(false);
_mPlayer.revalidate();
_mPlayer.repaint();
imageVideoContainer.revalidate();
_this.revalidate();
documentElement.setPropertyValue(photoFile);
} catch (Exception err) {
Log.e(err);
}
}
}
});
_captureButton.setText("");
getIconContainer().add(_captureButton);
getIconContainer().revalidate();
getIconContainer().repaint();
getLabelContainer().repaint();
_findButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
if (ev != null && ev.getSource() != null) {
String file = (String) ev.getSource();
try {
_mPlayer.setDataSource(file);
_mPlayer.setAutoplay(false);
_mPlayer.revalidate();
_mPlayer.repaint();
imageVideoContainer.revalidate();
imageVideoContainer.repaint();
_this.revalidate();
documentElement.setPropertyValue(file);
} catch (Exception err) {
Log.e(err);
}
}
}
}, Display.GALLERY_VIDEO);
}
});
_findButton.setText("");
getIconContainer().add(_findButton);
getIconContainer().revalidate();
getIconContainer().repaint();
getLabelContainer().repaint();
this.revalidate();
}
public void render(boolean editing) {
if (isEditing) {
renderEdit();
}
if (!isEditing) {
renderSummary();
}
}
}
`
What am I doing wrong or show me working code sample to achieve what I am trying to achieve.

ContactsContract.Contacts issue, duplicates

I've been doing research on this but I can't figure it out. My contacts in my phone in a sample app I downloaded are often duplicated, like so:
I'm quite sure it has something to do with ContactsContract.Contacts. I've read up on it but don't know how to implement it in my code. Could someone help (or indeed if there's another way of doing it). I just want each contact be listed once, not multiple time.
According to http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html :
ContactsContract.Contacts
Constants for the contacts table, which contains a record per aggregate of raw contacts representing the same person.
I have 3 java files in my project, MainActivity, SelectUser and SelectUserAdapter, but I believe MainActivity is the one pertaining to this problem. Probably specifically this line :
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
If you need more code just let me know.
Here's my MainActivity.java :
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
// ArrayList
ArrayList<SelectUser> selectUsers;
List<SelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;
// Pop up
ContentResolver resolver;
SearchView search;
SelectUserAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectUsers = new ArrayList<SelectUser>();
resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// retrieves contact information
LoadContact loadContact = new LoadContact();
loadContact.execute();
// let's set up our search box,
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// when the text in searchView changes, call the filter function
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
Toast.makeText(MainActivity.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
}
while (phones.moveToNext()) {
Bitmap bit_thumb = null;
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
Log.e("No Image Thumb", "--------------");
}
} catch (IOException e) {
e.printStackTrace();
}
//what's happening here? For every user in the phonebook, show an image, the name, number, an id and maybe a checkbox?
SelectUser selectUser = new SelectUser();
selectUser.setThumb(bit_thumb);
selectUser.setName(name);
selectUser.setPhone(phoneNumber);
selectUser.setEmail(id);
selectUser.setCheckedBox(false);
selectUsers.add(selectUser);
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
return null;
}
#Override
// when DoInBackground is finished, when we have our phone number, name etc... display the results in our listview.
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("search", "here---------------- listener");
SelectUser data = selectUsers.get(i);
}
});
listView.setFastScrollEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
phones.close();
}
}
public class MainActivity extends Activity {
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (cursor != null) {
cursor.moveToFirst();}
try {
cursor = getApplicationContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
cursor.moveToFirst();
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
String contactid=cursor.getString(Idx);
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
String image = cursor.getString(photoIdIdx);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Number--->"+phoneNumber);
if (!phoneNumber.contains("*")) {
hashMap.put("contactid", "" + contactid);
hashMap.put("name", "" + name);
hashMap.put("phoneNumber", "" + phoneNumber);
hashMap.put("image", "" + image);
// hashMap.put("email", ""+email);
if (hashMapsArrayList != null) {
hashMapsArrayList.add(hashMap);}
// hashMapsArrayList.add(hashMap);
}
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}

Compile error with two different fragmenttransaction types

I'm using AIDE on my phone, and trying to open a fragment from the navigation drawer in-app, but I get this error when I try to build the app:
An instance of type 'android.app.fragmenttransaction' cannot be assigned to a variable of type 'android.support.v4.app.fragmenttransaction'
Here is the code in the MainActivity.Java file:
package com.nickdgreen.net.act1;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.support.v4.app.*;
import android.support.v4.widget.*;
import android.view.*;
import android.widget.*;
import android.app.ActionBar.*;
import android.app.Activity.*;
import android.content.res.Configuration.*;
import android.os.Bundle.*;
import android.support.v4.app.ActionBarDrawerToggle.*;
import android.support.v4.app.Fragment.*;
import android.support.v4.app.FragmentActivity.*;
import android.support.v4.app.FragmentManager.*;
import android.support.v4.app.FragmentTransaction.*;
import android.support.v4.widget.DrawerLayout.*;
import android.view.Menu.*;
import android.view.MenuInflater.*;
import android.view.MenuItem.*;
import android.view.View.*;
import android.widget.AdapterView.*;
import android.widget.ArrayAdapter.*;
import android.widget.ListView.*;
public class MainActivity extends FragmentActivity
{
private ActionBarDrawerToggle drawerToggle;
final String fragments[] = {
"com.nickdgreen.net.act1.MainFragment",
"com.nickdgreen.net.act1.OneFragment",
"com.nickdgreen.net.act1.TwoFragment",
"com.nickdgreen.net.act1.ThreeFragment",
};
final String menuEntries[] = {
"Main", "One", "Two", "Three"
};
public MainActivity()
{
}
public void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
drawerToggle.onConfigurationChanged(configuration);
}
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(0x7f030000);
ArrayAdapter arrayadapter = new ArrayAdapter(getActionBar().getThemedContext(), 0x1090003, menuEntries);
final DrawerLayout drawer = (DrawerLayout)findViewById(0x7f080000);
final ListView navList = (ListView)findViewById(0x7f080002);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawer, 0x7f020000, 0x7f050003, 0x7f050002) {
final MainActivity this$0;
public void onDrawerClosed(View view)
{
}
public void onDrawerOpened(View view)
{
}
{
this$0 = MainActivity.this;
}
};
drawer.setDrawerListener(drawerToggle);
navList.setAdapter(arrayadapter);
navList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
final MainActivity this$0;
final DrawerLayout val$drawer;
final ListView val$navList;
public void onItemClick(AdapterView adapterview, View view, int i, long l)
{ {
}
drawer.closeDrawer(navList);
}
{
}
});
FragmentTransaction fragmenttransaction = getSupportFragmentManager().beginTransaction();
fragmenttransaction.replace(0x7f080001, Fragment.instantiate(this, fragments[0]));
fragmenttransaction.commit();
}
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(0x7f070000, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
if (drawerToggle.onOptionsItemSelected(menuitem))
{
return true;
} else
{
return super.onOptionsItemSelected(menuitem);
}
}
protected void onPostCreate(Bundle bundle)
{
super.onPostCreate(bundle);
drawerToggle.syncState();}
private class DrawerItemClickListener
implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{ selectItem(position); }
/** Swaps fragments in the main content view */
private void
selectItem(int position) {
//Fragment fragment = new PlanetFragment(); Bundle args = new Bundle(); // args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
Intent intent = new Intent(MainActivity.this, OneFragment.class); startActivity(intent); } }
public class
ProductListActivity extends MainActivity {
#Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate main_menu.xml
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mainMenuAbout:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.mainMenuExit:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override public void onClick(Bundle b) { super.onCreate(b); setContentView(R.layout.primary);}
public void
selectItem(int position) {
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new OneFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null); transaction.commit();
break;
case 1:
newFragment = new TwoFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
newFragment = new ThreeFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 3:
newFragment = new FourFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
}
//DrawerList.setItemChecked(position, true);
CharSequence[] ListTitles = null;
setTitle(ListTitles[position]);
View DrawerList = null;
}
}
}
import android.support.v4.app.FragmentTransaction.*;
This line means that you are using FragmentTransaction; note that you are using the support lib's version, not the system's.
However, later in the code, you are assigning the support lib's FragmentTransaction to the native FragmentTransaction. They are incompatible and thus won't work. (Actually, it's what the error message itself is telling you.)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// ^^^ support lib's version ^^^ this code returns a native FragmentTransaction
You should instead get the support lib's fragment manager, which will return the support FragmentTransaction.

Easy way to dynamically invoke web services (without JDK or proxy classes)

In Python I can consume a web service so easily:
from suds.client import Client
client = Client('http://www.example.org/MyService/wsdl/myservice.wsdl') #create client
result = client.service.myWSMethod("Bubi", 15) #invoke method
print result #print the result returned by the WS method
I'd like to reach such a simple usage with Java.
With Axis or CXF you have to create a web service client, i.e. a package which reproduces all web service methods so that we can invoke them as if they where normal methods. Let's call it proxy classes; usually they are generated by wsdl2java tool.
Useful and user-friendly. But any time I add/modify a web service method and I want to use it in a client program I need to regenerate proxy classes.
So I found CXF DynamicClientFactory, this technique avoids the use of proxy classes:
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
//...
//create client
DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client client = dcf.createClient("http://www.example.org/MyService/wsdl/myservice.wsdl");
//invoke method
Object[] res = client.invoke("myWSMethod", "Bubi");
//print the result
System.out.println("Response:\n" + res[0]);
But unfortunately it creates and compiles proxy classes runtime, hence requires JDK on the production machine. I have to avoid this, or at least I can't rely on it.
My question:
Is there another way to dinamically invoke any method of a web service in Java, without having a JDK at runtime and without generating "static" proxy classes? Maybe with a different library? Thanks!
I know this is a really old question but if you are still interested you could use soap-ws github project: https://github.com/reficio/soap-ws
Here you have a sample usage really simple:
Wsdl wsdl = Wsdl.parse("http://www.webservicex.net/CurrencyConvertor.asmx?WSDL");
SoapBuilder builder = wsdl.binding()
.localPart("CurrencyConvertorSoap")
.find();
SoapOperation operation = builder.operation()
.soapAction("http://www.webserviceX.NET/ConversionRate")
.find();
Request request = builder.buildInputMessage(operation)
SoapClient client = SoapClient.builder()
.endpointUrl("http://www.webservicex.net/CurrencyConvertor.asmx")
.build();
String response = client.post(request);
As you can see it is really simple.
With CXF 3.x this could be possible with StaxDataBinding. Follow below steps to get the basics. Of course, this could be enhanced to your needs.
Create StaxDataBinding something like below. Note below code can be enhanced to your sophistication.
class StaxDataBinding extends AbstractInterceptorProvidingDataBinding {
private XMLStreamDataReader xsrReader;
private XMLStreamDataWriter xswWriter;
public StaxDataBinding() {
super();
this.xsrReader = new XMLStreamDataReader();
this.xswWriter = new XMLStreamDataWriter();
inInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inFaultInterceptors.add(new StaxInEndingInterceptor(Phase.POST_INVOKE));
inInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
inFaultInterceptors.add(RemoveStaxInEndingInterceptor.INSTANCE);
}
static class RemoveStaxInEndingInterceptor
extends AbstractPhaseInterceptor<Message> {
static final RemoveStaxInEndingInterceptor INSTANCE = new RemoveStaxInEndingInterceptor();
public RemoveStaxInEndingInterceptor() {
super(Phase.PRE_INVOKE);
addBefore(StaxInEndingInterceptor.class.getName());
}
public void handleMessage(Message message) throws Fault {
message.getInterceptorChain().remove(StaxInEndingInterceptor.INSTANCE);
}
}
public void initialize(Service service) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
SchemaCollection schemaCollection = serviceInfo.getXmlSchemaCollection();
if (schemaCollection.getXmlSchemas().length > 1) {
// Schemas are already populated.
continue;
}
new ServiceModelVisitor(serviceInfo) {
public void begin(MessagePartInfo part) {
if (part.getTypeQName() != null
|| part.getElementQName() != null) {
return;
}
part.setTypeQName(Constants.XSD_ANYTYPE);
}
}.walk();
}
}
#SuppressWarnings("unchecked")
public <T> DataReader<T> createReader(Class<T> cls) {
if (cls == XMLStreamReader.class) {
return (DataReader<T>) xsrReader;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedReaderFormats() {
return new Class[] { XMLStreamReader.class };
}
#SuppressWarnings("unchecked")
public <T> DataWriter<T> createWriter(Class<T> cls) {
if (cls == XMLStreamWriter.class) {
return (DataWriter<T>) xswWriter;
}
else {
throw new UnsupportedOperationException(
"The type " + cls.getName() + " is not supported.");
}
}
public Class<?>[] getSupportedWriterFormats() {
return new Class[] { XMLStreamWriter.class, Node.class };
}
public static class XMLStreamDataReader implements DataReader<XMLStreamReader> {
public Object read(MessagePartInfo part, XMLStreamReader input) {
return read(null, input, part.getTypeClass());
}
public Object read(QName name, XMLStreamReader input, Class<?> type) {
return input;
}
public Object read(XMLStreamReader reader) {
return reader;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String prop, Object value) {
}
}
public static class XMLStreamDataWriter implements DataWriter<XMLStreamWriter> {
private static final Logger LOG = LogUtils
.getL7dLogger(XMLStreamDataWriter.class);
public void write(Object obj, MessagePartInfo part, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
// WRITE YOUR LOGIC HOW you WANT TO HANDLE THE INPUT DATA
//BELOW CODE JUST CALLS toString() METHOD
if (part.isElement()) {
QName element = part.getElementQName();
writer.writeStartElement(element.getNamespaceURI(),
element.getLocalPart());
if (obj != null) {
writer.writeCharacters(obj.toString());
}
writer.writeEndElement();
}
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
public void write(Object obj, XMLStreamWriter writer) {
try {
if (!doWrite(obj, writer)) {
throw new UnsupportedOperationException("Data types of "
+ obj.getClass() + " are not supported.");
}
}
catch (XMLStreamException e) {
throw new Fault("COULD_NOT_READ_XML_STREAM", LOG, e);
}
}
private boolean doWrite(Object obj, XMLStreamWriter writer)
throws XMLStreamException {
if (obj instanceof XMLStreamReader) {
XMLStreamReader xmlStreamReader = (XMLStreamReader) obj;
StaxUtils.copy(xmlStreamReader, writer);
xmlStreamReader.close();
return true;
}
else if (obj instanceof XMLStreamWriterCallback) {
((XMLStreamWriterCallback) obj).write(writer);
return true;
}
return false;
}
public void setSchema(Schema s) {
}
public void setAttachments(Collection<Attachment> attachments) {
}
public void setProperty(String key, Object value) {
}
}
}
Prepare your input to match the expected input, something like below
private Object[] prepareInput(BindingOperationInfo operInfo, String[] paramNames,
String[] paramValues) {
List<Object> inputs = new ArrayList<Object>();
List<MessagePartInfo> parts = operInfo.getInput().getMessageParts();
if (parts != null && parts.size() > 0) {
for (MessagePartInfo partInfo : parts) {
QName element = partInfo.getElementQName();
String localPart = element.getLocalPart();
// whatever your input data you need to match data value for given element
// below code assumes names are paramNames variable and value in paramValues
for (int i = 0; i < paramNames.length; i++) {
if (paramNames[i].equals(localPart)) {
inputs.add(findParamValue(paramNames, paramValues, localPart));
}
}
}
}
return inputs.toArray();
}
Now set the proper data binding and pass the data
Bus bus = CXFBusFactory.getThreadDefaultBus();
WSDLServiceFactory sf = new WSDLServiceFactory(bus, wsdl);
sf.setAllowElementRefs(false);
Service svc = sf.create();
Client client = new ClientImpl(bus, svc, null,
SimpleEndpointImplFactory.getSingleton());
StaxDataBinding databinding = new StaxDataBinding();
svc.setDataBinding(databinding);
bus.getFeatures().add(new StaxDataBindingFeature());
BindingOperationInfo operInfo = ...//find the operation you need (see below)
Object[] inputs = prepareInput(operInfo, paramNames, paramValues);
client.invoke("operationname", inputs);
If needed you can match operation name something like below
private BindingOperationInfo findBindingOperation(Service service,
String operationName) {
for (ServiceInfo serviceInfo : service.getServiceInfos()) {
Collection<BindingInfo> bindingInfos = serviceInfo.getBindings();
for (BindingInfo bindingInfo : bindingInfos) {
Collection<BindingOperationInfo> operInfos = bindingInfo.getOperations();
for (BindingOperationInfo operInfo : operInfos) {
if (operInfo.getName().getLocalPart().equals(operationName)) {
if (operInfo.isUnwrappedCapable()) {
return operInfo.getUnwrappedOperation();
}
return operInfo;
}
}
}
}
return null;
}

Resources