how to send the LatLng result of OnPostExecute() to url - google-maps

I am using Googlemaps v2.
I have to send the values of latlng, i.e.: the routePoints to the server.
I am displaying the latlng in onlocationchanged().
I need to send these values to an URL.
Here is my code.
public class MapDetail extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener,
OnMapLongClickListener {
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
private static final String TAG_SUCCESS = "successfully stored";
GoogleMap mMap;
LocationClient mLocationClient;
Marker marker;
LatLng ll;
LatLng point1;
LatLng cLocation, pLocation;
List<LatLng> routePoints;
private List<MarkerOptions> markerOptions = new ArrayList<MarkerOptions>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (serviceOk()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// mMap.setMyLocationEnabled(true);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
} else {
Toast.makeText(this, "Map Not Avialable !!", Toast.LENGTH_LONG)
.show();
}
} else {
setContentView(R.layout.activity_main);
}
routePoints = new ArrayList<LatLng>();
}
public boolean serviceOk() {
int isAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,
this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "can not connect google play services",
Toast.LENGTH_LONG).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mMap = mapFrag.getMap();
if (mMap != null) {
}
}
return (mMap != null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity:
Intent i = new Intent(this, ComInfo.class);
startActivity(i);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "Connected To Location Service", Toast.LENGTH_LONG)
.show();
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(5000);
request.setFastestInterval(1000);
mLocationClient.requestLocationUpdates(request, this);
mMap.setOnMapLongClickListener(this);
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
String msg = "Location:" + location.getLatitude() + ","
+ location.getLongitude();
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
drawCircle(location);
for (int i = 0; i < this.markerOptions.size(); i++) {
mMap.addMarker(markerOptions.get(i));
}
LatLng ll1 = new LatLng(location.getLatitude(), location.getLongitude());
routePoints.add(ll1);
for (int i = 0; i < routePoints.size(); i++) {
Polyline route = mMap.addPolyline(new PolylineOptions().width(5)
.color(Color.GREEN).geodesic(true).zIndex(10));
route.setPoints(routePoints);
}
new AttemptSave().execute();
}
private void drawCircle(Location location) {
mMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),
location.getLongitude());
mMap.addCircle(new CircleOptions().center(currentPosition).radius(50)
.fillColor(0x330000FF).strokeColor(Color.BLUE).strokeWidth(3));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15f).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
protected void onPause() {
mLocationClient.disconnect();
super.onPause();
}
#Override
protected void onResume() {
mLocationClient.connect();
super.onResume();
}
#Override
protected void onStop() {
mLocationClient.disconnect();
super.onStop();
}
#Override
public void onMapLongClick(LatLng point) {
this.point1 = point;
MarkerOptions moMarkerOptions = new MarkerOptions()
.position(point)
.title("se guarda el punto")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
Marker marker = mMap.addMarker(moMarkerOptions);
this.markerOptions.add(moMarkerOptions);
new AttemptSave().execute("test");
}
class AttemptSave extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args0) {
String res = sendJSON();
Log.d("InputStream", res);
return res;
}
private String sendJSON() {
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("MY_URL");
String json = "";
json = this.getJSONObject().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (IOException e) {
Log.d("InputStream", e.getLocalizedMessage()); // e.getLocalizedMessage());
}
return result;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
private JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("id", 1);
obj.put("lat", point1.latitude);
obj.put("long", point1.longitude);
obj.put("track", "");
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
new Saveroute().execute();
}
// Adding all the points in the route to LineOptionslineOptions.addAll(points) lineOptions.width(2);lineOptions.color(Color.RED);
}
}
}
class Saveroute extends AsyncTask<String, String, String >{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}}
}

In onLocationChanged(Location location) you are not initializing the point1, do as the same way you are doing in onMapLongClick()
#Override
public void onLocationChanged(Location location) {
point1=new LatLng(location.getLatitude(),location.getLongitude());
...
}

Related

