I am implementing raw h264 player using MediaCodec - h.264

I am implementing raw h264 player.
The following codes work slowly. (There is mutex problems, But ignore it.)
Also bpkt.bytes is sent each frame unit named end frame from other server via tcp.
But mH264Queue is slower for consuming data than filling data to mH264Queue.
The size of mH264Queue is increased forever.
Please see my codes.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import android.app.Activity;
import android.media.MediaCodec;
import android.media.MediaCodec.BufferInfo;
import android.media.MediaFormat;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class RawH264Activity extends Activity implements SurfaceHolder.Callback
{
// private static final String filePath = Environment.getExternalStorageDirectory()+ "/ksoo.h264"; // + "/video_encoded.263";//"/video_encoded.264";
private PlayerThread mPlayer = null;
Handler handler = null;
// public static byte[] SPS = null;
// public static byte[] PPS = null;
Socket mMediaSocket = null;
BufferedInputStream mMediaSocketIn = null;
OutputStream mMediaSocketOut = null;
Thread mSocketTh = null;
Queue<SocketTool.BinaryPkt> mH264Queue = new LinkedList<SocketTool.BinaryPkt>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SurfaceView sv = new SurfaceView(this);
handler = new Handler();
sv.getHolder().addCallback(this);
setContentView(sv);
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
Log.d("DecodeActivity", "in surfaceCreated");
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
Log.d("DecodeActivity", "in surfaceChanged");
if (mPlayer == null)
{
Toast.makeText(getApplicationContext(), "in surfaceChanged. creating playerthread", Toast.LENGTH_SHORT).show();
mSocketTh = new Thread(new Runnable() {
#Override
public void run() {
try {
mMediaSocket = new Socket(CurrentState.get().mRemoteAddress, CurrentState.get().mRemoteMediaPort);
mMediaSocketIn = new BufferedInputStream(mMediaSocket.getInputStream());
mMediaSocketOut = mMediaSocket.getOutputStream();
mPlayer = new PlayerThread(holder.getSurface());
mPlayer.start();
while(!mSocketTh.isInterrupted()) {
SocketTool.BinaryPkt bpkt = SocketTool.readPKTBinary(mMediaSocketIn);
mH264Queue.add(bpkt);
if(mH264Queue.size() > 2000)
break;
}
try {
mMediaSocketIn.close();
mMediaSocketOut.close();
mMediaSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
// Log.i("bpkt", "" + bpkt.mCmdType);
// }
} catch (IOException e) {
// 서버 접속 끊기
e.printStackTrace();
}
}
});
mSocketTh.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
if (mPlayer != null)
{
mPlayer.interrupt();
}
}
private class PlayerThread extends Thread
{
//private MediaExtractor extractor;
private MediaCodec decoder;
private Surface surface;
public PlayerThread(Surface surface)
{
this.surface = surface;
}
#Override
public void run()
{
handler.post(new Runnable()
{
#Override
public void run()
{
try {
decoder = MediaCodec.createDecoderByType("video/avc");
} catch (IOException e) {
e.printStackTrace();
}
MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", 1280, 720);
// Video_format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, interval);
// mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
// mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 60);
// mediaFormat.setByteBuffer("csd-0", ByteBuffer.wrap(new byte[] {
// 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, 0x00, 0x1F, (byte)0x9D, (byte)0xA8, 0x14, 0x01, 0x6E, (byte)0x9B, (byte)0x80,
// (byte)0x80, (byte)0x80, (byte)0x81}));
// mediaFormat.setByteBuffer("csd-1", ByteBuffer.wrap(new byte[] {
// 0x00, 0x00, 0x00, 0x01, 0x68, (byte)0xCE, 0x3C, (byte)0x80 }));
// byte[] header_sps = { 0x00, 0x00, 0x00, 0x01, 0x67, 0x42, (byte)0x80, 0x0C, (byte)0xE4, 0x40, (byte)0xA0, (byte)0xFD, 0x00, (byte)0xDA, 0x14, 0x26, (byte)0xA0 };
// byte[] header_pps = {0x00, 0x00, 0x00, 0x01, 0x68, (byte)0xCE, 0x38, (byte)0x80 };
// mediaFormat.setByteBuffer("csd-0", ByteBuffer.wrap(header_sps));
// mediaFormat.setByteBuffer("csd-1", ByteBuffer.wrap(header_pps));
decoder.configure(mediaFormat, surface /* surface */, null /* crypto */, 0 /* flags */);
if (decoder == null)
{
Log.e("DecodeActivity", "Can't find video info!");
return;
}
decoder.start();
Log.d("DecodeActivity", "decoder.start() called");
ByteBuffer[] inputBuffers = decoder.getInputBuffers();
ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
long startMs = System.currentTimeMillis();
int i = 0;
while(!Thread.interrupted())
{
int inIndex = 0;
while ((inIndex = decoder.dequeueInputBuffer(1)) < 0)
;
if (inIndex >= 0)
{
ByteBuffer buffer = inputBuffers[inIndex];
buffer.clear();
Log.i("queue", String.valueOf(mH264Queue.size()));
SocketTool.BinaryPkt bpkt = mH264Queue.poll();
int sampleSize = 0;
if (bpkt.bytes == null) {
Log.d("DecodeActivity", "InputBuffer BUFFER_FLAG_END_OF_STREAM");
decoder.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
break;
}
else
{
sampleSize = bpkt.bytes.length;
buffer.clear();
buffer.put(bpkt.bytes);
decoder.queueInputBuffer(inIndex, 0, sampleSize, 0, 0);
}
BufferInfo info = new BufferInfo();
int outIndex = decoder.dequeueOutputBuffer(info, 10000);
switch (outIndex)
{
case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED:
Log.d("DecodeActivity", "INFO_OUTPUT_BUFFERS_CHANGED");
outputBuffers = decoder.getOutputBuffers();
break;
case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED:
// Log.d("DecodeActivity", "New format " + decoder.getOutputFormat());
break;
case MediaCodec.INFO_TRY_AGAIN_LATER:
// Log.d("DecodeActivity", "dequeueOutputBuffer timed out!");
try {
sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
ByteBuffer outbuffer = outputBuffers[outIndex];
// Log.d("DecodeActivity", "We can't use this buffer but render it due to the API limit, " + outbuffer);
decoder.releaseOutputBuffer(outIndex, true);
break;
}
i++;
}
}
decoder.stop();
decoder.release();
}
});
}
}
}

The problem here is you only drain the output buffer when input buffer is available.
The fact is the output of mediacodec is often (if not always) not available instantly after queueing the input buffer.
So instead you should do something like this
while(!endReached) {
// Try drain decoder output first
BufferInfo info = new BufferInfo();
int outIndex = decoder.dequeueOutputBuffer(info, 10000);
switch (outIndex) {
...
}
// Feed decoder input
if (inputAvailable) {
int inIndex = decoder.dequeueInputBuffer(10000);
...
}
}

Related

NullPointerException: thrown in OnMapReady method

Started running my google maps project and encountered this NullPointerException error in the
Logcat ->
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.sachiewerk.smart_healthcare.pharma2.onMapReady(pharma2.java:100)
at com.google.android.gms.maps.zzak.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:504)
at fr.b(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):20)
at com.google.android.gms.maps.internal.bg.a(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):5)
at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):5)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
The app finds and displays nearby pharmacies, This class show details of nearby pharmacy details like(address, phone numbers, website URI and price ratings) in a custom info window.
this is the class java code
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sachiewerk.smart_healthcare.models.PlaceInfo;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
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.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class pharma2 extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready..");
mMap = googleMap;
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.getUiSettings().setMyLocationButtonEnabled(false);
buildGoogleApiClient();
init();
}
/*
------------------------------------------------------------------------
*/
Button btnPharma = (Button) findViewById(R.id.btnPharma);
btnPharma.setOnClickListener(new View.OnClickListener(){
String search = "pharmacy";
#Override
public void onClick (View v){
mMap.clear();
String url = getUrl(latitude, longitude, search);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
GetNearbyBanksData getNearbyPlacesData = new GetNearbyBanksData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(pharma2.this, "These are your Nearby Pharmacies! ",
Toast.LENGTH_LONG).show();
}
});
/*
------------------------------------------------------------------------
*/
}
private static final String TAG = "pharma2";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 20f;
private static final int PLACE_PICKER_REQUEST = 1;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136));
//widgets
private AutoCompleteTextView mSearchText;
private ImageView mGps;
private ImageView mInfo;
private ImageView mPlacePicker;
//vars
private boolean mLocationPermissionGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutocompleteAdapter mPlaceAutocompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
private Marker mMarker;
private Location mLastLocation;
LocationRequest mLocationRequest;
double latitude, longitude;
private int PROXIMITY_RADIUS = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hosp2);
mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
mGps = (ImageView) findViewById(R.id.ic_gps);
mInfo = (ImageView) findViewById(R.id.place_info);
mPlacePicker = (ImageView) findViewById(R.id.place_picker);
getLocationPermission();
}
private void init() {
Log.d(TAG, "init: initializing");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mSearchText.setOnItemClickListener(mAutocompleteClickListener);
mPlaceAutocompleteAdapter = new PlaceAutocompleteAdapter(this, Places.getGeoDataClient(this, null),
LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(mPlaceAutocompleteAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
//execute our method for searching
geolocate();
}
return false;
}
});
}
mGps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked gps icon");
getDeviceLocation();
}
});
mInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked place Info");
try {
if (mMarker.isInfoWindowShown()) {
mMarker.hideInfoWindow();
} else {
Log.d(TAG, "onClick: place info: " + mPlace.toString());
mMarker.showInfoWindow();
}
} catch (NullPointerException e) {
Log.e(TAG, "onClick: NullPointerException: " + e.getMessage());
}
}
});
mPlacePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(pharma2.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, "onClick: GooglePlayServicesRepairableException: " + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, "onClick: GooglePlayServicesNotAvailableException: " + e.getMessage());
}
}
});
hideSoftKeyboard();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, place.getId());
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
}
}
private void geolocate() {
Log.d(TAG, "geolocate: geolocating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(pharma2.this);
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchString, 2);
} catch (IOException e) {
Log.d(TAG, "geolocate: IOException: " + e.getMessage());
}
if (list.size() > 0) {
Address address = list.get(0);
Log.d(TAG, "geolocate: found a location: " + address.toString());
//Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM,
address.getAddressLine(0));
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new
StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyAvxiw4FVJzY-XGx9mW8fNde4bjvc8mlbo");
return (googlePlacesUrl.toString());
}
/*
------------------------------------------------------------------------
*/
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting device's current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM, "Your Device's Location");
} else {
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(pharma2.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom, PlaceInfo placeInfo) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
mMap.clear();
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(pharma2.this));
if (placeInfo != null) {
try {
String snippet = "Address: " + placeInfo.getAddress() + "\n" +
"Phone Number: " + placeInfo.getPhoneNumber() + "\n" +
"Website: " + placeInfo.getWebsiteUri() + "\n" +
"Rating: " + placeInfo.getRating() + "\n";
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(placeInfo.getName())
.snippet(snippet);
mMarker = mMap.addMarker(options);
} catch (NullPointerException e) {
Log.e(TAG, "moveCamera: NullPointerException: " + e.getMessage());
}
} else {
mMap.addMarker(new MarkerOptions().position(latLng));
}
hideSoftKeyboard();
}
private void moveCamera(LatLng latLng, float zoom, String title) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
if (!title.equals("My Location")) {
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(title);
mMap.addMarker(options);
}
hideSoftKeyboard();
}
private void initMap() {
Log.d(TAG, "initMap: initializing map..");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(pharma2.this);
}
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called");
mLocationPermissionGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionGranted = true;
//initialize map
initMap();
}
}
}
}
private void hideSoftKeyboard() {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/*---------------------------------------------------------------------------------------------------------- */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
/*---------------------------------------------------------------------------------------------------------- */
/*
----------------------Google Places Autocomplete suggesstions-------------------------------------------------------------
*/
private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
hideSoftKeyboard();
final AutocompletePrediction item = mPlaceAutocompleteAdapter.getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient ,placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
if(!places.getStatus().isSuccess()){
Log.d(TAG, "onResult: PLace query did not complete successfully: " + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(TAG, "onResult: name: " + place.getName());
mPlace.setAddress(place.getAddress().toString());
Log.d(TAG, "onResult: address: " + place.getAddress());
// mPlace.setAttribution(place.getAttributions().toString());
// Log.d(TAG, "onResult: attribution: " + place.getAttributions());
mPlace.setId(place.getId());
Log.d(TAG, "onResult: id: " + place.getId());
mPlace.setLatLng(place.getLatLng());
Log.d(TAG, "onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(TAG, "onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(TAG, "onResult: Phone Number:" + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(TAG, "onResult: Website: " + place.getWebsiteUri());
Log.d(TAG, "onResult: place: " + mPlace.toString());
}catch(NullPointerException e){
Log.d(TAG, "onResult: NullPointerException: " + e.getMessage() );
}
moveCamera(new LatLng(place.getViewport().getCenter().latitude,
place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace);
places.release();
}
};
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mMarker != null) {
mMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("You are Here!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(pharma2.this, "Your Current Location",
Toast.LENGTH_LONG).show();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
Really want to get this app to work because it is my end of year project for my java class.
Any help will much appreciated.
I think it's not working because you're calling the method OnMapReady() before creating the view in the OnCreate() method. Besides, you're not calling the method initMap() anywhere.
i think you got error on this part.
Button btnPharma = (Button) findViewById(R.id.btnPharma);
btnPharma.setOnClickListener(new View.OnClickListener(){});
Your activity_hosp2.xml doesn't have btnPharma id, thus it got
Attempt to invoke virtual method on a null object reference
when you try to listener to null object.

can anyone explain how to initialize realm instance outside the Activity? for example while parsing json with volley and gson?

This is my Api class where json parsing is being done. But wherever I call Realm.getDefaultInstance(), at that line app stops running..Please help ...m stuck..Thanks in advance..
package com.portea.internal.api.realm_api;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.portea.internal.app.App;
import com.portea.internal.constants.Constants;
import com.portea.internal.constants.PrintLog;
import com.portea.internal.enums.Transaction;
import com.portea.internal.network.Network;
import com.portea.internal.realm_pojo_container.AppointmentPojos.Appointments;
import com.portea.internal.realm_pojo_container.AppointmentPojos.AppointmmentMainObject;
import com.portea.internal.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import io.realm.Realm;
import io.realm.RealmList;
/**
* Created by Dipti on 26/3/17.
*/
public class ApiAppointment extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private boolean isSubordinateAppointment = false;
private boolean forceReload = false;
String Tag = "ApiAppointment";
// RealmList<AppointmmentMainObject> realmObjList =null;
RealmList<AppointmmentMainObject> inpList = null;
Collection<AppointmmentMainObject> realmApts;
private Context context;
private Realm my_realm;//where to initialize this realm instance and where to close it
AppointmmentMainObject obj1, obj2;
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url) {
super(Request.Method.GET, getApiUrl(url), errorListener);
this.listener = listener;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, boolean forceReload) {
super(Request.Method.GET, getApiUrl(url), errorListener);
this.listener = listener;
this.forceReload = forceReload;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.v(Tag + "dip", "" + getApiUrl(url));
}
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, String append) {
super(Request.Method.GET, getApiUrl(url) + append, errorListener);
this.listener = listener;
isSubordinateAppointment = true;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.v(Tag, "" + getApiUrl(url) + append);
}
public ApiAppointment(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, String url, String append, boolean forceReload) {
super(Request.Method.GET, getApiUrl(url) + append, errorListener);
this.listener = listener;
this.forceReload = forceReload;
isSubordinateAppointment = true;
setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e(Tag, " " + getApiUrl(url) + append);
}
static String getApiUrl(String url_append) {
String lastSynced = App.getPref().get(Constants.STORAGE_KEY_LAST_APPOINTMENT_SYNCED);
if (lastSynced == null) {
lastSynced = "0";
}
if (url_append.length() > 0) {
lastSynced = "0";
}
return Network.getTxnPath(Transaction.APPOINTMENTS, "/get?user_id="
+ App.getUser().getUserId() + "&key=" + App.getUser().getKey()
+ "&version=" + App.version + "&last_synced=" + lastSynced + url_append);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
Log.v(Tag, "========================================>>");
//Utils.sendLogoutBroadCast(App.getAppContext(), response.statusCode);
Gson gson = new GsonBuilder().create();
// Realm.init(App.getAppContext());
// my_realm = Realm.getDefaultInstance();
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i(Tag, jsonString);
JSONObject MainObject = new JSONObject(jsonString);
JSONArray dataObj = MainObject.getJSONArray("data");
for (int i = 0; i < dataObj.length(); i++) {
JSONObject singleUserObj = dataObj.getJSONObject(i);
JSONArray apointment = singleUserObj.getJSONArray("appointments");
for (int j = 0; j < apointment.length(); j++) {
JSONObject appointmentObj = apointment.getJSONObject(j);
// Appointments appointments=realm.createObjectFromJson(Appointments.class,appointmentObj);
// Log.v("Realmcheck",appointments.toString());
Type type = new TypeToken<RealmList<Appointments>>() {}.getType();
RealmList<Appointments> appointmentsObjList = gson.fromJson(apointment.toString(), type);
// List<Appointments> realm_copy_of_list=my_realm.copyToRealm(appointmentsObjList); Log.v("size", String.valueOf(appointmentsObjList.toString()));
RealmList<Appointments> apo = new RealmList<Appointments>();
Log.v("dipti", appointmentsObjList.get(j).toString());
// apo = (RealmList<Appointments>) my_realm.copyToRealm(appointmentsObjList);
}
}
// Log.v(Tag + "xx", AppointmmentMainObject.getClinicianName());
// Log.i("packageFee", String.valueOf(AppointmmentMainObject.getPackageFee()));
return Response.success(MainObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
PrintLog.d("e: " + e);
e.printStackTrace();
return Response.error(new ParseError(e));
} catch (JSONException je) {
PrintLog.d("je: " + je);
je.printStackTrace();
return Response.error(new ParseError(je));
} catch (NullPointerException ne) {
PrintLog.d("ne: " + ne);
return Response.error(new ParseError(ne));
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
String creds = String.format("%s:%s", "stage", "d7kVzNZDqn");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
params.put("Authorization", auth);
params.put("DEVICE_ID", App.deviceId);
return params;
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
try {
Utils.sendLogoutBroadCast(App.getAppContext(),
volleyError.networkResponse.statusCode);
Log.e("onErrorResponse", ""
+ volleyError.networkResponse.statusCode);
} catch (Exception e) {
e.printStackTrace();
}
return volleyError;
}
#Override
protected void deliverResponse(JSONObject response) {
}
}
I think your main problem is in the Realm initialization. You should have an application class and initialize your Realm in there. Like this:
public class BaseApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(config);
}
}
And then you can call my_realm = Realm.getDefaultInstance();
I hope this solves your problem.

