This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm building a map on my app and everything works fine until I add my ClusterItem to my ClusterManager throwing the exception:
Attempt to read from field 'double com.google.android.gms.maps.model.LatLng.longitude' on a null object reference
public class MapaActivity extends FragmentActivity implements OnMapReadyCallback {
BancoDadosController bancoDadosController;
private List<Obra> listaPlot;
private String numObra, numeroObra, tipoObra, descricao;
private double latitude;
private double longitude;
private String geoPonto;
private GoogleMap gMap;
private LatLng pontoFinal;
private ClusterManager<ItemCluster> mClusterManager;
private ItemCluster itemCluster;
private SharedPreferences pegaIdJurisdicionado;
private static final String USER_AUTH = "Autentication";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
bancoDadosController = new BancoDadosController(this);
pegaIdJurisdicionado = getSharedPreferences(USER_AUTH,0);
String idJurisdicionado = pegaIdJurisdicionado.getString("idJurisdicionado", null);
listaPlot = bancoDadosController.buscarListaMapa("3", "5527");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapaDespesa);
mapFragment.getMapAsync(this);
}
private void setUpClusterer(GoogleMap googleMap) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-7.116289, -34.850414), 4.5f));
mClusterManager = new ClusterManager<ItemCluster>(this, googleMap);
mClusterManager.setRenderer(new IconePersonalizado(MapaActivity.this, googleMap,mClusterManager));
final IconePersonalizado iconePersonalizado = new IconePersonalizado(this,gMap,mClusterManager);
mClusterManager.setRenderer(iconePersonalizado);
mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(new InfoWindowMapa(LayoutInflater.from(this)));
gMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
googleMap.setOnCameraIdleListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
googleMap.setOnInfoWindowClickListener(mClusterManager);
addItemsCluster();
}
private void addItemsCluster() {
for (int i = 0; i < listaPlot.size(); i++) {
geoPonto = listaPlot.get(i).getGeoReferenciamento();
pontoFinal = tratamentoGeoPonto(geoPonto);
numObra = listaPlot.get(i).getNumeroObra();
tipoObra = listaPlot.get(i).getTipoObra();
descricao = listaPlot.get(i).getDescricaoObra();
itemCluster = new ItemCluster(pontoFinal, numObra, tipoObra, descricao);
try{
mClusterManager.addItem(itemCluster);
}catch (NullPointerException e){
Log.d("Andre", String.valueOf(itemCluster.getPosition()));
e.printStackTrace();
}
}
}
private LatLng tratamentoGeoPonto(String valor){
String geoPontoFormatado = "";
geoPontoFormatado = valor.substring(1, (valor.length()-1));
String[] pontos = geoPontoFormatado.split(",");
double lat = Double.parseDouble(pontos[0]);
double lngt = Double.parseDouble(pontos[1]);
LatLng pontoTratado = new LatLng(lat, lngt);
return pontoTratado;
}
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.getUiSettings().setRotateGesturesEnabled(false);
gMap.getUiSettings().setZoomControlsEnabled(true);
setUpClusterer(gMap);
mClusterManager.setOnClusterItemInfoWindowClickListener(new ClusterManager.OnClusterItemInfoWindowClickListener<ItemCluster>() {
#Override
public void onClusterItemInfoWindowClick(ItemCluster itemCluster) {
numeroObra = itemCluster.getNumeroObra();
Intent passarObra = new Intent(MapaActivity.this,CardObraActivity.class);
passarObra.putExtra("obraDigitada",numeroObra);
startActivity(passarObra);
}
});
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<ItemCluster>() {
#Override
public boolean onClusterItemClick(ItemCluster itemCluster) {
return false;
}
});
mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<ItemCluster>() {
#Override
public boolean onClusterClick(Cluster<ItemCluster> cluster) {
float teste = gMap.getCameraPosition().zoom;
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(teste+6).build();
gMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
return false;
}
});
}
}
And here is my ClusterItem class:
public class ItemCluster implements ClusterItem{
private LatLng mPosition;
private String numeroObra;
private String descricao;
private String tipoObra;
public ItemCluster(LatLng mPosition, String numeroObra, String descricao, String tipoObra) {
this.mPosition = mPosition;
this.numeroObra = numeroObra;
this.descricao = descricao;
this.tipoObra = tipoObra;
}
public LatLng getmPosition() {
return mPosition;
}
public String getNumeroObra() {
return numeroObra;
}
public String getDescricao() {
return descricao;
}
public String getTipoObra() {
return tipoObra;
}
#Override
public LatLng getPosition() {
return null;
}
#Override
public String getTitle() {
return null;
}
#Override
public String getSnippet() {
return null;
}
}
all my variables have values and it's all ok until reach on this function
private void addItemsCluster() {
for (int i = 0; i < listaPlot.size(); i++) {
geoPonto = listaPlot.get(i).getGeoReferenciamento();
pontoFinal = tratamentoGeoPonto(geoPonto);
numObra = listaPlot.get(i).getNumeroObra();
tipoObra = listaPlot.get(i).getTipoObra();
descricao = listaPlot.get(i).getDescricaoObra();
itemCluster = new ItemCluster(pontoFinal, numObra, tipoObra, descricao);
try{
mClusterManager.addItem(itemCluster);
}catch (NullPointerException e){
Log.d("Andre", String.valueOf(itemCluster.getPosition()));
e.printStackTrace();
}
}
}
And that's my Select function to return my list to plot the map
public List<Obra> buscarListaMapa(String tipoGeoReferenciamentoFiltro, String idJurisdicionadoFiltro) {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + BancoDadosHelper.TABELA_OBRA + " WHERE "+ BancoDadosHelper.COLUNA_ID_TIPO_GEOREFERENCIAMENTO + " = '"+tipoGeoReferenciamentoFiltro+"' and "+
BancoDadosHelper.COLUNA_ID_JURISDICIONADO+" = '"+idJurisdicionadoFiltro+"'", null);
List<Obra> listaMapa = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
String numObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_NUM_OBRA));
String descObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_DESCRICAO_OBRA));
String geoReferenciamento = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_GEOREFERENCIAMENTO));
String tipoObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_TIPO_OBRA));
Obra novaObra = new Obra(numObra, descObra, tipoObra, geoReferenciamento);
listaMapa.add(novaObra);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return listaMapa;
}
The problem may be in your ItemCluster.class, In your case getPosition() returns null.
#Override
public LatLng getPosition() {
return new LatLng(getSLatitude(), getSLongitude());
}
Related
I am using jd-alexander/LikeButton https://github.com/jd-alexander/LikeButton instead of normal buttons in the android app. The code works fine while enabling and disabling switches. But I want to save the state of the like button. Suppose I enable the like button and swap the list the background code will run fine but the like button state will change to unliked.
Every time when I swap the list the like button state becomes unliked. Is there any way to save the like button State??
Activity codes:
public class CollectorListAdapter extends ArrayAdapter<Collector> {
private static final String TAG = "CollectorListAdapter";
private Context mContext;
private int mResource;
public CollectorListAdapter(Context context, int resource, ArrayList<Collector> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
public View getView(final int position, View convertView, ViewGroup parent) {
//Get the Shop information
String Shopname = getItem(position).getName();
String Specialoffers = getItem(position).getSpecialoffers();
int Price = getItem(position).getPrice();
final Double startLatitude = getItem(position).getLatitude();
final Double startLongitude = getItem(position).getLongitude();
final String user_id = String.valueOf(getItem(position).getUserid());
final String shop_id = String.valueOf(getItem(position).getShopid());
final String product_id = String.valueOf(getItem(position).getProductid());
//create the view result for showing the animation
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView sname = (TextView) convertView.findViewById(R.id.textView);
TextView tvname = (TextView) convertView.findViewById(R.id.textView7);
TextView Location = (TextView) convertView.findViewById(R.id.textView9);
TextView tvdescription = (TextView) convertView.findViewById(R.id.textView10);
sname.setText(Shopname);
tvdescription.setText(Specialoffers);
tvname.setText(CurrencyFormatting(Integer.toString(Price)) + " EGP");
Location.setText(format(results[0]) + " km");
LikeButton heart;
heart = convertView.findViewById(R.id.favBtn);
heart.setOnLikeListener(new OnLikeListener() {
// Add Data to the Saved Shop Table by like
#Override
public void liked(LikeButton likeButton) {
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq);
Toast.makeText(getContext(),
"Shop Saved Successfully", Toast.LENGTH_LONG).show();
}
// Delete Data to the Saved Shop Table by Unlike
#Override
public void unLiked(LikeButton likeButton) {
StringRequest strReq10 = new StringRequest(Request.Method.POST, AppConfig.URL_Delete_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq10);
Toast.makeText(getContext(),
"Shop Saved Deleted Successfully", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Collector Class:
public class Collector implements java.io.Serializable {
private String specialoffers, name;
private Double latitude, longitude;
private int price,userid,shopid,productid;
public Collector() {
}
//Sorting by Price method
public static Comparator<Collector> PriceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
int rollno1 = s1.getPrice();
int rollno2 = s2.getPrice();
/*For ascending order*/
return rollno1 - rollno2;
/*For descending order*/
//rollno2-rollno1;
}
};
//Sorting by Distance method
public static Comparator<Collector> DistanceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
float[] results1 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s1.getLatitude(),
s1.getLongitude(),
results1);
float[] results2 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s2.getLatitude(),
s2.getLongitude(),
results2);
/*For ascending order*/
return Float.compare(results1[0], results2[0]);
/*For descending order*/
//rollno2-rollno1;
}
};
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getShopid() {
return shopid;
}
public void setShopid(int shopid) {
this.shopid = shopid;
}
public int getProductid() {
return productid;
}
public void setProductid(int productid) {
this.productid = productid;
}
public String toString() {
return ("Shop Name:" + getName() +
" Price : " + getPrice() +
" SpecialOffers : " + getSpecialoffers() +
" latitude : " + getLatitude()) +
" longitude : " + getLongitude();
}
public String getSpecialoffers() {
return specialoffers;
}
public void setSpecialoffers(String specialoffers) {
this.specialoffers = specialoffers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
This is the normal behaviour in ArrayAdapter, the whole list gets recreated again so you lose the state of the button. You should save the boolean of the button in the local list variable.
Add a field like isLiked = true/false in the Collector class and update the value at the particular position every time user click like/unlike buttons.
Trying to convert JSON array to list of objects using Gson library.
Code:
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {}; //this line throws the following exception
public class Comment implements Serializable{
#SerializedName("id")
private int mID;
#SerializedName("content")
private String mContent;
#SerializedName("author")
private String mAuthor;
#SerializedName("author_id")
private int mAuthorID;
#SerializedName("author_email")
private String mAuthorEmail;
#SerializedName("date")
private String mDate;
#SerializedName("name")
private String mName;
#SerializedName("image")
private String mImage;
public int getmID() {
return mID;
}
public void setmID(int mID) {
this.mID = mID;
}
public String getmContent() {
return mContent;
}
public void setmContent(String mContent) {
this.mContent = mContent;
}
public String getmAuthor() {
return mAuthor;
}
public void setmAuthor(String mAuthor) {
this.mAuthor = mAuthor;
}
public int getmAuthorID() {
return mAuthorID;
}
public void setmAuthorID(int mAuthorID) {
this.mAuthorID = mAuthorID;
}
public String getmAuthorEmail() {
return mAuthorEmail;
}
public void setmAuthorEmail(String mAuthorEmail) {
this.mAuthorEmail = mAuthorEmail;
}
public String getmDate() {
return mDate;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmImage() {
return mImage;
}
public void setmImage(String mImage) {
this.mImage = mImage;
}
}
public class CommentListingActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "CommentListingActivity";
private ListView mListViewComments;
private CommentAdapter mCommentAdapter;
private ArrayList<Comment> mCommentList = new ArrayList<Comment>();
private ProgressBar mProgressBar;
private TextView mTextViewErrorMessage;
private Button mButtonRefresh;
private LinearLayout mLinearLayoutError;
private int mPostID;
private boolean isCommentListLoading = true;
private EditText mEditTextComment;
private ImageView mImageViewSend;
private InputMethodManager mInputMethodManager;
private SwipeRefreshLayout mSwipeRefreshLayout;
private boolean mIsRefreshing = false;
private int mOffset = 0;
private View mProgressBarView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_listing);
mPostID = getIntent().getIntExtra("postID",0);
setToolbar();
setToolBarTitle(getString(R.string.commentsLabel));
setToolbarHomeAsUpEnabled(true);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
mIsRefreshing = true;
mOffset = 0;
fetchComments();
}
});
mListViewComments = (ListView) findViewById(R.id.listViewComments);
mCommentAdapter = new CommentAdapter(this, mCommentList,mImageLoader);
mListViewComments.setAdapter(mCommentAdapter);
mProgressBarView = getLayoutInflater().inflate(R.layout.recyclerview_loading_item,null);
mListViewComments.addFooterView(mProgressBarView);
// set the custom dialog components - text, image and button
mEditTextComment = (EditText) findViewById(R.id.editTextComment);
mImageViewSend = (ImageView) findViewById(R.id.imageViewSend);
mImageViewSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postComment();
}
});
mEditTextComment.requestFocus();
mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
initProgressBar();
initErrorView();
mListViewComments.setOnScrollListener(new EndlessScrollListener() {
#Override
public boolean onLoadMore(int page, int totalItemsCount) {
mOffset = mOffset + LIST_LIMIT;
mListViewComments.addFooterView(mProgressBarView);
fetchComments();
return true;
}
});
fetchComments();
}
private void fetchComments(){
if (!mIsRefreshing && mCommentAdapter.getCount()==0)
showProgressBar();
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("post",String.valueOf(mPostID));
parameters.put("offset",String.valueOf(mOffset));
NetworkUtility.getJSONRquest(this, APIURLs.LIST_COMMENTS, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Remove loading item
if(mCommentList.size()>0) {
mListViewComments.removeFooterView(mProgressBarView);
}
try {
if(response.getString(API_KEY_STATUS).equalsIgnoreCase(API_RESPONSE_SUCCESS)){
JSONArray jsonArrayComments = response.getJSONArray(API_KEY_DATA);
if(jsonArrayComments.length()>0) {
if (mIsRefreshing) {
mCommentList.clear();
mCommentAdapter.notifyDataSetChanged();
}
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
mCommentList.addAll((Collection<? extends Comment>) GsonUtility.convertJSONStringToObject(jsonArrayComments.toString(), token));
mCommentAdapter.notifyDataSetChanged();
}
mIsRefreshing = false;
if(mCommentAdapter.getCount()>0) {
showContent();
} else {
if (mOffset == 0)
showError("No comments found.");
}
} else {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),response.getString(API_KEY_MESSAGE),getString(R.string.okLabel),null,null,null);
} else
showError(response.getString(API_KEY_MESSAGE));
}
} catch (JSONException e) {
e.printStackTrace();
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(getString(R.string.volleyErrorMessage));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressBarView.setVisibility(View.GONE);
if(mCommentAdapter.getCount()>0){
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),getString(R.string.volleyErrorMessage),getString(R.string.okLabel),null,null,null);
} else {
showError(error.getCause().getMessage());
}
error.printStackTrace();
}
},null,TAG);
}
private void postComment() {
final AppProgressDialog appProgressDialog = new AppProgressDialog(this);
appProgressDialog.setProgressDialogTitle("Posting Comment");
appProgressDialog.setProgressDialogMessage("Please Wait...");
appProgressDialog.showProgressDialog();
try {
final String comment = mEditTextComment.getText().toString();
if (!ValidatorUtility.isBlank(comment) && mPostID!=0) {
JSONObject jsonData = new JSONObject();
jsonData.put("content",comment);
jsonData.put("post",mPostID);
NetworkUtility.postRquestWithBasicAuth(this, APIURLs.POST_COMMENT, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.has("id") && response.getInt("id")>0){
AppToast.toastLong(mContext,"Comment Added");
Comment objComment = new Comment();
if (response.has("author_name"))
objComment.setmAuthor(response.getString("author_name"));
if (response.has("author_email"))
objComment.setmAuthorEmail(response.getString("author_email"));
if (response.has("author"))
objComment.setmAuthorID(response.getInt("author"));
objComment.setmContent(comment);
if (response.has("date"))
objComment.setmDate(response.getString("date"));
if (response.has("id"))
objComment.setmID(response.getInt("id"));
objComment.setmImage(mUser.getImage());
objComment.setmName(mUser.getName());
mCommentList.add(0,objComment);
mCommentAdapter.notifyDataSetChanged();
mEditTextComment.setText(null);
mEditTextComment.clearFocus();
mInputMethodManager.hideSoftInputFromWindow(mEditTextComment.getWindowToken(),0);
showContent();
} else {
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),"Failed to add comment. Please try again later.",getString(R.string.okLabel),null,null,null);
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
appProgressDialog.dismissProgressDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
appProgressDialog.dismissProgressDialog();
AlertDialogUtility.showErrorMessage(CommentListingActivity.this,getString(R.string.errorLabel),error.getCause().getMessage(),getString(R.string.okLabel),null,null,null);
}
}, jsonData, TAG);
} else {
appProgressDialog.dismissProgressDialog();
}
} catch (Exception e){
e.printStackTrace();
appProgressDialog.dismissProgressDialog();
}
}
private void initProgressBar(){
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
}
private void initErrorView(){
mLinearLayoutError = (LinearLayout) findViewById(R.id.linearLayoutError);
mTextViewErrorMessage = (TextView) findViewById(R.id.textViewErrorMessage);
mButtonRefresh = (Button) findViewById(R.id.buttonRefresh);
mButtonRefresh.setOnClickListener(this);
}
private void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.GONE);
}
private void showContent(){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.GONE);
mSwipeRefreshLayout.setVisibility(View.VISIBLE);
}
private void showError(String message){
mProgressBar.setVisibility(View.GONE);
mLinearLayoutError.setVisibility(View.VISIBLE);
mSwipeRefreshLayout.setVisibility(View.GONE);
mTextViewErrorMessage.setText(message);
}
#Override
public void onClick(View view) {
if(view == mButtonRefresh){
fetchComments();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
KeyboardUtility.closeKeyboard(this,mEditTextComment);
}
}
Exception:
Method threw 'java.lang.NullPointerException' exception. Cannot evaluate app.govindaconnect.mangaltaraproductions.com.views.CommentListingActivity$4$1.toString()
Only 1 JSON objects get converted and added to the list.
What might be causing the exception? Because this is not happening with other classes.
You can try this
replace this line
TypeToken<List<Comment>> token = new TypeToken<List<Comment>>() {};
with this and try
Type token = new TypeToken<List<Comment>>() {}.getType();
List<Comment> commentsList = gson.fromJson(String.valueOf(resultArray), type);
I took JSON array in a string variable and then it started working.
why don't you try Jackson parser for conversion, it's much simpler and easier
example for you :
List<Comment> list=null;
String json="your json array";
ObjectMapper mapper = new ObjectMapper();
try {
list= mapper.readValue(json, new TypeReference<List<Comment>>(){});
} catch (IOException e) {
throw new Exception(e);
}
I am now working on a online rent car finder apk. I want this program TO fetch database from server and sort it based on the location (distance from user current location of rent car garage).
But i am confuse here on how to sort the list view base on the distance ? I mean, i know how to calculate the distance but i am blank about how to get the user's current latitude and longitude inside an Activity without opening mapActivity?
This my condition right now :
1. My result list is inside ResultListFragment.java and my google map activity is on MapActivity.java.
2. I have to try and get the longitude,latitude using getLatitude and getLongitude method which i create on MapActivity.java, but it just returning zero (not null).
3. I tried to separate the gps listener on GPStracker class, but still it doesn't work.
Please help me, how do i get the latitude and longitude of the current user position.
NB. This is my ResultListFragment.java
public class ResultListFragment extends Fragment implements InternetConnectionListener,
LocationChangeListener {
public static String catId;
public static String titleId;
public static String searchTerm;
public static LocationChangeListener locationChangeListener;
private final int RESULT_ACTION = 1;
private final int RESULT_LIMIT = 100;
private ArrayList<Item> searchResultList;
private ResultListCallbacks mCallbacks;
private InternetConnectionListener internetConnectionListener;
private ArrayList<Item> resultList;
private ListView resultListView;
private LatLng itemLocation;
GPSTrackStandAlone gTrack = new GPSTrackStandAlone(getContext());
MapActivity mAct = new MapActivity();
public HomeActivity hAct = new HomeActivity();
public ResultListFragment() {
}
public static ResultListFragment newInstance(String id, String title) {
ResultListFragment fragment = new ResultListFragment();
catId = id;
titleId = title;
searchTerm = "";
locationChangeListener = fragment;
return fragment;
}
public static ResultListFragment newInstance(String id, String title,String term) {
ResultListFragment fragment = new ResultListFragment();
catId = id;
titleId = title;
searchTerm = term;
locationChangeListener = fragment;
return fragment;
}
public void getGPSLoc(){
double latitude = mAct.getLatitudeSend();
double longitude = mAct.getLongitudeSend();
Log.d("LatitudeCurrGPSLoc",String.valueOf(latitude));
Log.d("LongCur",String.valueOf(longitude));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (ResultListCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement ResultListCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_result_list, container, false);
resultListView = (ListView) rootView.findViewById(R.id.resultListView);
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onResume() {
super.onResume();
isHomeOpened = false;
isResultListFragmentOpened = true;
if (UtilMethods.isConnectedToInternet(getActivity())) {
if (!TextUtils.isEmpty(catId))
initResultList();
else if (!TextUtils.isEmpty(searchTerm))
getSearchResults(searchTerm);
} else {
internetConnectionListener = (InternetConnectionListener) ResultListFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener, getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), RESULT_ACTION);
}
}
private void initResultList() {
Log.d("Pembuktian", catId);
if(Integer.parseInt(catId)>100 && Integer.parseInt(catId)<200 ){
new getCarRent().execute();
}else if(Integer.parseInt(catId)>199 && Integer.parseInt(catId)<300){
new getCarBrand().execute();
}else if(Integer.parseInt(catId)>299 && Integer.parseInt(catId)<400){
new getCarType().execute();
}
/**
* json is populating from text file. To make api call use ApiHandler class
* pass parameter using ContentValues (values)
*
* <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_RESULT_LIST_WITH_AD, values);</CODE> <BR>
* <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done.
*/
// String jsonString = loadJSONFromAsset(getActivity(), "get_result_list");
//parseJson(jsonString);
}
private void getSearchResults(String query) {
/**
* json is populating from text file. To make api call use ApiHandler class
* pass parameter using ContentValues (values)
*
* <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_SEARCH_LIST_AD, values);</CODE> <BR>
* <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done.
*/
String jsonString = loadJSONFromAsset(getActivity(), "get_search_list");
parseJson(jsonString);
}
public class getCarRent extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
URL hp = null;
try {
hp = new URL(getString(R.string.liveurl)
+ "getCarRent.php?value=" + catId);
// hp = new URL(
// "http://192.168.1.106/restourant/foodtype.php?value="
// + id);
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
Log.d("input", "" + input);
BufferedReader r = new BufferedReader(new InputStreamReader(
input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("URL", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
Item[] itemList = new Item[j.length()];
resultList = new ArrayList<Item>();
for (int i = 0; i < j.length(); i++) {
Item item = new Item();// buat variabel category
//JSONObject Obj;
JSONObject Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
item.setId(Obj.getString(JF_ID));
//item.setTitle(Obj.getString(JF_TITLE));
item.setAddress(Obj.getString(JF_ADDRESS));
item.setTelephoneNumber(Obj.optString(JF_TELEPHONE, NO_DATA_FOUND));
item.setEmailAddress(Obj.optString(JF_EMAIL, NO_DATA_FOUND));
item.setWebUrl(Obj.optString(JF_WEB, NO_DATA_FOUND));
item.setFacebookUrl(Obj.optString(JF_FACEBOOK, NO_DATA_FOUND));
item.setLatitude(Obj.optDouble(JF_LATITUDE, NULL_LOCATION));
item.setLongitude(Obj.optDouble(JF_LONGITUDE, NULL_LOCATION));
try {
item.setRating(Float.parseFloat(Obj.optString(JF_RATING, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRating(0.0f);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATING_COUNT, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATINGSCORE, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
item.setTagLine(Obj.optString(JF_TAG_LINE, NO_DATA_FOUND));
item.setDescription(Obj.optString(JF_DESCRIPTION, NO_DATA_FOUND));
item.setVerification(Obj.optString(JF_VERIFICATION, NO_DATA_FOUND).equals("1") ? true : false);
item.setCarId(Obj.optString(JF_CARID, NO_DATA_FOUND));
item.setTitle(Obj.optString(JF_CARTITLE, NO_DATA_FOUND));
item.setCarRentalId(Obj.optString(JF_CARRENTALID, NO_DATA_FOUND));
item.setCarPrice(Obj.optString(JF_CARPRICE, NO_DATA_FOUND));
item.setCarYear(Obj.optString(JF_CARYEAR, NO_DATA_FOUND));
JSONArray imgArr = Obj.getJSONArray("thumbImage");
String[] imageThumb = new String[imgArr.length()];
// String[] imageLarge = new String[imgArr.length()];
for (int k = 0; k < imgArr.length(); k++) {
imageThumb[k] = imgArr.getString(k);
// imageLarge[k] = imgArr.getJSONObject(k).getString(JF_TITLE);
}
for(int l = 0; l <imgArr.length(); l++) {
item.setImageLargeUrls(imageThumb);
}
item.setImageThumbUrls(imageThumb);
// item.setImageLargeUrls(imageLarge);
// JSONArray imgArr = Obj.getJSONArray("thumbImage");
/*String[] imgCount = new String[imgArr.length()];
for(int k = 0 ; k < imgCount.length; k++) {
imgCount[k] = imgArr.getString(k);
item.setImageThumbUrls(imgCount);
}*/
Location trgtLocation = new Location("trgtLocation");
trgtLocation.setLatitude(item.getLatitude());
trgtLocation.setLongitude(item.getLongitude());
Location crntLocation = new Location("crntlocation");
crntLocation.setLatitude(gTrack.getLatitude());
crntLocation.setLongitude(gTrack.getLongitude());
Log.d("latitudeCurr", String.valueOf(gTrack.getLatitude()));
Log.d("curLocLong", String.valueOf(gTrack.getLongitude()));
//LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
item.setDistance(crntLocation.distanceTo(trgtLocation) / 1000);
Log.d("distance", String.valueOf(item.getDistance()));
Log.d("URL1", "" + Obj.getString(JF_TITLE));
resultList.add(item);
itemList[i]=item;
Log.d("itemList",String.valueOf(itemList[i]));
Arrays.sort(itemList, new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
return 0;
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
resultListView.setAdapter(new ResultListAdapterRental(getActivity(), mCallbacks, resultList));
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
}
return null;
}
}
I try to take the Lng and Lat from a System service like this one, but it's still doesn't work. Is this code right ?
GPSTracker.java
public class GPSTrackStandAlone extends Service implements LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Context mContext;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location mLocation;
private double mLatitude;
private double mLongitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 60000;
private LocationManager mLocationManager;
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
public GPSTrackStandAlone(Context mContext) {
this.mContext = mContext;
}
/**
* #return location
*/
public Location getLocation() {
try {
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
/*no location provider enabled*/
} else {
this.canGetLocation = true;
/*getting location from network provider*/
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_FOR_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.d("Perms", "Permission for GPS Granted");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
/*if gps is enabled then get location using gps*/
if (isGpsEnabled) {
if (mLocation == null) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_FOR_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mLocation;
}
/**
* call this function to stop using gps in your application
*/
public void stopUsingGps() {
if (mLocationManager != null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.removeUpdates(GPSTrackStandAlone.this);
}
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
Toast.makeText(GPSTrackStandAlone.this, "isGooglePlayServiceAvailable = False", Toast.LENGTH_SHORT).show();
return false;
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* #return latitude
* <p/>
* function to get latitude
*/
public double getLatitude() {
getLocation();
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* #return longitude
* function to get longitude
*/
public double getLongitude() {
getLocation();
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
Log.d("MGPS", String.valueOf(mLocation.getLatitude()));
}
return mLongitude;
}
/**
* #return to check gps or wifi is enabled or not
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Have you consider to use the Google Maps API ? With it you can simply do the following to get the user's current location :
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation();
Do you mean that you can getLng and getLat in activity ?
Try to use a public static to describe your values,and use MyActivity.value in Fragment.
when you want to pass the data from activity to fragment you should use bundle .
I will give you the example.
public class CompleteJobFragment extends Fragment {
private final static String PICKUP_TIME="pickup time";
public static CompleteJobFragment newInstance(String pickUpTime) {
CompleteJobFragment fragment = new CompleteJobFragment();
Bundle bundle = new Bundle();
bundle.putString(PICKUP_TIME, pickUpTime);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
pickUpTime = getArguments().getString(PICKUP_TIME);
}
}
Activity file
public class ActiveJobActivity extends AppCompatActivity {
String x1;
public void loadData()
{
CompleteJobFragment completeJobFragment = CompleteJobFragment.newInstance(x1);
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.activez, completeJobFragment, COMPLETE_FRAGMENT);
fragmentTransaction.addToBackStack(COMPLETE_FRAGMENT);
completeJobFragment.setCommunicator(this);
fragmentTransaction.commit();
}
I'm creating an Android map app by getting venue from Foursquare and using Google Map.
I have set my MainActivity to get the venue results, a MapFragmentClass and a VenueModel.
I keep all the JSON result from Foursquare into a List venueModelList in the MainActivity.
What I want to do is to add markers in the MapFragmentClass based on the coordinates received from Foursquare.
However, I am stuck trying to pass the venueModelList to the MapFragmentClass.
Any help is appreciated. Thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity implements LocationListener{
private final String VENUE_URL = "https://api.foursquare.com/v2/venues/search?ll=";
private final int LIMIT = 40;
private final double RADIUS = 50000;
private String MOSQUE_URL;
private String RES_URL;
public static final String CLIENT_ID = "";
public static final String CLIENT_SECRET = "";
private static final long MIN_TIME_BW_UPDATES = 20000;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private LocationManager locationManager;
private Location lastLocation;
private Location location;
private boolean receivedLocation = false;
private double lt;
private double lg;
private boolean canGetLocation;
private boolean isGPSEnabled;
private boolean isNetworkEnabled;
private boolean updateSettings = false;
private String TAG = "TAG";
private ListView lvVenues;
private Bundle bundle;
private ArrayList<VenueModel> venueModelList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvVenues = (ListView) findViewById(R.id.lvVenues);
String t = timeMilisToString(System.currentTimeMillis());
Bundle extras = getIntent().getExtras();
if (extras != null)
{
lt = extras.getDouble("LATITUDE");
lg = extras.getDouble("LONGITUDE");
receivedLocation = true;
}
else
{
receivedLocation = false;
}
location = getLocation();
if (location != null)
{
if(receivedLocation)
{
location.setLatitude(lt);
location.setLongitude(lg);
}
else
{
lt = location.getLatitude();
lg = location.getLongitude();
Log.d("LAT", "Latitude: " + lt);
Log.d("LONG", "Longitude: " + lg);
}
}
double lt = 3.142182;
double lg = 101.710602;
MOSQUE_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=4bf58dd8d48988d138941735"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
RES_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=52e81612bcbc57f1066b79ff"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
}
public class JSONTask extends AsyncTask<String, String, List<VenueModel>>
{
#Override
public List<VenueModel> doInBackground(String... params)
{
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondObject = parentObject.getJSONObject("response");
JSONArray parentArray = secondObject.getJSONArray("venues");
venueModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++)
{
JSONObject finalObject = parentArray.getJSONObject(i);
JSONObject thirdObject = finalObject.getJSONObject("location");
try {
VenueModel venueModel = new VenueModel();
venueModel.setId(finalObject.getString("id"));
venueModel.setName(finalObject.getString("name"));
venueModel.setAddress(thirdObject.optString("address"));
venueModel.setPostalCode(thirdObject.optString("postalCode"));
venueModel.setCity(thirdObject.optString("city"));
venueModel.setState(thirdObject.optString("state"));
venueModel.setDistance(thirdObject.getInt("distance"));
venueModel.setLat(thirdObject.getDouble("lat"));
venueModel.setLng(thirdObject.getDouble("lng"));
LatLng coordinate = new LatLng(thirdObject.getDouble("lat"), thirdObject.getDouble("lng"));
venueModel.setCoordinate(coordinate);
venueModelList.add(venueModel);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Collections.sort(venueModelList);
return venueModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<VenueModel> result)
{
super.onPostExecute(result);
VenueAdapter adapter = new VenueAdapter(getApplicationContext(), R.layout.row, result);
lvVenues.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_mosque)
{
new JSONTask().execute(MOSQUE_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
if (id == R.id.action_restaurant)
{
new JSONTask().execute(RES_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
private String timeMilisToString(long milis)
{
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public Location getLocation()
{
try
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
Log.v(TAG, "No network provider enabled");
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "Network Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "GPS Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider)
{
Log.v(TAG, "onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider)
{
Log.v(TAG, "onProviderDisabled");
}
public LatLng setCoordinate()
{
LatLng coordinate = new LatLng(getLocation().getLatitude(), getLocation().getLongitude());
LatLng coordinate = new LatLng(lt, lg);
return coordinate;
}
}
VenueModel.java
public class VenueModel implements Comparable<VenueModel>, Parcelable
{
private String id;
private String name;
private String address;
private String postalCode;
private String city;
private String state;
private Integer distance;
private double lat;
private double lng;
private LatLng coordinate;
private List<VenueModel> venueModelList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public void setVenueModelList(List<VenueModel> venueModelList)
{
this.venueModelList = venueModelList;
}
public List<VenueModel> getVenueModelList()
{
return venueModelList;
}
public LatLng getCoordinate() {
return coordinate;
}
public void setCoordinate(LatLng coordinate)
{
this.coordinate = coordinate;
}
#Override
public int compareTo(VenueModel venueModel) {
return this.distance.compareTo(venueModel.distance);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeString(this.address);
dest.writeString(this.postalCode);
dest.writeString(this.city);
dest.writeString(this.state);
dest.writeValue(this.distance);
dest.writeDouble(this.lat);
dest.writeDouble(this.lng);
dest.writeParcelable(this.coordinate, flags);
dest.writeList(this.venueModelList);
}
public VenueModel() {
}
protected VenueModel(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.address = in.readString();
this.postalCode = in.readString();
this.city = in.readString();
this.state = in.readString();
this.distance = (Integer) in.readValue(Integer.class.getClassLoader());
this.lat = in.readDouble();
this.lng = in.readDouble();
this.coordinate = in.readParcelable(LatLng.class.getClassLoader());
this.venueModelList = new ArrayList<VenueModel>();
in.readList(this.venueModelList, VenueModel.class.getClassLoader());
}
public static final Parcelable.Creator<VenueModel> CREATOR = new Parcelable.Creator<VenueModel>() {
#Override
public VenueModel createFromParcel(Parcel source) {
return new VenueModel(source);
}
#Override
public VenueModel[] newArray(int size) {
return new VenueModel[size];
}
};
}
MapFragmentClass.java
public class MapFragmentClass extends Fragment implements OnMapReadyCallback
{
private MainActivity mA;
private GoogleMap gmap;
private static final LatLng coordinate = new LatLng(3.152182, 101.710602);
private LatLng coordinate2;
private ArrayList<VenueModel> venueModelList;
#Override
public void onAttach(Context context)
{
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
gmap = googleMap;
gmap.addMarker(new MarkerOptions().position(coordinate).title("Your location").draggable(true));
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 14));
}
}
Convert that Object to JSON string using GSON and then reconvert that string again to Object of list again.
MapFragment.getInstance(new Gson().toJson(venuList));
public static final getInstance(String venusStringListObj) {}
Bundle argument = new Bundle();
argument.putString("VENUES", venusStringListObj);
MapFragment fragment = new MapFragment();
fragment.setArgument(argument);
return fragment;
}
onCreate(...) {
private List<VenueModel> venueList;
Type listType = new TypeToken<ArrayList<VenueModel>>() {}.getType();
String venueStringRecvFromFragArg = getArguments().getString("VENUES");
venueList = new Gson().fromJson(venueStringRecvFromFragArg, listType);
}
MapFragmentClass mfc = new MapFragmentClass();
Bundle b = new Bundle();
b.putParcelableArrayList("Parcel", list);
mfc.setArguments(b);
FT.add(R.id.mapLayout, mfc);
FT.commit();
To access arrayList in MapFragment use this
ArrayList<VenueModel> myList = getArguments().getParcelableArrayList("Parcel");
I made a custom info window that displays 5 info (Hospital name, Address, Fax, Mobile and Landline), I successfully displayed the Hospital and Address with the use of Title and Snippet when being pressed but not with the 3 last data. some blogs says I should use Hashmap to display extra data, but I am confused with their samples.
Code for marker:
ArrayList<MapConstants> _list = new ArrayList<MapConstants>(); _list.addAll(GlobalVariablesClass.FOR_MAPMARKER);
for (int i = 0; i < _list.size(); i++) {
MarkerOptions markerOption = (new MarkerOptions().position(new LatLng(Double.valueOf(_list.get(i).getLatitude()), Double.valueOf(_list.get(i).getLongitude()))).title(bla).snippet(bla).icon(bla);
}
I solved my problem By doing this:
1st: I created a Class in which I'll get stored the return of webservice and use it for the marker. (mapConstants.Class)
MapConstants.Class:
public class MapConstants {
private String CLINIC_NAME, CLINIC_CODE, UNIT_NO
,BLDG_NAME, STREET, COUNTRY, LATITUDE, LONGITUDE, LANDLINE, MOBILE, FAX;
public MapConstants()
{
}
public MapConstants (String ClinicName, String ClinicCode, String UnitNo, String BuildingName
, String Street, String Country, String Latitude, String Longitude, String Landline, String Mobile, String Fax)
{
CLINIC_NAME = ClinicName;
CLINIC_CODE = ClinicCode;
UNIT_NO = UnitNo;
BLDG_NAME = BuildingName;
STREET = Street;
COUNTRY = Country;
LATITUDE = Latitude;
LONGITUDE = Longitude;
LANDLINE = Landline;
MOBILE = Mobile;
FAX = Fax;
}
public String setClinicName() {
return this.CLINIC_NAME;
}
public String getClinicName() {
return this.CLINIC_NAME;
}
public String setClinicCode() {
return this.CLINIC_CODE;
}
public String getClinicCode() {
return this.CLINIC_CODE;
}
public String setUnitNo() {
return this.UNIT_NO;
}
public String getUnitNo() {
return this.UNIT_NO;
}
public String setBldgName() {
return this.BLDG_NAME;
}
public String getBldgName() {
return this.BLDG_NAME;
}
public String setStreet() {
return this.STREET;
}
public String getStreet() {
return this.STREET;
}
public String setCountry() {
return this.COUNTRY;
}
public String getCountry() {
return this.COUNTRY;
}
public String setLatitude() {
return this.LATITUDE;
}
public String getLatitude() {
return this.LATITUDE;
}
public String setLongitude() {
return this.LONGITUDE;
}
public String getLongitude() {
return this.LONGITUDE;
}
public String setMobile(){
return this.MOBILE;
}
public String getMobile(){
return this.MOBILE;
}
public String setLandline(){
return this.LANDLINE;
}
public String getLandline(){
return this.LANDLINE;
}
public String setFax(){
return this.FAX;
}
public String getFax(){
return this.FAX;
}
}
2nd: On the method where you make your marker(In my case it is addmarkersToMapNew()), I made a Hashmap that will store other data you need aside from title and Snippet.
addMarkersToMapNew():
private void addMarkersToMapNew()
{
//TODO addMarkersToMapNew
int markerCount = 0;
//ProgressDialog progDailog = null;
if (ConnectionEcardMessage.isConnectingToInternet(SearchMapFragmentActivity.this))
{
ArrayList<MapConstants> _list = new ArrayList<MapConstants>();
_list.addAll(GlobalVariablesClass.FOR_MAPMARKER);
Log.i("addMarkersToMapNew-size", ""+_list.size());
Log.i("addMarkersToMapNew", "ConnectionEcardMessage.isConnectingToInternet(SearchMapFragmentActivity.this)");
if (mMapMarkers == null)
{
Log.i("addMarkersToMapNew", "null");
mMapMarkers = new HashMap<String, MarkerOptions>();
extraMarkerInfo = new ArrayList<HashMap<String, String>>();
EcardMessage.appendLog("SearchMapFrag 6.5 - get curBranchDetails");
for (int i = 0; i < _list.size(); i++)
{
HashMap<String, String> contactHashmap = new HashMap<String, String>();
Log.d("myApp", "added branch " + _list.get(i).getClinicName());
MarkerOptions markerOption = (new MarkerOptions()
.position(
new LatLng(Double.valueOf(_list.get(i).getLatitude()),
Double.valueOf(_list.get(i).getLongitude())))
.title(_list.get(i).getClinicName()) .snippet(_list.get(i).getUnitNo()+""+_list.get(i).getBldgName()+","+_list.get(i).getStreet()+", "+_list.get(i).getCountry())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.address)));
Log.i("Latitude_At_Longitude", "EDI WOW");
contactHashmap.put("landline", _list.get(i).getLandline() );
Log.i("kay landline", _list.get(i).getLandline());
contactHashmap.put("mobile", _list.get(i).getMobile() );
Log.i("kay Mobile", _list.get(i).getMobile());
contactHashmap.put("fax", _list.get(i).getFax() );
Log.i("kay Fax", _list.get(i).getFax());
contactHashmap.put("title", _list.get(i).getClinicName());
Log.i("kay title", _list.get(i).getClinicName());
extraMarkerInfo.add(contactHashmap);
mMapMarkers.put("Marker" + ++markerCount, markerOption);
mMap.addMarker(markerOption);
}
}
}
3rd: After I saved the other Data that I need to display in Hashmap(extraMarkerInfo), I can now declare my Custom Info window:
Custom Info Window:
class MyInfoWindowAdapter implements InfoWindowAdapter
{
private final View myContentsView;
MyInfoWindowAdapter(){
myContentsView = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
}
#Override
public View getInfoContents(Marker marker) {
//TODO getInfoContents
TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
// private static HashMap<String, MarkerOptions> mMapMarkers = null;
String landline = "";
String mobile = "";
String fax = "";
for (int i = 0; i < extraMarkerInfo.size(); i++) {
if (extraMarkerInfo.get(i).get("title").toString().equalsIgnoreCase(marker.getTitle()))
{
landline = extraMarkerInfo.get(i).get("landline").toString();
Log.i("get_Landline", landline);
mobile = extraMarkerInfo.get(i).get("mobile").toString();
Log.i("get_Mobile", mobile);
fax = extraMarkerInfo.get(i).get("fax").toString();
Log.i("get_Fax", fax);
}
}
TextView tvLandline = ((TextView)myContentsView.findViewById(R.id.landline_number));
tvLandline.setText(landline);
TextView tvMobile = ((TextView)myContentsView.findViewById(R.id.mobile_number));
tvMobile.setText(mobile);
TextView tvFax = ((TextView)myContentsView.findViewById(R.id.fax_number));
tvFax.setText(fax);
return myContentsView;
}
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
return null;
}
}