I have a problem to use Volley. want to use POST method with some parameters and get Array type response but my response is not array type

I have a problem using Volley. want to use POST method with some parameters and get Array type response but my response is not an array type. Here, I share my request code and response.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
route = null;
route_spinner.setSelection(0);
check_in_date = null;
check_out_date = null;
adults = child = room = child1 = child2 = child3 = child4 = child5 = 0;
text_adults.setText("0 Adult");
text_child.setText("0 Child");
text_room.setText("0 Room");
layout_child.setVisibility(View.GONE);
in_date.setText("Add Date");
out_date.setText("Add Date");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};
queue.add(postRequest);
when u use string request response you get will be string also.
you should turn that response to JsonArray , then get bojects from that JsonArray something like this :
if (response != null) {
JSONArray fetchlist = JSONArray(response);
for (int i=0 ; i<fetchlist .lenght ; i++) {
JSONObject obj = fetchlist.getJSONObject(i);
Int idd = obj.getInt("genderid");
I have solved this question in this way. Where hudx_Object and hudx_JSON is JSONObject
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest hudxconnect = new StringRequest(Request.Method.POST, "https://umrahtech.com/umrahtechapi.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
hudx_Object = new JSONObject(response);
if (hudx_Object != null) {
hudx_JSON = hudx_Object.getJSONObject("response");
hudx_Object = new JSONObject(hudx_JSON.toString());
} else {
hudx_Object = null;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("case", "hotel_makkah");
params.put("location", route);
params.put("check_in_1", check_in_date);
params.put("check_out_1", check_out_date);
params.put("passengers", room_array.toString());
return params;
}
};

Error initialising a JSONObject from a string

I'm trying to parse JSON from this
string x = "http://www.neowsapp.com/rest/v1/neo/3725762?api_key=DEMO_KEY";
In the browser I can see all the data from this link, but in the parsing method, it can't be converted to a JSONObject.
The error is in this line, in the Utilsul class:
root = new JSONObject(x);
Here is the class containing all the methods for parsing:
public class Utilsul {
private static URL createURL(String x){
URL myurl = null;
try {
myurl = new URL(x);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Log.i("obtine link ", myurl.toString());
return myurl;
}
private static String raspunsul(URL myurl){
String rasp = "";
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) myurl.openConnection();
inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String liniaCurenta = "";
StringBuffer stringBuffer = new StringBuffer();
while ((liniaCurenta = bufferedReader.readLine())!=null){
stringBuffer.append(liniaCurenta);
}
rasp = stringBuffer.toString();
bufferedReader.close();
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
httpURLConnection.disconnect();
}
// Log.i("Obtine Raspuns", rasp);
return rasp;
}
private static ArrayList<Obiectul> obtineSir(String x){
ArrayList<Obiectul> sirul = new ArrayList<>();
JSONObject root = null;
try {
root = new JSONObject(x);
// Log.i("Obtine root ", root.toString());
JSONArray sirJONURI = root.getJSONArray("close_approach_data");
for (int i=0; i<sirJONURI.length(); i++){
JSONObject obiectCurent = sirJONURI.getJSONObject(i);
String data = obiectCurent.getString("close_approach_date");
JSONObject jsonViteza = obiectCurent.getJSONObject("relative_velocity");
String viteza = jsonViteza.getString("kilometers_per_hour");
JSONObject jsonDistanta = obiectCurent.getJSONObject("miss_distance");
String distanta = jsonDistanta.getString("kilometers");
sirul.add(new Obiectul(data, viteza, distanta));
}
} catch (JSONException e) {
e.printStackTrace();
}
return sirul;
}
public static ArrayList<Obiectul> toateOdata(String x){
URL ur = createURL(x);
String raspuns = raspunsul(ur);
ArrayList<Obiectul> sir = obtineSir(raspuns);
return sir;
}
}
And here is the class where the parsing will be execute:
public class ActivityB extends AppCompatActivity {
RecyclerView rv;
AdaptorRecycler mAdapter;
ArrayList<Obiectul> sirul;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
rv = findViewById(R.id.toataLista);
rv.setLayoutManager(new LinearLayoutManager(this));
ClasaAsy clasaAsy = new ClasaAsy();
clasaAsy.execute(linkul());
}
private String linkul(){
String link = "http://www.neowsapp.com/rest/v1/neo/3725762?api_key=DEMO_KEY";
return link;
}
public class ClasaAsy extends AsyncTask<String, Void, ArrayList<Obiectul>>{
#Override
protected ArrayList<Obiectul> doInBackground(String... strings) {
ArrayList<Obiectul> sir = Utilsul.toateOdata(strings[0]);
return sir;
}
#Override
protected void onPostExecute(ArrayList<Obiectul> obiectuls) {
mAdapter = new AdaptorRecycler(ActivityB.this, obiectuls);
rv.setAdapter(mAdapter);
}
}
And here is the Adapter for the RecyclerView (which is tested working, with an ArrayList randomly written).
public class AdaptorRecycler extends RecyclerView.Adapter<AdaptorRecycler.ClasaVH> {
Context context;
ArrayList<Obiectul> sirul;
public AdaptorRecycler(Context context, ArrayList<Obiectul> sirul) {
this.context = context;
this.sirul = sirul;
}
public class ClasaVH extends RecyclerView.ViewHolder{
TextView data, viteza, distanta;
public ClasaVH(#NonNull View itemView) {
super(itemView);
data = itemView.findViewById(R.id.textView2);
viteza = itemView.findViewById(R.id.textView3);
distanta = itemView.findViewById(R.id.textView4);
}
}
#NonNull
#Override
public ClasaVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ClasaVH(LayoutInflater.from(context).inflate(R.layout.randul, parent, false));
}
#Override
public void onBindViewHolder(#NonNull ClasaVH holder, int position) {
Obiectul a = sirul.get(position);
holder.data.setText(a.getData());
holder.viteza.setText(a.getViteza());
holder.distanta.setText(a.getDistanta());
}
#Override
public int getItemCount() {
return sirul.size();
}
}
For some reason, the JSONObject root is never initialised and I couldn't find why.
Please kindly give me an idea, what else should I try.
Thanks