Register Page Data store but no JSON encode received

I'm sure it's just a minor problem but I can't figure out what I need to change: I have a register page in my app. When the user inserts data, the data is passed to php script and stored in MYSQL database. The connection works as I get a new user in the db, but the json $success doesn't work - I want to make a Toast and change to a new activity if the user could register, but it does nothing when I click on the button.
Here is my Java Code:
package com.example.android.festivalapp;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class JetztRegistrieren extends Startseite {
Button bRegistrierungAbschliessen;
EditText etUserName, etUserMail, etUserPasswort, etUserPasswort2, etGeburtsdatum, etTelefonnummer;
RadioButton rbMaennlich, rbWeiblich;
RadioGroup rgGeschlecht;
protected String enteredname, enteredemail, enteredpassword, enteredpassword2, enteredGeb, enteredTelnr, userGender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jetzt_registrieren);
bRegistrierungAbschliessen = (Button) findViewById(R.id.bRegistrierungAbschliessen);
etUserName = (EditText) findViewById(R.id.etUserName);
etUserMail = (EditText) findViewById(R.id.etUserMail);
etUserPasswort = (EditText) findViewById(R.id.etUserPasswort);
etUserPasswort2 = (EditText) findViewById(R.id.etUserPasswort2);
etGeburtsdatum = (EditText) findViewById(R.id.etGeburtsdatum);
etTelefonnummer = (EditText) findViewById(R.id.etTelefonnummer);
rgGeschlecht = (RadioGroup) findViewById(R.id.rgGeschlecht);
rbMaennlich = (RadioButton) findViewById(R.id.rbMaennlich);
rbWeiblich = (RadioButton) findViewById(R.id.rbWeiblich);
bRegistrierungAbschliessen.setOnClickListener(new View.OnClickListener() {
//testen, ob Mail und Passwort ausgefüllt oder lang genug
#Override
public void onClick(View v) {
enteredname = etUserName.getText().toString();
enteredemail = etUserMail.getText().toString();
enteredpassword = etUserPasswort.getText().toString();
enteredpassword2 = etUserPasswort2.getText().toString();
enteredTelnr = etTelefonnummer.getText().toString();
enteredGeb = etGeburtsdatum.getText().toString();
userGender = ((RadioButton) findViewById(rgGeschlecht.getCheckedRadioButtonId())).getText().toString();
String serverUrl = "http://www.pou-pou.de/stagedriver/android/register.php";
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(serverUrl, enteredname, enteredemail, enteredpassword, enteredpassword2, enteredTelnr, enteredGeb, userGender);
if (enteredname.equals("") || enteredemail.equals("") || enteredpassword.equals("") || enteredpassword2.equals("") || enteredGeb.equals("")) {
Toast.makeText(JetztRegistrieren.this, "Bitte alle Felder ausfüllen", Toast.LENGTH_LONG).show();
return;
}
}
class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("http://www.pou-pou.de/stagedriver/android/register.php");
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("enteredname", params[1]));
nameValuePairs.add(new BasicNameValuePair("enteredemail", params[2]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword", params[3]));
nameValuePairs.add(new BasicNameValuePair("enteredpassword2", params[4]));
nameValuePairs.add(new BasicNameValuePair("enteredTelnr", params[5]));
nameValuePairs.add(new BasicNameValuePair("enteredGeb", params[6]));
nameValuePairs.add(new BasicNameValuePair("userGender", params[7]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(JetztRegistrieren.this, "Passwörter stimmen nicht überein", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(JetztRegistrieren.this, Startseite.class);
Toast.makeText(JetztRegistrieren.this, "Willkommen bei Stage Driver! Jetzt loslegen.", Toast.LENGTH_LONG).show();
startActivity(intent);
return;
}
System.out.println("Resulted Value: " + result);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 2;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
});
}
}
And this is the php file:
<?php
include('config.php');
session_start();
$name = $_POST["enteredname"];
$pass = $_POST["enteredpassword"];
$pass2 = $_POST["enteredpassword2"];
$email = $_POST["enteredemail"];
$tel = $_POST["enteredTelnr"];
$geb = $_POST["enteredGeb"];
$gender = $_POST["userGender"];
if($pass != $pass2) {
$success = 0;
}
else {
$hash = md5($pass);
$speichern = "INSERT INTO user (user_name, user_pw, user_mail, user_tel, user_geb, user_geschl)
VALUES('$name', '$hash', '$email', '$tel', '$geb', '$gender');";
mysql_query($speichern) or die(mysql_error());
if($speichern) {
$success = 1;
}
}
echo json_encode($success);
?>
Thanks in advance!
The problem is that you are not returning an HTTP header for the content type you are returning.
Add this to the top of your php script:
header("Content-Type: application/json;charset=utf-8");
So I think I found the error, in the log it says the jsonresult cannot be converted, it's because in the php script I wrote $success = 0; but instead I think it has to be something like $response["success"] = 0;

GoogleMaps displaying "locals" on wrong position

i want to display the CurrentPosition of the mobile phone and display all bar|cafe nearby the position.
The CurrentPosition works.
But the displaying of the bars/cafes is wrong. It seems like they are showing up from the center of vienna and not from the position of my phone.
Would be really thankful if someone could find the problem
MapsActivity.java
package androfenix.currentpositionandplacesnearby;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
LatLng latLng;
double mLatitude=0;
double mLongitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Mit setMapType setzen wir das Aussehen der Karte auf "Hybrid"
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onPause()
{
super.onPause();
//Unregister for location callbacks:
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
// Create a LatLng object for the current location
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
StringBuilder sbValue = new StringBuilder(sbMethod());
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
public StringBuilder sbMethod() throws SecurityException
{
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=50000");
sb.append("&sensor=true");
sb.append("&keyword=" + "bar|cafe");
sb.append("&key= SERVER API KEY ");
Log.d("Map", "url: " + sb.toString());
return sb;
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParserTask
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
Log.d("Map", "list size: " + list.size());
// Clears all the existing markers;
//mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
Log.d("Map", "place: " + name);
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// Placing a marker on the touched position
Marker m = mMap.addMarker(markerOptions);
// ZZZZZZZZZZZZZZZZZZZ
}
}
}
public class Place_JSON {
/**
* Receives a JSONObject and returns a list
*/
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for (int i = 0; i < placesCount; i++) {
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/**
* Parsing the Place JSON object
*/
private HashMap<String, String> getPlace(JSONObject jPlace)
{
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
}
Using the Google Places API for Android, you can discover the place where the device is currently located. That is, the place at the device's currently-reported location. Examples of places include local businesses, points of interest, and geographic locations.
If your app uses PlaceDetectionApi.getCurrentPlace() must request the ACCESS_FINE_LOCATION permission.
The following code sample retrieves the list of places where the device is most likely to be located, and logs the name and likelihood for each place.
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
Log.i(TAG, String.format("Place '%s' has likelihood: %g",
placeLikelihood.getPlace().getName(),
placeLikelihood.getLikelihood()));
}
likelyPlaces.release();
}
});
The PlacePicker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.
The following code snippet retrieves the place that the user has selected:
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();
}
}
}

