//Rahees is class in Parse.com for android from where I want to get the list of nearest location from geopoint g.Rahees class has column name "Locations".
I want to get the list of nearest geopoints from g by comparing it with the geopoints listed in Location column of Rahees class
//******************Rahees Class************************//
#ParseClassName("Rahees")
public class Rahees extends ParseObject {
public Rahees()
{
super();
}
public String getDisplayName() {
return getString("displayName");
}
public void setDisplayName(String value) {
put("displayName", value);
}
public static ParseQuery<Rahees> getQuery() {
return ParseQuery.getQuery(Rahees.class);
}
}
//************Main Activity*******************************//
public class MainActivity extends AppCompatActivity {
ParseGeoPoint g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseUser cuser = ParseUser.getCurrentUser();
Rahees haila = new Rahees();
haila.setDisplayName("Rahim");
}
//button for Logging out of system
public void logout(View view)
{
ParseUser.logOut();
Intent intent = new Intent(MainActivity.this, SignUp_Login.class);
startActivity(intent);
}
//Button for going to Map Masti class, it is this button which triggers to compare the geopoint g with the geopoints in the server
public void go_to_maps(View view)
{
Intent intent = new Intent(MainActivity.this, Map_Masti.class);
startActivity(intent);
}
}
//****************************MapMasti Class*****************************//
public class Map_Masti extends FragmentActivity {
ParseGeoPoint g;
private TextView textView;
private SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_masti);
textView = (TextView)findViewById(R.id.text);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
//Query to get the geopoint g from server
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.getInBackground("ccm3xKMmr4", new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
g = (ParseGeoPoint) object.get("user_Location");
Log.d("mohit", g + "");
} else {
// something went wrong
Log.d("mohit", e + " ");
}
}
});
//query to compare which geopoints in the object "Rahees" with column "Locations" are near to geopoing "g"
ParseQuery<Rahees> mapQuery1 = Rahees.getQuery();
mapQuery1.whereWithinKilometers("Locations", g, 6000);
mapQuery1.setLimit(3);
mapQuery1.findInBackground(new FindCallback<Rahees>() {
#Override
public void done(List<Rahees> objects, ParseException e) {
// Handle the results
if (e == null) {//****this is where the exception error comes, it doesn't goes inside if statement****
for (int i = 0; i < objects.size(); i++) {
Log.d("mohit", "2" + objects.get(i).get("Locations"));
}
} else {
Log.d("mohit", "" + e);
}
}
});
}
}
Below is the error I am getting , from the else part
01-10 12:27:38.655 4348-4348/? D/error: com.parse.ParseRequest$ParseRequestException: $nearSphere needs a map operator
I am able to retrive value of g from Parse,output of Log for g is :
ParseGeoPoint[40.000000,30.000000]
Please help
You should do second query only after will get result of first one, because g is null until will be initialized by callback.
Update:
public class Map_Masti extends FragmentActivity {
ParseGeoPoint g;
private SupportMapFragment mapFragment;
private TextView textView;
private void getG() {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.getInBackground("ccm3xKMmr4", new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
g = (ParseGeoPoint) object.get("user_Location");
Log.d("mohit", g + "");
getLocations();
} else {
// something went wrong
Log.d("mohit", e + " ");
}
}
});
}
private void getLocations() {
ParseQuery<Rahees> mapQuery1 = Rahees.getQuery();
mapQuery1.whereWithinKilometers("Locations", g, 6000);
mapQuery1.setLimit(3);
mapQuery1.findInBackground(new FindCallback<Rahees>() {
#Override
public void done(List<Rahees> objects, ParseException e) {
// Handle the results
if (e == null) {//****this is where the exception error comes, it doesn't goes inside if statement****
for (int i = 0; i < objects.size(); i++) {
Log.d("mohit", "2" + objects.get(i).get("Locations"));
}
} else {
Log.d("mohit", "" + e);
}
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_masti);
textView = (TextView) findViewById(R.id.text);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
getG();
}
}
Related
This is my example where I am tapping on the map to get the tapped point coordinates and to send a search request to know more details about that place, for example, city, street. But the response is always null values.
public class MainActivity extends AppCompatActivity implements CameraListener, InputListener, Session.SearchListener {
private ActivityMainBinding binding;
private SearchManager searchManager;
private Session searchSession;
private SearchOptions searchOptions;
private MapObjectCollection mapObjectCollection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapKitFactory.setApiKey("your api key");
MapKitFactory.initialize(this);
searchOptions = new SearchOptions();
searchOptions.setSearchTypes(SearchType.GEO.value);
searchOptions.setGeometry(true);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.mapview.getMap().setNightModeEnabled((getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES);
searchManager = SearchFactory.getInstance().createSearchManager(SearchManagerType.COMBINED);
binding.mapview.getMap().addCameraListener(this);
binding.mapview.getMap().addInputListener(this);
mapObjectCollection = binding.mapview.getMap().getMapObjects();
binding.mapview.getMap().move(
new CameraPosition(new Point(55.751574, 37.573856), 11.0f, 0.0f, 0.0f),
new Animation(Animation.Type.SMOOTH, 0),
null);
}
#Override
protected void onStop() {
super.onStop();
binding.mapview.onStop();
MapKitFactory.getInstance().onStop();
}
#Override
protected void onStart() {
super.onStart();
binding.mapview.onStart();
MapKitFactory.getInstance().onStart();
}
public void submitQueryByName(String query) {
searchSession = searchManager.submit(
query,
Geometry.fromPoint(new Point(40.177200, 44.503490)),
searchOptions,
this);
}
public void submitQueryByPoint(Point point) {
searchSession = searchManager.submit(
point,
11,
searchOptions,
this);
}
#Override
public void onCameraPositionChanged(#NonNull Map map, #NonNull CameraPosition cameraPosition, #NonNull CameraUpdateReason cameraUpdateReason, boolean finished) {
Log.e("onCameraPositionChanged"," cameraPosition: "+cameraPosition+" cameraUpdateReason: "+cameraUpdateReason+" finished: "+finished);
}
#Override
public void onMapTap(#NonNull Map map, #NonNull Point point) {
MapObjectCollection mapObjects = binding.mapview.getMap().getMapObjects();
mapObjects.clear();
PlacemarkMapObject placemarkMapObject = mapObjectCollection.addPlacemark(new Point(point.getLatitude(), point.getLongitude()),
ImageProvider.fromResource(this, R.mipmap.marker_flag));
submitQueryByPoint(point);
Log.e("onMapTap", "point lat - lang: " + point.getLatitude() + " : " + point.getLongitude());
}
#Override
public void onMapLongTap(#NonNull Map map, #NonNull Point point) {
Log.e("onMapLongTap","onMapLongTap");
}
#Override
public void onSearchResponse(#NonNull Response response) {
try {
Log.e("Search", "Response: " + response);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
public void onSearchError(#NonNull Error error) {
String errorMessage = "unknown_error_message";
if (error instanceof RemoteError) {
errorMessage = "remote_error_message";
} else if (error instanceof NetworkError) {
errorMessage = "network_error_message";
}
Log.e("Response error", " error: " + errorMessage);
}
}
In the onMapTap method, I get the tapped point coordinates and send a search request by point
#Override
public void onMapTap(#NonNull Map map, #NonNull Point point) {
MapObjectCollection mapObjects = binding.mapview.getMap().getMapObjects();
mapObjects.clear();
PlacemarkMapObject placemarkMapObject = mapObjectCollection.addPlacemark(new Point(point.getLatitude(), point.getLongitude()),
ImageProvider.fromResource(this, R.mipmap.marker_flag));
submitQueryByPoint(point);
Log.e("onMapTap", "point lat - lang: " + point.getLatitude() + " : " + point.getLongitude());
}
**Response is always null values. What I do wrong?
This is a GitHub whole project for this example https://github.com/davmehrabyan/YandexMapSearch **
UPD: I've found that there is something bad is happening to latitude and longitude field when I'm getting it from the database, for example it does not shows correctly using Toast.
I'm using a Firebase database in my project. It saves locations with additional information to Firebase database and I need to display markers corresponding to that locations on the map.
The writing database works without perfect.
However, reading does not work at all. I've followed this guide and defined the database as a field on my class, added instantiation in onCreate method and added ValueListener.
DatabaseReference databaseEvents;
//some code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
databaseEvents = FirebaseDatabase.getInstance().getReference("events");
}
//somecode
databaseEvents.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// events.clear();
Toast.makeText(MapsActivity.this, "LUL", Toast.LENGTH_SHORT).show();
for (DataSnapshot event : dataSnapshot.getChildren()) {
Event e = event.getValue(Event.class);
events.add(e);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//here I'm trying to display the markers.
When I'm trying to output the size of events it always prints 0 and so it does not print any marker on the map.
The full code is here:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener, GoogleMap.OnInfoWindowClickListener {
private static final int PLACE_PICKER_REQUEST = 1;
private GoogleMap mMap;
private Button addEventBtn;
private PlacePicker.IntentBuilder builder;
private Place place;
private EditText editEventName;
private Spinner typeOfEvent;
private LatLng coordOfNewMarker;
private String nameOfNewMarker;
private String typeOfNewMarker;
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton1, infoButton2;
private OnInfoWindowElemTouchListener infoButtonListener1, infoButtonListener2;
DatabaseReference databaseEvents;
#Override
public void onClick(View v) {
place = null;
switch (v.getId()) {
case R.id.AddEventButton:
callPlacePicker();
break;
}
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, "Info window clicked",
Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
databaseEvents = FirebaseDatabase.getInstance().getReference("events");
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
addEventBtn = findViewById(R.id.AddEventButton);
final MapWrapperLayout mapWrapperLayout = findViewById(R.id.map_relative_layout);
mapWrapperLayout.init(mMap, getPixelsFromDp(MapsActivity.this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.custom_infowindow, null);
this.infoTitle = infoWindow.findViewById(R.id.nameTxt);
this.infoSnippet = infoWindow.findViewById(R.id.addressTxt);
this.infoButton1 = infoWindow.findViewById(R.id.btnOne);
this.infoButton2 = infoWindow.findViewById(R.id.btnTwo);
this.infoButtonListener1 = new OnInfoWindowElemTouchListener(infoButton1,
getResources().getDrawable(R.drawable.round_but_green_sel),
getResources().getDrawable(R.drawable.round_but_red_sel))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(MapsActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton1.setOnTouchListener(infoButtonListener1);
this.infoButtonListener2 = new OnInfoWindowElemTouchListener(infoButton2,
getResources().getDrawable(R.drawable.round_but_green_sel),
getResources().getDrawable(R.drawable.round_but_red_sel))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(MapsActivity.this, marker.getSnippet() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton2.setOnTouchListener(infoButtonListener2);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener1.setMarker(marker);
infoButtonListener2.setMarker(marker);
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
final ArrayList<Event> events = new ArrayList<>();
databaseEvents.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// events.clear();
Toast.makeText(MapsActivity.this, "LUL", Toast.LENGTH_SHORT).show();
for (DataSnapshot event : dataSnapshot.getChildren()) {
Event e = event.getValue(Event.class);
events.add(e);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
/*
This code was being used for SQLite database which now is not being used at all.
ArrayList<Double> lat = new ArrayList<>();
ArrayList<Double> lng = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
ArrayList<String> type = new ArrayList<>();
String query = "SELECT * FROM "+ "locations";
Cursor cursor = locations.getWritableDatabase().rawQuery(query,null);
while(cursor.moveToNext()){
lat.add(cursor.getDouble(cursor.getColumnIndex("lat")));
lng.add(cursor.getDouble(cursor.getColumnIndex("lng")));
name.add(cursor.getString(cursor.getColumnIndex("name")));
type.add(cursor.getString(cursor.getColumnIndex("type")));
}*/
// It always print 0.
Toast.makeText(MapsActivity.this, ((Integer) events.size()).toString(), Toast.LENGTH_SHORT).show();
int sz = events.size();
for(int i = 0; i < sz; i++) {
mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(events.get(i).getLatitude()), Double.parseDouble(events.get(i).getLongitude())))
.title(events.get(i).getName())
.snippet(events.get(i).getType()));
}
addEventBtn.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
openDialog();
}
}
}
public void openDialog() {
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
editEventName = view.findViewById(R.id.editEventName);
typeOfEvent = view.findViewById(R.id.spinnerEventType);
final LocationsDB locations = new LocationsDB(this);
final StatsDB stats = new StatsDB(this);
try {
final String selected = typeOfEvent.getSelectedItem().toString();
}
catch (Exception e) {
Toast.makeText(this, "BAD", Toast.LENGTH_LONG);
}
builder.setView(view)
.setTitle("Create Event")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
coordOfNewMarker = place.getLatLng();
nameOfNewMarker = editEventName.getText().toString();
typeOfNewMarker = typeOfEvent.getSelectedItem().toString();
ContentValues event = new ContentValues();
Geocoder geocoder;
List<Address> addresses = new ArrayList<>();
geocoder = new Geocoder(getApplication(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(coordOfNewMarker.latitude,
coordOfNewMarker.longitude,
1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
event.put("lat", coordOfNewMarker.latitude);
event.put("lng", coordOfNewMarker.longitude);
event.put("name", nameOfNewMarker);
event.put("type", typeOfNewMarker);
event.put("address", address);
locations.insert(event);
addEvent(coordOfNewMarker.longitude, coordOfNewMarker.latitude, typeOfNewMarker, nameOfNewMarker, address);
ContentValues created = new ContentValues();
created.put("type", "created");
created.put("number", stats.get() + 1);
stats.update(created);
mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(editEventName.getText().toString())
.snippet(typeOfEvent.getSelectedItem().toString()));
}
});
builder.show();
}
public void callPlacePicker() {
builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
private void addEvent(Double lng, Double ltd, String type, String name, String address) {
String id = databaseEvents.push().getKey();
Event e = new Event(id, lng.toString(), ltd.toString(), type, name, address);
databaseEvents.child(id).setValue(e);
Toast.makeText(this, "Event added!", Toast.LENGTH_LONG).show();
}
}
I am trying to handle events apart from the onCamerachange Listener such as knowing the event when the camera is dragged and released. For that I have taken help of a custom touch fragment and touch wrapper to manage the touch events but without success.
Here is my main activity code :
public class PickupActivity extends LocationUtils implements OnMapReadyCallback, AddressSearchAdapter.ClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LatLng center;
private TextView pickupMarker;
private LinearLayout markerLayout, addressBox, confirmPickupLayout;
private EditText address, pincodeText, landmarkText;
private ImageView currentLocationButton;
private LatLng latLng, latLng1;
private JSONArray addressComponents, typesArray;
String formattedAddress;
String currentLatitude, currentLongitude;
private Toolbar toolbar;
private SharedPreferenceClass preferenceClass;
private String pincode, gPlaceId, city, country, state, premise, route, enteredText, pickupLat, pickupLong, currentGplaceId;
private AddressSearchAdapter mAdapter;
private RecyclerView mRecyclerView;
private ArrayList<com.packr.classes.Address> addressArrayList = new ArrayList<>();
private JSONObject locationObject, geometryObject;
private com.packr.classes.Address mAddress;
private int pickupToastVisible = 0;
private Boolean pickupLocationSet = false, isAddressTextEmpty = false;
private Button confirmPickupButton;
private Double a, b, x, y;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pickup);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initialize();
onClick();
onSearchTextChanged();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setLayoutManager(new MyLinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mAdapter = new AddressSearchAdapter(getApplicationContext(), this);
mAdapter.setClickListener(this);
mRecyclerView.setAdapter(mAdapter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Set Pickup Location");
setSupportActionBar(toolbar);
}
/**
* function to load map. If map is not created it will create it for you
* */
#Override
public void onResume() {
super.onResume();
}
public void initialize() {
confirmPickupLayout = (LinearLayout) findViewById(R.id.confirmPickupLayout);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
pickupMarker = (TextView) findViewById(R.id.locationMarkertext);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
address = (EditText) findViewById(R.id.addressText);
currentLocationButton = (ImageView) findViewById(R.id.current_location);
addressBox = (LinearLayout) findViewById(R.id.addressBox);
pincodeText = (EditText) findViewById(R.id.pincodeText);
landmarkText = (EditText) findViewById(R.id.landmarkText);
confirmPickupButton = (Button) findViewById(R.id.confirmPickup);
}
public void onClick() {
}
public void onSearchTextChanged() {
address.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() == 0 || s == "") {
isAddressTextEmpty = true;
if (mRecyclerView.getVisibility() == View.VISIBLE) {
mRecyclerView.setVisibility(View.GONE);
}
}
if (s.length() < 16) {
mRecyclerView.setVisibility(View.VISIBLE);
enteredText = s.toString().replace(" ", "");
if (isAddressTextEmpty) {
sendAutocompleteJsonRequest();
}
}
final List<com.packr.classes.Address> filteredModelList = filter(addressArrayList, s.toString());
mAdapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onMapReady(GoogleMap map) {
TouchableMapFragment mFragment;
mFragment = new TouchableMapFragment();
new MapStateListener(map,mFragment,this){
#Override
public void onMapTouched() {
// Map touched
L.m("touched");
}
#Override
public void onMapReleased() {
// Map released
L.m("released");
}
#Override
public void onMapUnsettled() {
// Map unsettled
L.m("unSettled");
}
#Override
public void onMapSettled() {
// Map settled
L.m("settled");
}
};
mMap = map;
map.setMyLocationEnabled(false);
currentLatitude = preferenceClass.getCurrentLatitude();
currentLongitude = preferenceClass.getCurrentLongitude();
a = Double.parseDouble(currentLatitude);
b = Double.parseDouble(currentLongitude);
latLng = new LatLng(Double.parseDouble(currentLatitude), Double.parseDouble(currentLongitude));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory
.fromResource(R.drawable.current_location_marker)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.moveCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(preferenceClass.getPickupAddress());
pincodeText.setText(preferenceClass.getPickupPincode());
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
if (confirmPickupLayout.getVisibility() == View.VISIBLE) {
confirmPickupLayout.setVisibility(View.GONE);
slideOutTowardsBottom();
}
center = mMap.getCameraPosition().target;
currentLatitude = String.valueOf(center.latitude);
currentLongitude = String.valueOf(center.longitude);
latLng1 = new LatLng(center.latitude, center.longitude);
Log.e("Coordinates", String.valueOf(center.latitude) + "," + String.valueOf(center.longitude) + latLng1);
pickupMarker.setText(" Set your Location ");
if (!pickupLocationSet) {
float[] distances = new float[1];
Location.distanceBetween(center.latitude, center.longitude, a, b, distances);
System.out.println("Distance: " + distances[0]);
if (distances[0] > 1000.0) {
sendJsonRequest();
L.m("called");
a = center.latitude;
b = center.longitude;
}
}
}
});
}
public void sendJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
//console test
parseJsonResponse(jsonObject);
if (formattedAddress == null) {
address.setText("Obtaining Address");
} else {
address.setText(formattedAddress);
}
Log.e("error", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
} else if (volleyError instanceof ServerError) {
} else if (volleyError instanceof NetworkError) {
} else if (volleyError instanceof ParseError) {
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
requestQueue.add(jsonObjectRequest);
}
public String getRequestUrl() {
return KEY_GEOCODE_URL +
currentLatitude + KEY_COMMA + currentLongitude +
KEY_SENSOR;
}
public void parseJsonResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(0);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
preferenceClass.savePickupGplaceId(gPlaceId);
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
pincodeText.setText(pincode);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getAutocompleteRequestUrl() {
return KEY_AUTOCOMPLETE_API.concat(enteredText);
}
public void sendAutocompleteJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getAutocompleteRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
mAdapter.setAddressArrayList(addressArrayList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
} else if (volleyError instanceof AuthFailureError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ServerError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof NetworkError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ParseError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
private void parseJSONResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(i);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
if (resultListObject.has(KEY_LOCATION) && !(resultListObject.isNull(KEY_LOCATION))) {
locationObject = resultListObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
if ((resultListObject.has(KEY_GEOMETRY)) && !(resultListObject.isNull(KEY_GEOMETRY))) {
geometryObject = resultListObject.getJSONObject(KEY_GEOMETRY);
if (geometryObject.has(KEY_LOCATION) && !(geometryObject.isNull(KEY_LOCATION))) {
locationObject = geometryObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_CITY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
city = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_COUNTRY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
country = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_STATE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
state = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_PREMISE)) {
premise = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_ROUTE)) {
route = addressComponentsObject.getString(KEY_LONG_NAME);
}
}
}
if (country.contentEquals("India") && city.contentEquals("Kolkata")) {
mAddress = new com.packr.classes.Address();
mAddress.setFormattedAddress(formattedAddress);
mAddress.setCity(city);
mAddress.setCountry(country);
mAddress.setPincode(pincode);
mAddress.setState(state);
mAddress.setStreet(premise);
mAddress.setRoute(route);
mAddress.setLatitude(currentLatitude);
mAddress.setLongitude(currentLongitude);
mAddress.setGplaceId(gPlaceId);
addressArrayList.add(mAddress);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private List<com.packr.classes.Address> filter(List<com.packr.classes.Address> models, String query) {
query = query.toLowerCase();
final List<com.packr.classes.Address> filteredModelList = new ArrayList<>();
for (com.packr.classes.Address model : models) {
final String text = model.getFormattedAddress().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public void slideInFromBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_in_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
public void slideOutTowardsBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_out_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
// to check whether location services are enable or not
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
#Override
public void itemClicked(View view, int position) {
hideKeyboard();
confirmPickupLayout.setVisibility(View.VISIBLE);
slideInFromBottom();
mRecyclerView.setVisibility(View.GONE);
pickupLat = addressArrayList.get(position).getLatitude();
pickupLong = addressArrayList.get(position).getLongitude();
preferenceClass.savePickupLatitude(currentLatitude);
preferenceClass.savePickupLongitude(currentLongitude);
String pincode = addressArrayList.get(position).getPincode();
currentGplaceId = addressArrayList.get(position).getGplaceId();
preferenceClass.savePickupGplaceId(currentGplaceId);
latLng = new LatLng(Double.parseDouble(pickupLat), Double.parseDouble(pickupLong));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(formattedAddress);
if (pincode != null) {
pincodeText.setText(pincode);
}
}
public Boolean validationCheck() {
if (address.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a pickup address");
} else if (pincodeText.getText().length() != 6) {
L.t(getApplicationContext(), "Pincode must contain 6 digits");
} else if (landmarkText.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a landmark");
} else return true;
return false;
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Here is the code for the custom Touch fragement. I have extended MapSupportFragment
public class TouchableMapFragment extends MapFragment {
private View mOriginalContentView;
private TouchableWrapper mTouchView;
public void setTouchListener(TouchableWrapper.OnTouchListener onTouchListener) {
mTouchView.setTouchListener(onTouchListener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
L.m("called");
mOriginalContentView = super.onCreateView(inflater, parent,
savedInstanceState);
mTouchView = new TouchableWrapper(getActivity());
mTouchView.addView(mOriginalContentView);
return mTouchView;
}
#Override
public View getView() {
return mOriginalContentView;
}
}
Here is the code for the touchWrapper
public class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
public void setTouchListener(OnTouchListener onTouchListener) {
this.onTouchListener = onTouchListener;
}
private OnTouchListener onTouchListener;
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onTouchListener.onTouch();
break;
case MotionEvent.ACTION_UP:
onTouchListener.onRelease();
break;
}
return super.dispatchTouchEvent(event);
}
public interface OnTouchListener {
void onTouch();
void onRelease();
}
}
Please help.
I am trying to obtain some data from Parse.com through an AsyncTaskRunner. ANd then I intend to show them in a ListView. My custom adapter code is attached below :
public class ParseObjectAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
List<ParseObject> parseArray;
DBShoppingHelper mydb2;
public ParseObjectAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
parseArray = new ArrayList<>();
}
#Override
public int getCount() {
try {
return parseArray.size();
}
catch (Exception e){
return 0;
}
}
#Override
public ParseObject getItem(int position) { return parseArray.get(position); }
#Override
public long getItemId(int position) {
return position;
}
public String getObjectId(int position){
return getItem(position).getObjectId();
}
public void sortByExpiry()
{
Comparator<ParseObject> comparator = new Comparator<ParseObject>() {
#Override
public int compare(ParseObject lhs, ParseObject rhs) {
return ((Integer) lhs.getInt("expiresIn")).compareTo(rhs.getInt("expiresIn"));
}
};
Collections.sort(parseArray, comparator);
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder;
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.list_item, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.itemNameView = (TextView) convertView.findViewById(R.id.item_name);
holder.itemExpiryView = (TextView) convertView.findViewById(R.id.item_expiry);
// Taking care of the buttons
holder.editButton = (Button) convertView.findViewById(R.id.button_edit);
holder.deleteButton = (Button) convertView.findViewById(R.id.button_delete);
holder.shoppingListButton = (Button) convertView.findViewById(R.id.button_shopping);
// hang onto this holder for future recycling
convertView.setTag(holder);
int expiry = getItem(position).getInt("expiresIn");
if (expiry <= 0) {
holder.itemExpiryView.setTextColor(Color.rgb(255,80,54));
}
// Set listener on the buttons
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Edit Button CLicked", Toast.LENGTH_SHORT).show();
ParseObject p = getItem(position);
Intent goToAddItem = new Intent(mContext,ItemAddPage.class);
goToAddItem.putExtra("catg_passed", p.getString("category"));
goToAddItem.putExtra("update_flag", "YES");
goToAddItem.putExtra("name passed", p.getString("itemName"));
goToAddItem.putExtra("expires_in_passed", p.getString("expiresIn"));
goToAddItem.putExtra("price_passed", p.getString("itemPrice"));
mContext.startActivity(goToAddItem);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject p = getItem(position);
String android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
ParseQuery itemToBeDeleted = new ParseQuery("Items");
itemToBeDeleted.whereEqualTo("ACL", p.getACL());
itemToBeDeleted.whereEqualTo("objectId", p.getObjectId());
final Date deletionDate = new Date();
itemToBeDeleted.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, com.parse.ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
if (Items.size() == 1) {
ParseObject itemToDelete = Items.get(0);
itemToDelete.put("deleted", true);
itemToDelete.put("deletedOn", deletionDate);
itemToDelete.saveEventually();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
parseArray.remove(p);
sortByExpiry();
notifyDataSetChanged();
Toast.makeText(mContext, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
holder.shoppingListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
ParseObject p = getItem(position);
String add_to_list = p.getString("itemName");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String add_date = sdf.format(new Date());
System.out.println(add_date);
mydb2.insertItem(add_to_list, add_date);
Toast.makeText(mContext, "Item added to shopping list", Toast.LENGTH_SHORT).show();
}
});
ParseObject p = getItem(position);
String name2 = p.getString("itemName");
Integer ex = p.getInt("expiresIn");
String days_s ="";
if (ex == 0) {
days_s = "Expires today" ;
}
else if (ex == -1) {
days_s = "Expired yesterday";
}
else if (ex < 0) {
days_s = "Expired " + Math.abs(ex) + " days ago";
}
else if (ex == 1) {
days_s = "Expires tomorrow";
}
else {
days_s = "Expires in " + ex + " days";
}
holder.itemNameView.setText(name2);
holder.itemExpiryView.setText(days_s);
return convertView;
}
public void onClick(View v)
{
Intent viewItem = new Intent(v.getContext(), ItemAddPage.class);
v.getContext().startActivity(viewItem);
}
private static class ViewHolder {
public TextView itemNameView;
public TextView itemExpiryView;
public Button editButton;
public Button deleteButton;
public Button shoppingListButton;
}
public void updateData(List<ParseObject> arrayPassed) {
// update the adapter's data set
parseArray = arrayPassed;
notifyDataSetChanged();
}
}
This is the method from which I am calling it..
public class WelcomeParse extends Activity {
ListView currentListView;
List<ParseObject> currentList;
ParseObjectAdapter itemAdder;
String catg;
DBShoppingHelper mydb2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
setContentView(R.layout.activity_main);
itemAdder = new ParseObjectAdapter(this, getLayoutInflater());
mydb2 = new DBShoppingHelper(this);
AsyncTaskAllItems runner = new AsyncTaskAllItems();
runner.execute();
// itemAdder.notifyDataSetChanged();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public class AsyncTaskAllItems extends AsyncTask<String, String, String> {
private String resp;
private Integer numItems = 0;
#Override
protected String doInBackground(String... params) {
try {
ParseQuery itemsAll = new ParseQuery("Items");
itemsAll.whereEqualTo("owner", ParseUser.getCurrentUser().getUsername());
// itemsByCategory.whereEqualTo("category", catg);
itemsAll.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
Log.d("owner", ParseUser.getCurrentUser().getUsername());
// HERE SIZE is 0 then 'No Data Found!'
numItems = Items.size();
if (numItems > 0) {
currentList = Items;
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
resp = "Done";
}
// catch (InterruptedException e) {
// e.printStackTrace();
// resp = e.getMessage();
// }
catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
}
I do not get any error and the log correctly shows the number of items that should be retrieved. But the view does not get updated with the relevant data.
COuld anyone please show me where I am wrong? Anything else you need, just let me know. Much appreciated.
Try after replacing
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
With
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
currentListView.setAdapter(itemAdder);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
}
I am new to parse ,i am able to store data to its database and also to retrieve some information like object-id from database but when I try to send push notification i usually get the above mentioned error.Query which i am using to send push notification with object-id corresponding to the given Friend-id.
public class MainActivity extends Activity {
private RadioButton genderFemaleButton;
private RadioButton genderMaleButton;
private Button getObjectId,sndpush;
private EditText ageEditText, frndidEditText, objectidEditText;
private RadioGroup genderRadioGroup;
private String FrndTextString, ageTextString, objectid;
private ParseObject sid;
public static final String GENDER_MALE = "male";
public static final String GENDER_FEMALE = "female";
protected static final String ParseIntallation = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(this, "c7fOlMSS4S8rxI53m0u49maP1Kab8PWVWSNwVu3s", "0xOUq1uoDb2NIi1jYZHWANZ9PP4X4W7vDfcA1UOw");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.saveInBackground();
// Track app opens.
ParseAnalytics.trackAppOpened(getIntent());
getObjectId = (Button) findViewById(R.id.get_button);
genderFemaleButton = (RadioButton) findViewById(R.id.gender_female_button);
genderMaleButton = (RadioButton) findViewById(R.id.gender_male_button);
ageEditText = (EditText) findViewById(R.id.age_edit_text);
genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
frndidEditText = (EditText) findViewById(R.id.frndid_edit_text);
sndpush = (Button) findViewById(R.id.send_push);
sndpush.setEnabled(true);
sndpush.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JSONObject obj;
try {
obj =new JSONObject();
obj.put("alert","erwerwe");
obj.put("action","com.parse.pushnotifications.UPDATE_STATUS");
obj.put("customdata","My string");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("objectId",objectidEditText.getText().toString() );
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
// vk
objectidEditText = (EditText) findViewById(R.id.objectid_edit_text);
getObjectId.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getObjectId();
}
});
}
#Override
public void onStart() {
super.onStart();
// Display the current values for this user, such as their age and gender.
displayUserProfile();
refreshUserProfile();
}
// Save the user's profile to their installation.
public void saveUserProfile(View view) {
ageTextString = ageEditText.getText().toString();
FrndTextString = frndidEditText.getText().toString();
if (ageTextString.length() > 0) {
sid.put("age",
Integer.valueOf(ageTextString));
}
if (FrndTextString.length() > 0) {
sid.put("FriendId",
FrndTextString);
}
if (ageTextString.length() > 0) {
ParseInstallation.getCurrentInstallation().put("age", Integer.valueOf(ageTextString));
}
if (FrndTextString.length() > 0) {
ParseInstallation.getCurrentInstallation().put("FriendId", Integer.valueOf(FrndTextString));
}
if (genderRadioGroup.getCheckedRadioButtonId() == genderFemaleButton
.getId()) {
sid.put("gender",
GENDER_FEMALE);
} else if (genderRadioGroup.getCheckedRadioButtonId() == genderMaleButton
.getId()) {
sid.put("gender",
GENDER_MALE);
} else {
sid.remove("gender");
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ageEditText.getWindowToken(), 0);
sid.saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast toast = Toast.makeText(
getApplicationContext(),
R.string.alert_dialog_success,
Toast.LENGTH_SHORT);
toast.show();
} else {
e.printStackTrace();
Toast toast = Toast.makeText(
getApplicationContext(),
R.string.alert_dialog_failed,
Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
// Get the user's Id from parse.com.
#SuppressWarnings({ "rawtypes", "unchecked" })
public void getObjectId() {
#SuppressWarnings("rawtypes")
ParseQuery query = new ParseQuery("sid");
query.whereEqualTo("FriendId", FrndTextString);
query.getFirstInBackground(new GetCallback() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("objectId", "The getFirst request failed.");
} else {
String objectid = object.getObjectId();
objectidEditText.setText(objectid);
sndpush.setEnabled(true);
Log.d("objectId", "Retrieved the object.");
}
}
});
}
// Refresh the UI with the data obtained from the current ParseInstallation
// object.
private void displayUserProfile() {
sid =ParseInstallation.create("sid");
String gender = sid.getString(
"gender");
int age = ParseInstallation.getCurrentInstallation().getInt("age");
if (gender != null) {
genderMaleButton.setChecked(gender.equalsIgnoreCase(GENDER_MALE));
genderFemaleButton.setChecked(gender
.equalsIgnoreCase(GENDER_FEMALE));
} else {
genderMaleButton.setChecked(false);
genderFemaleButton.setChecked(false);
}
if (age > 0) {
ageEditText.setText(Integer.valueOf(age).toString());
}
}
private void refreshUserProfile() {
ParseInstallation.getCurrentInstallation().refreshInBackground(
new RefreshCallback() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
displayUserProfile();
}
}
});
}
}
Please help me in solving this issue as I googled a lot but haven’t found anything good solution.Any help will be appreciated.
Thanks.