Not refreshing custom renderer Xamarin forms maps

I created a map with custom marker with real-time location update. But after adding a new pin to the map its not applying the custom renderer. If I zoomed-in or zoomed-out on the map its applying that custom renders for markers. Here is my code.
This Code is in Xamarin.Droid project
public class CustomMapRenderer : MapRenderer, IOnMapReadyCallback, GoogleMap.IInfoWindowAdapter
{
GoogleMap map;
List<Position> routeCoordinates;
List<CustomPin> customPins;
Action<CustomPin> onInfoWindowClicked;
public void OnMapReady(GoogleMap googleMap)
{
map = googleMap;
//map.InfoWindowClick += OnInfoWindowClick;
map.SetInfoWindowAdapter(this);
var polylineOptions = new PolylineOptions();
polylineOptions.InvokeColor(Android.Graphics.Color.Blue);
foreach (var position in routeCoordinates)
{
polylineOptions.Add(new LatLng(position.Latitude, position.Longitude));
}
map.AddPolyline(polylineOptions);
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
map.InfoWindowClick -= OnInfoWindowClick;
// Unsubscribe
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
routeCoordinates = formsMap.RouteCoordinates;
customPins = formsMap.CustomPins;
onInfoWindowClicked = formsMap.OnInfoWindowClicked;
((Android.Gms.Maps.MapView)Control).GetMapAsync(this);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (map != null)
{
map.Clear();
foreach (var pin in customPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Id.ToString());
marker.SetSnippet(pin.Pin.Address);
if(pin.UserType == global::Common.Models.UserType.Driver)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.car));
}
else if (pin.UserType == global::Common.Models.UserType.Rider)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.person));
}
map.AddMarker(marker);
}
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
onInfoWindowClicked(GetCustomPin(e.Marker));
}
private CustomPin GetCustomPin(Marker marker)
{
return customPins.Find(x => x.Id.ToString() ==marker.Title.ToString());
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
var infoImage = view.FindViewById<ImageView>(Resource.Id.markerInfoImage);
var infoTitle = view.FindViewById<TextView>(Resource.Id.markerInfoTitle);
var infoSummary = view.FindViewById<TextView>(Resource.Id.markerInfoSummary);
System.IO.Stream ims = Context.Assets.Open(customPin.Image);
// load image as Drawable
Drawable d = Drawable.CreateFromStream(ims, null);
// set image to ImageView
infoImage.SetImageDrawable(d);
//File file = new File(customPin.Image);
//var image = Android.Net.Uri.FromFile(file);
//var resource=ResourceManager.GetDrawableByName("driverLogActive_icon.png");
//infoImage.SetImageResource(resource);
//infoImag = customPin.Title;
infoTitle.Text = customPin.Title;
infoSummary.Text = customPin.MobileNo;
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
}
This code is in Xamarin.Forms project
public class CustomPin
{
public Pin Pin { get; set; }
public Guid Id { get; set; }
public string Title { get; set; }
public string MobileNo { get; set; }
public string Image { get; set; }
public string UserName { get; set; }
public UserType UserType { get; set; }
}
public class CustomMap : Map
{
public static readonly BindableProperty RouteCoordinatesProperty = BindableProperty.Create(nameof(RouteCoordinates), typeof(List<Position>), typeof(CustomMap), new List<Position>(), BindingMode.TwoWay);
public static readonly BindableProperty CustomPinsProperty = BindableProperty.Create(nameof(CustomPins), typeof(List<CustomPin>), typeof(CustomMap), new List<CustomPin>(), BindingMode.TwoWay);
public List<CustomPin> CustomPins
{
get { return (List<CustomPin>)GetValue(CustomPinsProperty); }
set { SetValue(CustomPinsProperty, value); }
}
public List<Position> RouteCoordinates
{
get { return (List<Position>)GetValue(RouteCoordinatesProperty); }
set { SetValue(RouteCoordinatesProperty, value); }
}
public Action<CustomPin> OnInfoWindowClicked;
public CustomMap()
{
RouteCoordinates = new List<Position>();
CustomPins = new List<CustomPin>();
}
}
This is how I use the custom map to render pin in Xamrin.Fomrs project
private void RenderPin(string longitudeCoordinate, string latitudeCoordinate,bool canMoveToLoacation, string lable,UserType userType,string mobileNo,string image,string userName)
{
double latitude = 0;
double longitude = 0;
double.TryParse(latitudeCoordinate, out latitude);
double.TryParse(longitudeCoordinate, out longitude);
var position = new Position(latitude, longitude);
var pin = new CustomPin
{
Pin = new Pin
{
Type = PinType.Place,
Position = position,
Label = lable,
},
Title = lable,
UserType = userType,
MobileNo = "Mobile No:" + mobileNo,
Image = "profile_images/" + image,
UserName = userName,
Id = Guid.NewGuid()
};
map.CustomPins.Add(pin);
map.Pins.Add(pin.Pin);
if (canMoveToLoacation)
{
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(latitude, longitude), Distance.FromKilometers(2)));
}
}
If you install the Xamarin.Forms.Maps pre-release (2.3.5.255-pre5), you can now just override the CreateMarker() method in MapRenderer. It's much more elegant, and it fixes this problem with pins not being updated when added after map creation.