I want to know, why get a exception of redis.clients.jedis.exceptions.JedisConnectionException?

I used jedis in my java project with one master and slave, once the slave started, it come to this in redis_slave.log:
44764 [2721] 24 Dec 14:07:41.157 * Connecting to MASTER...
44765 [2721] 24 Dec 14:07:41.158 * MASTER <-> SLAVE sync started
44766 [2721] 24 Dec 14:07:41.158 # Error condition on socket for SYNC: Connection refused
and in my java source file, I want to delete all data in redis, so I wrote this code:
public class TestJedisPool {
private Jedis jedis = null;
private JedisPool jedisPool = null;
public TestJedisPool() {
initialPool();
jedis = jedisPool.getResource();
jedis.auth("123456");
}
private void initialPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxActive(20);
config.setMaxIdle(5);
config.setMaxWait(1000L);
config.setTestOnBorrow(false);
jedisPool = new JedisPool(config, "192.168.144.3", 6397);
}
private void masterThread() {
System.out.println(jedis.flushAll());
jedisPool.returnResource(jedis);
jedis.disconnect();
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestJedisPool test = new TestJedisPool();
test.masterThread();
}
}
and get a exception like this:
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:22)
at com.oppo.testpool.TestJedisPool.<init>(TestJedisPool.java:15)
at com.oppo.testpool.TestJedisPool.main(TestJedisPool.java:41)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
any one can help me ?
I modified your code and it works for:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
public class TestJedisPool {
static ExecutorService executor = Executors.newSingleThreadExecutor();
final static ShardedJedisPool redisStatsPool;
static {
String host = "127.0.0.1";
int port = 6379;
List<JedisShardInfo> redisClickShard = new ArrayList<JedisShardInfo>();
redisClickShard.add(new JedisShardInfo(host, port));
JedisPoolConfig config = new JedisPoolConfig();
config.maxActive = 1000;
config.maxIdle = 10;
config.minIdle = 1;
config.maxWait = 30000;
config.numTestsPerEvictionRun = 3;
config.testOnBorrow = true;
config.testOnReturn = true;
config.testWhileIdle = true;
config.timeBetweenEvictionRunsMillis = 30000;
redisStatsPool = new ShardedJedisPool( config, redisClickShard);
}
public TestJedisPool() {
}
String[] getRandomNumber(int min, int max){
String[] test = new String[8];
for (int i = 0; i < test.length; i++) {
int partition = min + (int)(Math.random() * ((max - min) + 1));
test[i] = "key"+partition;
}
return test;
}
static volatile long sum = 0;
public Runnable hincrBy(final String keyname, final String[] keyfields , final long val){
Runnable job = new Runnable() {
#Override
public void run() {
c++;
System.out.println(c);
try {
ShardedJedis shardedJedis = redisStatsPool.getResource();
final Jedis jedis = shardedJedis.getShard("") ;
Pipeline p = jedis.pipelined();
for (String keyfield : keyfields) {
p.hincrBy(keyname, keyfield, val);
sum += val;
}
p.sync();
redisStatsPool.returnResource(shardedJedis);
} catch (Exception e) {
//e.printStackTrace();
}
}
};
return job;
}
static volatile int c = 0;
static final int MAX = (int) Math.pow(10, 6);
void masterThread() {
for (int i = 0; i < MAX; i++) {
String[] keynames = getRandomNumber(100, 1000);
executor.submit(hincrBy("test10^6", keynames, 1L));
}
executor.shutdown();
while(!executor.isTerminated()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int sumTest() {
int total = 0;
try {
ShardedJedis shardedJedis = redisStatsPool.getResource();
final Jedis jedis = shardedJedis.getShard("") ;
Map<String,String> map = jedis.hgetAll("test10^6");
Set<String> keys = map.keySet();
for (String keyfield : keys) {
int v = Integer.parseInt(map.get(keyfield));
total += v;
}
redisStatsPool.returnResource(shardedJedis);
} catch (Exception e) {
//e.printStackTrace();
}
return total;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestJedisPool test = new TestJedisPool();
test.masterThread();
System.out.println(sum);
System.out.println(test.sumTest());
System.out.println(test.sumTest() == sum);
}
}