大家好我已经实现了OnMapReadyCallback应用程序用于发布添加崩溃的活动,在实现活动正常工作之前。我已经添加了所有的OnMapReadyCallBackRequest,但我不知道为什么会崩溃。
package com.classify.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.classify.activity.adapters.CatItem;
import com.classify.activity.adapters.CatePriseAdapter;
import com.classify.activity.adapters.CateSpinnerAdapter;
import com.classify.activity.adapters.cateCityAdapter;
import com.classify.activity.utils.AndroidMultiPartEntity;
import com.classify.activity.utils.Constants;
import com.classify.activity.utils.CustomProgressDialog;
import com.classify.activity.utils.GeocodeJSONParser;
import com.classify.activity.utils.GetJSONObject;
import com.classify.activity.utils.MarshMallowPermission;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@SuppressWarnings("deprecation")
public class AddPostActivity extends AppCompatActivity implements OnMapReadyCallback{
private GoogleMap map;
ArrayList<CatItem>cateList = new ArrayList<CatItem>();
private Spinner spiCategory,spiCity,spiPrice;
ImageView imgadpost1,imgadpost2,imgadpost3;
private String selectedImagePath1 = "";
private String selectedImagePath2 = "";
private String selectedImagePath3 = "";
final private int PICK_IMAGE1 = 11;
final private int CAPTURE_IMAGE1 = 21;
final private int PICK_IMAGE2 = 12;
final private int CAPTURE_IMAGE2 = 22;
final private int PICK_IMAGE3 = 13;
final private int CAPTURE_IMAGE3 = 23;
private String imgPath;
View imageView;
CateSpinnerAdapter adapter;
cateCityAdapter adapterCity;
TextView txtTitle,txtCategory,txtPrice,txtDesc,txtAddress,txtspinnercategory,txtcontact,txtSpinnerCity,txtSpiPrice;
EditText edttitle,edtprice,edtdescription,edtaddrerss,edtcontact;
private UiSettings mUiSettings;
ScrollView scrollViewParent;
ImageView imgMap;
Toolbar toolbar;
Typeface typeface,typeface1;
Button btnPostAdd;
String strtitle = "",strprice="",strdescription="",straddress= "",advertId="",strcontact="",strCity="";
int categoryId = -1;
private double lat = 0.0;
private double lng =0.0;
private SharedPreferences pref;
private AdView mAdView;
private InterstitialAd mInterstitial;
MarshMallowPermission marshMallowPermission;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_post_activity);
MapFragment fm = (MapFragment) getFragmentManager().findFragmentById(R.id.maps_fragment);
fm.getMapAsync(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.AddPost);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
marshMallowPermission = new MarshMallowPermission(this);
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
}
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
}
if (!marshMallowPermission.checkPermissionForCoreLocation()) {
marshMallowPermission.requestPermissionForCoreLocation();
}
if (!marshMallowPermission.checkPermissionForfineLocation()) {
marshMallowPermission.requestPermissionForfineLocation();
}
mAdView = (AdView)findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
pref = getSharedPreferences("loginpreference", MODE_PRIVATE);
advertId = pref.getString("advertId","");
spiCategory = (Spinner) findViewById(R.id.spiCategory);
spiCity = (Spinner) findViewById(R.id.spiCity);
spiPrice = (Spinner)findViewById(R.id.spiPrice);
imgadpost1 = (ImageView) findViewById(R.id.imgadpost1);
imgadpost2 = (ImageView) findViewById(R.id.imgadpost2);
imgadpost3 = (ImageView) findViewById(R.id.imgadpost3);
imgMap = (ImageView) findViewById(R.id.imgmap);
txtAddress = (TextView) findViewById(R.id.txtAddress);
txtCategory= (TextView) findViewById(R.id.txtCategory);
txtDesc = (TextView) findViewById(R.id.txtDesc);
txtPrice = (TextView) findViewById(R.id.txtPrice);
txtTitle = (TextView) findViewById(R.id.txtTitle);
txtcontact = (TextView) findViewById(R.id.txtContact);
txtSpinnerCity = (TextView) findViewById(R.id.txtspinnercity);
txtSpiPrice = (TextView)findViewById(R.id.txtSpiPrice);
edtdescription = (EditText)findViewById(R.id.edtdescription);
edtprice = (EditText)findViewById(R.id.edtprice);
edttitle = (EditText)findViewById(R.id.edttitle);
edtaddrerss = (EditText)findViewById(R.id.edtaddrerss);
edtcontact = (EditText)findViewById(R.id.edtcontact);
btnPostAdd = (Button) findViewById(R.id.btnPostAdd);
txtspinnercategory = (TextView) findViewById(R.id.txtspinnercategory);
scrollViewParent = (ScrollView)findViewById(R.id.scrollView);
View customView = (View)findViewById(R.id.customView);
txtAddress.setTypeface(typeface);
txtCategory.setTypeface(typeface);
txtDesc.setTypeface(typeface);
txtPrice.setTypeface(typeface);
txtTitle.setTypeface(typeface);
txtcontact.setTypeface(typeface);
edtaddrerss.setTypeface(typeface);
edtdescription.setTypeface(typeface);
edtprice.setTypeface(typeface);
edttitle.setTypeface(typeface);
btnPostAdd.setTypeface(typeface);
edtcontact.setTypeface(typeface);
cateList = new ArrayList<CatItem>();
new GetCategoryList().execute();
txtspinnercategory.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
spiCategory.performClick();
}
});
spiCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (cateList.size() > 0) {
txtspinnercategory.setText(cateList.get(position).toString());
categoryId = cateList.get(position).getId();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
imgadpost1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
imageView = v;
startDialog(1);
}
});
imgadpost2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
imageView = v;
startDialog(2);
}
});
imgadpost3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
imageView = v;
startDialog(3);
}
});
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Berat");
list1.add("Bulqizë");
list1.add("Delvinë");
list1.add("Devoll");
list1.add("Dibër");
list1.add("Durrës");
list1.add("Elbasan");
list1.add("Fier");
list1.add("Gramsh");
list1.add("Gjirokastër");
list1.add("Has");
list1.add("Kavajë");
list1.add("Kolonjë");
list1.add("Korçë");
list1.add("Krujë");
list1.add("Kucovë");
list1.add("Kukës");
list1.add("Kurbin");
list1.add("Lezhë");
list1.add("Librazhd");
list1.add("Lushnjë");
list1.add("Malësi e Madhe");
list1.add("Mallakastër");
list1.add("Mat");
list1.add("Mirditë");
list1.add("Peqin");
list1.add("Përmet");
list1.add("Pogradec");
list1.add("Pukë");
list1.add("Sarandë");
list1.add("Skrapar");
list1.add("Shkodër");
list1.add("Tepelenë");
list1.add("Tiranë");
list1.add("Tropojë");
list1.add("Vlorë");
adapterCity = new cateCityAdapter(this,list1,typeface);
spiCity.setAdapter(adapterCity);
txtSpinnerCity.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
spiCity.performClick();
}
});
spiCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
txtSpinnerCity.setText(parent.getItemAtPosition(position).toString());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayList<String> currencyArray = new ArrayList<String>();
currencyArray.add("EUR");
currencyArray.add("LEK");
CatePriseAdapter adapterPrice = new CatePriseAdapter(this,currencyArray,typeface);
spiPrice.setAdapter(adapterPrice);
txtSpiPrice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
spiPrice.performClick();
}
});
spiPrice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
txtSpiPrice.setText(parent.getItemAtPosition(position).toString());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnPostAdd.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mInterstitial = new InterstitialAd(getApplicationContext());
mInterstitial.setAdUnitId(getResources().getString(R.string.interestrial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
mInterstitial.setAdListener(new AdListener()
{
@Override
public void onAdLoaded() {
// TODO Auto-generated method stub
super.onAdLoaded();
//mInterstitial.show();
}
});
String strPriceCurrency= txtSpiPrice.getText().toString();
strtitle = edttitle.getText().toString().trim();
strprice = edtprice.getText().toString().trim() + strPriceCurrency;
straddress = edtaddrerss.getText().toString().trim();
strdescription = edtdescription.getText().toString().trim();
strcontact = edtcontact.getText().toString().trim();
strCity = txtSpinnerCity.getText().toString().trim();
edttitle.setError(null);
edtprice.setError(null);
edtaddrerss.setError(null);
edtdescription.setError(null);
edtcontact.setError(null);
if(strtitle.length() == 0){
edttitle.requestFocus();
edttitle.setError("Enter title.");
}else if(strprice.length() == 0){
edtprice.requestFocus();
edtprice.setError("Enter price.");
}else if(straddress.length() == 0){
edtaddrerss.requestFocus();
edtaddrerss.setError("Enter address.");
}else if(strdescription.length() == 0){
edtdescription.requestFocus();
edtdescription.setError("Enter description.");
}else if(selectedImagePath1.length() == 0 & selectedImagePath2.length() ==0 && selectedImagePath3.length() == 0){
Toast.makeText(AddPostActivity.this,"Please select images.",Toast.LENGTH_LONG).show();
}else if(categoryId == -1){
Toast.makeText(AddPostActivity.this,"Please select Category.",Toast.LENGTH_LONG).show();
}else if(lat == 0.0 && lng == 0.0){
Toast.makeText(AddPostActivity.this,"Please insert location.",Toast.LENGTH_LONG).show();
}else if(strcontact.length() == 0){
edtcontact.requestFocus();
edtcontact.setError("Enter Contact Number.");
}else{
new PostAddTask().execute();
}
}
});
imgMap.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = edtaddrerss.getText().toString();
if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://maps.googleapis.com/maps/api/geocode/json?";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String address = "address=" + location;
String sensor = "sensor=false";
url = url + address + "&" + sensor;
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
});
customView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
scrollViewParent.requestDisallowInterceptTouchEvent(true);
// Disable touch on transparent view
return false;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
scrollViewParent.requestDisallowInterceptTouchEvent(false);
return true;
case MotionEvent.ACTION_MOVE:
scrollViewParent.requestDisallowInterceptTouchEvent(true);
return false;
default:
return true;
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
@Override
public void onMapReady(GoogleMap googleMap) {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mUiSettings = map.getUiSettings();
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
}
class PostAddTask extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
@Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(AddPostActivity.this, "Loading...");
}
@Override
protected Void doInBackground(Void... arg0) {
jsonStr = uploadFile();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
cd.dismissdialog();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String responce = jsonObj.getString(Constants.LOGIN_TAG);
String msg = jsonObj.getString(Constants.REG_TAG);
Toast.makeText(AddPostActivity.this, "successfully Ad posted",Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
Intent intent = new Intent(AddPostActivity.this,MainActivity.class);
startActivity(intent);
}
}
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.WEBURL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
}
});
if(selectedImagePath1.length()>0){
File file = new File(selectedImagePath1);
entity.addPart("images[]", new FileBody(file));
}
if(selectedImagePath2.length()>0){
File file = new File(selectedImagePath2);
entity.addPart("images[]", new FileBody(file));
}
if(selectedImagePath2.length()>0){
File file = new File(selectedImagePath2);
entity.addPart("images[]", new FileBody(file));
}
entity.addPart("action", new StringBody("postAd"));
entity.addPart("advertId", new StringBody(advertId));
entity.addPart("categoryId", new StringBody(String.valueOf(categoryId)));
entity.addPart("title", new StringBody(strtitle));
entity.addPart("prize", new StringBody(strprice));
entity.addPart("city",new StringBody(strCity));
entity.addPart("desc", new StringBody(strdescription));
entity.addPart("address", new StringBody(straddress));
entity.addPart("contact",new StringBody(strcontact));
entity.addPart("latlong", new StringBody(String.valueOf(lat)+","+String.valueOf(lng)));
entity.addPart("info",new StringBody("Hellooo"));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
Log.e("PostAd", "Response:"+responseString);
} else {
responseString = "Error occurred! Http Status Code: "+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class GetCategoryList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
JSONObject jsonObj = null;
CustomProgressDialog cd = new CustomProgressDialog();
@Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(AddPostActivity.this, "Loading.....");
}
@Override
protected Void doInBackground(Void... arg0) {
jsonObj = new GetJSONObject().getJSONfromURL(Constants.CAT_URL);
Log.d("Response: ", "> " + jsonStr);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
cd.dismissdialog();
if (jsonObj != null) {
try {
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(Constants.CAT_ID);
String name = c.getString(Constants.CAT_NAME);
CatItem v=new CatItem();
v.setId(Integer.parseInt(id));
v.setName(name);
cateList.add(v);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CateSpinnerAdapter(AddPostActivity.this, cateList,typeface);
spiCategory.setAdapter(adapter);
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode == Activity.RESULT_OK) {
if(requestCode == PICK_IMAGE1 || requestCode == CAPTURE_IMAGE1){
if (requestCode == PICK_IMAGE1) {
selectedImagePath1 = getAbsolutePath(data.getData());
ImageView img=(ImageView)imageView;
img.setImageBitmap(decodeFile(selectedImagePath1));
} else if (requestCode == CAPTURE_IMAGE1) {
selectedImagePath1 = getImagePath();
ImageView img=(ImageView)imageView;
img.setImageBitmap(decodeFile(selectedImagePath1));
}
}else if(requestCode == PICK_IMAGE2 || requestCode == CAPTURE_IMAGE2){
if (requestCode == PICK_IMAGE2) {
selectedImagePath2 = getAbsolutePath(data.getData());
ImageView img=(ImageView)imageView;
img.setImageBitmap(decodeFile(selectedImagePath2));
} else if (requestCode == CAPTURE_IMAGE2) {
selectedImagePath2 = getImagePath();
ImageView img=(ImageView)imageView;
img.setImageBitmap(decodeFile(selectedImagePath2));
}
}else if(requestCode == PICK_IMAGE3 || requestCode == CAPTURE_IMAGE3){
if (requestCode == PICK_IMAGE3) {
selectedImagePath3 = getAbsolutePath(data.getData());
ImageView img=(ImageView)imageView;
img.setImageBitmap(decodeFile(selectedImagePath3));
} else if (requestCode == CAPTURE_IMAGE3) {
selectedImagePath3 = getImagePath();
ImageView img=(ImageView)imageView;
img.setImageBitmap(decodeFile(selectedImagePath3));
}
}
super.onActivityResult(requestCode, resultCode,data);
}
}
private void startDialog(final int imageid)
{
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Upload Pictures Option");
builder.setMessage("How do you want to set your picture?");
builder.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
if(imageid == 1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE1);
}else if(imageid == 2){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""),PICK_IMAGE2);
}else if(imageid == 3){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""),PICK_IMAGE3);
}
}
});
builder.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i)
{
if(imageid == 1) {
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE1);
}else if(imageid ==2){
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE2);
}else if(imageid == 3){
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE3);
}
}
});
builder.show();
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
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 while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String>
{
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
@Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
places = parser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
@Override
protected void onPostExecute(List<HashMap<String,String>> list){
map.clear();
for(int i=0;i<list.size();i++){
HashMap<String, String> hmPlace = list.get(i);
lat = Double.parseDouble(hmPlace.get("lat"));
lng = Double.parseDouble(hmPlace.get("lng"));
String name = hmPlace.get("formatted_address");
LatLng l1 = new LatLng(lat,lng);
MarkerOptions options = new MarkerOptions();
options.position(l1);
options.title(name);
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
map.addMarker(options);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(l1, 10));
}
}
}
}
答案 0 :(得分:0)
您的地图实例为空,当您收到回调时,您有nullpointerexception。
尝试做下一步
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
....
}