json parsing using uri for listview in android

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://jsonplaceholder.typicode.com/posts";
//JSON Node Names
// private static final String TAG_OS = "Employee";
private static final String TAG_USER= "userId";
private static final String TAG_NAME = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_BODY = "body";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.user);
name = (TextView)findViewById(R.id.id);
api = (TextView)findViewById(R.id.titile);
body =(TextView)findViewById(R.id.body);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray("");
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_USER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_TITLE);
String body =c.getString(TAG_BODY);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_USER, ver);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, api);
map.put(TAG_BODY, body);
list.add(map);
List=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.list_v,
new String[] { TAG_USER,TAG_NAME, TAG_TITLE,TAG_BODY }, new int[] {
R.id.user,R.id.id, R.id.titile,R.id.body});
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+list.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
json parse:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Logcat here
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArrayorg.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:134)
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:103)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Actually, I faced problem when I click get button to call uri for json parsing.
But when in android device json = null parsing...
Here I used Volley library, it handle the all the things which you did manually(Asynctask, httprequest for json).
I hope it may helps you
// JsonObject request
public void getJSONFromUrl(String url) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", "Response" + response);
//handle the json response
handleResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error", "Error: " + error.getMessage());
}
});
queue.add(jsonObjReq);
}
// converting from json to Map using JsonHelper class
public void handleResponse(JSONObject response) {
Map<String, Object> map = new HashMap<>();
if(response != null){
try {
// JsonObject to Map
map = JsonHelper.toMap(response);
// boolean isSuccess = map.get("success")
// if(isSuccess){
//}
if (map.size() != 0){
// use the data
}
Log.d("MAp","map" + map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here below class will help converting json response to MAP, from map to json.
copied from https://gist.github.com/codebutler/2339666
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
if (object instanceof Map) {
JSONObject json = new JSONObject();
Map map = (Map) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable)object)) {
json.put(value);
}
return json;
} else {
return object;
}
}
public static boolean isEmptyObject(JSONObject object) {
return object.names() == null;
}
public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
return toMap(object.getJSONObject(key));
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}
volley library usage
http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

Error in deleting file using Drive Rest API + Drive Android Api. drive.files().delete(driveid.getResourceId())

Drive REST API + GDAA not able to delete the file.
Gone through this question and comments How to delete a file on google drive using Google Drive Android API but when I use driveid.getResourceId(); to pass as a fileId parameter to old Drive API service.files().delete() method its giving error:
Error Required parameteres must be passed it may lead to Dead Lock
My code:
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private GoogleAccountCredential credential;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private static final int PICKFILE_RESULT_CODE = 1;
private static Uri fileUri;
private ContentsResult contentsresult;
private GoogleApiClient mGoogleApiClient;
byte[] buffer;
String EXISTING_FILE_ID = "";
int folderCreated = 0;
SharedPreferences prefs;
ArrayList<String> dbfileid = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
String fdd="";
DriveFolderResult sky;
private DriveId mFolderDriveId;
String isfolder;
SharedPreferences sp;
String Shared="Shared";
String folderid="";
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
int j=0;
String songfileid="";
private static com.google.api.services.drive.Drive service;
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
String realid ="";
#Override
protected void onResume() {
super.onResume();
initDrive();
}
private void initDrive() {
credential = GoogleAccountCredential.usingOAuth2(this,Arrays.asList(DriveScopes.DRIVE.split(",")));
credential.setSelectedAccountName("shivrajp130#gmail.com");
service = getDriveService(credential);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName("shivrajp130#gmail.com")
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error" + e.toString());
}
}
#Override
public void onConnected(Bundle connectionHint) {
showToast("Inside Connected");
sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
showToast("Inside Connected");
createSkyFolder();
}
private void createSkyFolder()
{
// TODO Auto-generated method stub
try
{
showToast("creating Folder");
if(!sp.getString(isfolder, "false").contains("created"))
{
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().
setTitle("Sky folder").build();
sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
showToast("folder created");
sp.edit().putString(isfolder, "created").commit();
// To store secret ID string of file or folder so that we can later get a DriveId object.
realid = sky.getDriveFolder().getDriveId().encodeToString();
sp.edit().putString(folderid, realid).commit();
showToast("Real== "+realid);
}
DriveId retid = DriveId.decodeFromString(sp.getString(folderid, ""));
DriveFolder folder = Drive.DriveApi.getFolder(getGoogleApiClient(), retid);
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setTitle("New folder")
.build();
MetadataResult res = folder.updateMetadata(getGoogleApiClient(), changeSet2).await();
showToast("Folder== "+folder.getDriveId().encodeToString());
showToast("folder created");
upladfile();
}
catch(Exception e)
{
showToast(""+e);
}
}
private void upladfile() {
// TODO Auto-generated method stub
String storedId=sp.getString(folderid, "");
DriveId retid = DriveId.decodeFromString(storedId);
DriveFolder skyfolder = Drive.DriveApi.getFolder(getGoogleApiClient(), retid);
contentsresult = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = contentsresult.getContents().getOutputStream();
String s = Environment.getExternalStoragePublicDirectory("Download")
.getPath().toString();
showToast(s);
File file = new File(s + "/k.mp3");
showToast("Path=" + Environment.DIRECTORY_DOWNLOADS + "/k"
+ file.length());
buffer = new byte[(int) file.length()];
try {
showToast("started reading n writing");
outputStream.write(buffer);
showToast("Buffer is written");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast("" + e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast("" + e.toString());
}
showToast("" + contentsresult.getContents().toString());
//DriveFolder fldr = Drive.DriveApi.getFolder(getGoogleApiClient(),sky.getDriveFolder().getDriveId());
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setTitle("New file").setMimeType("audio/MP3").setStarred(true)
.build();
showToast("meta data created");
DriveFileResult fileresult = skyfolder.createFile(getGoogleApiClient(),
changeSet2, contentsresult.getContents()).await();
songfileid = fileresult.getDriveFile().getDriveId().encodeToString();
showToast("file has been created "+fileresult.toString());
// Status stat = Drive.DriveApi.requestSync(mGoogleApiClient).await();
showToast("await() complete");
if (!contentsresult.getStatus().isSuccess()) {
showToast("Error while trying to create the file");
return;
}
add_to_db();
getvalues();
//String storedId=sp.getString(folderid, "");
DriveId fffid = DriveId.decodeFromString(dbfileid.get(0));
DriveFile fff = Drive.DriveApi.getFile(getGoogleApiClient(), fffid);
MetadataChangeSet changeSet3 = new MetadataChangeSet.Builder()
.setTitle("renamed")
.build();
MetadataResult res = fff.updateMetadata(getGoogleApiClient(), changeSet3).await();
if(res!=null)
{
showToast("renamed"+res.getMetadata().getTitle());
}
try {
//String iid=fffid.getResourceId();
service.files().delete(fffid.getResourceId()).execute();
showToast("Delete");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
public void add_to_db()
{
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
String id =songfileid;
String name="k";
showToast("database id ="+id);
values.put(fileid,id);
values.put(filename,name);
database.insert(TABLE, null, values);
database.close();
Toast.makeText(this,"Added Successfully" ,Toast.LENGTH_LONG).show();
}
public void getvalues()
{
showToast("getting Values");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
dbfileid.add(cursor.getString(0));
dbfilename.add(cursor.getString(1));
showToast("id=="+dbfileid.get(j).toString());
j++;
} while (cursor.moveToNext());
}
}
private com.google.api.services.drive.Drive getDriveService(GoogleAccountCredential credential) {
return new com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
#Override
public void onConnectionSuspended(int cause) {
showToast("GoogleApiClient connection suspended");
}
}
Except delete everything is working fine.
service.files().delete(fffid.getResourceId()).execute();
Any REST Api's .execute() (as well as GDAA's .await() flavored calls) must be run off UI thread. You should wrap it in:
new AsyncTask<Void, Void, Void>() {
#Override protected Integer doInBackground(String... params) {
//...
return null;
}
}.execute(); // .cancel(true);
or
new Thread(new Runnable() { #Override public void run() {
//....
}}).start();
Good Luck