I am passing data with the below code:
<p:poll interval="3" listener="#{chartController.loadChartData}" oncomplete="renderChart('container','area','Sample Chart', '#{chartController.chartData}', '#{chartController.categories}');"
id="chartvalue_btn" update="textID" />
But when I checked null value is passed in JavaScript function while I checked bean variable initialized with values. Am I doing something wrong here?
ANd my bean is
package com.bchetty.charts.controller;
import com.bchetty.charts.model.Series;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
/**
* Chart Controller
*/
#ManagedBean(name="chartController")
#SessionScoped
public class ChartController {
private String chartData;
private String categories;
private List<String> categoryList = new ArrayList<String>();
private List<Long> heapSizeList = new ArrayList<Long>();
private List<Long> usedHeapSizeList = new ArrayList<Long>();
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss");//dd/MM/yyyy
private static final long MB = 1024*1024;
int index = 0;
private Long[] longs;
/**
* Load Chart Data
*/
public void loadChartData() {
if(heapSizeList.size() > 10) {
heapSizeList.remove(0);
usedHeapSizeList.remove(0);
categoryList.remove(0);
}
List<Series> series = new ArrayList<Series>();
malloc();
long heapSize = Runtime.getRuntime().maxMemory();
heapSizeList.add(heapSize/MB);
usedHeapSizeList.add((heapSize - Runtime.getRuntime().freeMemory())/MB);
series.add(new Series("Heap Size", heapSizeList));
series.add(new Series("Used Heap", usedHeapSizeList));
setChartData(new Gson().toJson(series));
categoryList.add(sdfDate.format(new Date()));
System.out.println(categoryList);
setCategories(new Gson().toJson(categoryList));
}
/**
* #return the chartData
*/
public String getChartData() {
return chartData;
}
/**
* #param chartData the chartData to set
*/
public void setChartData(String chartData) {
this.chartData = chartData;
}
/**
* #return the categories
*/
public String getCategories() {
return categories;
}
/**
* #param categories the categories to set
*/
public void setCategories(String categories) {
this.categories = categories;
}
private void malloc() {
if(index%2 == 0) {
longs = new Long[100000];
for(int i=0;i<1000;i++) {
longs[i] = Long.valueOf(i);
}
} else {
longs = null;
}
index++;
}
}
The problem is that the arguments of the oncomplete-function are only updated when the view is entered. The arguments are not automatically updated when the value of the properties on the bean have changed. So as chartController.chartData is initially not instanciated it is null when the page is rendered and remains null until you manually refresh the whole page.
To fix this issue I would recommend you to use the Primefaces RequestContext and add the chartData everytime loadChartData is called as a callback param.
I.e. add the following to the and of loadChartData:
public void loadChartData() {
...
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("chartData", chartData);
context.addCallbackParam("categories", categories);
}
And in the UI define the p:poll as follows:
<p:poll interval="3" listener="#{chartController.loadChartData}"
oncomplete="renderChart('container','area','Sample Chart', args.chartData, args.categories);"
id="chartvalue_btn" update="textID" />
If this is no option for you, because you are using loadChartData anywhere else, wrap the call of loadChartData with the addCallbackParam stuff in another method and specify this method as listener of the p:poll.
Related
I have a project on android studio and I want to drag and drop images items in RecylerView to an Container on my Activity...
In my activity I have a fragment container and this displays fragments with an RecyclerView and this display animal parts in JSON connection, it's posible to make a Drag And Drop to move images to Cointainer to make a animal character and send data to my database, and how I do it???
You have to implement ItemTouchHelper and this is an example about how to do it:
1- Add your recyclerview
<android.support.v7.widget.RecyclerView
android:id="#+id/note_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
2 - Add Model Class
public class Customer {
private Long id;
private String name;
private String emailAddress;
private int imageId;
private String imagePath;
}
3 - Add Dependencies
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.yqritc:recyclerview-flexibledivider:1.2.6'
compile 'com.google.code.gson:gson:2.3.1'
4 - Add Internet permission
<uses-permission android:name="android.permission.INTERNET" />
5- Create a new List of Customer in your Activity and add customers into it.
6- Create a new class named CustomerListAdapter
package com.okason.draganddrop;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.okason.draganddrop.listeners.OnCustomerListChangedListener;
import com.okason.draganddrop.listeners.OnStartDragListener;
import com.okason.draganddrop.utilities.ItemTouchHelperAdapter;
import com.okason.draganddrop.utilities.ItemTouchHelperViewHolder;
import com.squareup.picasso.Picasso;
import java.util.Collections;
import java.util.List;
/**
* Created by Valentine on 10/18/2015.
*/
public class CustomerListAdapter extends
RecyclerView.Adapter<CustomerListAdapter.ItemViewHolder>
implements ItemTouchHelperAdapter {
private List<Customer> mCustomers;
private Context mContext;
private OnStartDragListener mDragStartListener;
private OnCustomerListChangedListener mListChangedListener;
public CustomerListAdapter(List<Customer> customers, Context context,
OnStartDragListener dragLlistener,
OnCustomerListChangedListener listChangedListener){
mCustomers = customers;
mContext = context;
mDragStartListener = dragLlistener;
mListChangedListener = listChangedListener;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from
(parent.getContext()).inflate(R.layout.row_customer_list, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(rowView);
return viewHolder;
}
#Override
public void onBindViewHolder(final ItemViewHolder holder, int position) {
final Customer selectedCustomer = mCustomers.get(position);
holder.customerName.setText(selectedCustomer.getName());
holder.customerEmail.setText(selectedCustomer.getEmailAddress());
Picasso.with(mContext)
.load(selectedCustomer.getImagePath())
.placeholder(R.drawable.profile_icon)
.into(holder.profileImage);
holder.handleView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mDragStartListener.onStartDrag(holder);
}
return false;
}
});
}
#Override
public int getItemCount() {
return mCustomers.size();
}
#Override
public void onItemMove(int fromPosition, int toPosition) {
Collections.swap(mCustomers, fromPosition, toPosition);
mListChangedListener.onNoteListChanged(mCustomers);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public void onItemDismiss(int position) {
}
public static class ItemViewHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
public final TextView customerName, customerEmail;
public final ImageView handleView, profileImage;
public ItemViewHolder(View itemView) {
super(itemView);
customerName = (TextView)itemView.findViewById(R.id.text_view_customer_name);
customerEmail = (TextView)itemView.findViewById(R.id.text_view_customer_email);
handleView = (ImageView)itemView.findViewById(R.id.handle);
profileImage = (ImageView)itemView.findViewById(R.id.image_view_customer_head_shot);
}
#Override
public void onItemSelected() {
itemView.setBahttp://valokafor.com/wp-admin/post.php?post=1804&action=edit#ckgroundColor(Color.LTGRAY);
}
#Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
}
}
7- Implement ItemTouchHelper
In your utilities package, add ItemTouchHelperAdapter.java and below is the content:
public interface ItemTouchHelperAdapter {
/**
* Called when an item has been dragged far enough to trigger a move. This is called every time
* an item is shifted, and not at the end of a "drop" event.
*
* #param fromPosition The start position of the moved item.
* #param toPosition Then end position of the moved item.
*/
void onItemMove(int fromPosition, int toPosition);
/**
* Called when an item has been dismissed by a swipe.
*
* #param position The position of the item dismissed.
*/
void onItemDismiss(int position);
}
And in your utilities package, add ItemTouchHelperViewHolder.java and below is the content:
public interface ItemTouchHelperViewHolder {
/**
* Implementations should update the item view to indicate it's active state.
*/
void onItemSelected();
/**
* state should be cleared.
*/
void onItemClear();
}
In your utilities package, add SimpleItemTouchHelperCallback.java and here is the content:
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final ItemTouchHelperAdapter mAdapter;
public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
mAdapter = adapter;
}
#Override
public boolean isLongPressDragEnabled() {
return true;
}
#Override
public boolean isItemViewSwipeEnabled() {
return false;
}
#Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
#Override
public boolean onMove(RecyclerView recyclerView,
RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
return true;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
#Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
itemViewHolder.onItemSelected();
}
super.onSelectedChanged(viewHolder, actionState);
}
#Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
itemViewHolder.onItemClear();
}
}
Add a package called listener and add an interface called OnStartDragListener.java and here is the content:
public interface OnCustomerListChangedListener {
void onNoteListChanged(List<Customer> customers);
}
Implement Custom Row
private RecyclerView mRecyclerView;
private CustomerListAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ItemTouchHelper mItemTouchHelper;
private List<Customer> mCustomers;
After the onCreate method, add this method. And then call this method from the onCreate() method probably after the call to set Toolbar. Ignore the error warning for a minute.
private void setupRecyclerView(){
mRecyclerView = (RecyclerView) `findViewById(R.id.note_recycler_view);`
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mCustomers = SampleData.addSampleCustomers();
//setup the adapter with empty list
mAdapter = new CustomerListAdapter(mCustomers, this, this, this);
ItemTouchHelper.Callback callback = new `SimpleItemTouchHelperCallback(mAdapter);`
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(mRecyclerView);
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
.colorResId(R.color.colorPrimaryDark)
.size(2)
.build());
mRecyclerView.setAdapter(mAdapter);
}
Update the signature of your MainActivity to implement the two listeners that we added like below and use Android Studio quick fix to implement the methods.
public class MainActivity extends AppCompatActivity
implements OnCustomerListChangedListener,
OnStartDragListener{
Here is the implementation of one of the methods, and we will implement the other one in the next section.
#Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
mItemTouchHelper.startDrag(viewHolder);
}
At this point, your drag and drop list should be working and we now want to remember the position of the list items after they have been re-organized. Like I mentioned at the beginning of the post, this is accomplished by saving the ids of the list items to SharedPreference so go ahead and add the following class members to the top of the file.
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
public static final String LIST_OF_SORTED_DATA_ID = "json_list_sorted_data_id";
public final static String PREFERENCE_FILE = "preference_file";
And in the onCreate() instantiate the SharedPreference like so:
mSharedPreferences = this.getApplicationContext()
.getSharedPreferences(PREFERENCE_FILE, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
Then go ahead and implement the other method that listens for when the list changes and here is the implementation of that method:
#Override
public void onNoteListChanged(List<Customer> customers) {
//after drag and drop operation, the new list of Customers is passed in here
//create a List of Long to hold the Ids of the
//Customers in the List
List<Long> listOfSortedCustomerId = new ArrayList<Long>();
for (Customer customer: customers){
listOfSortedCustomerId.add(customer.getId());
}
//convert the List of Longs to a JSON string
Gson gson = new Gson();
String jsonListOfSortedCustomerIds = gson.toJson(listOfSortedCustomerId);
//save to SharedPreference
mEditor.putString(LIST_OF_SORTED_DATA_ID, jsonListOfSortedCustomerIds).commit();
mEditor.commit();
}
Then, add this method to your MainActivity.java:
private List<Customer> getSampleData(){
//Get the sample data
List<Customer> customerList = SampleData.addSampleCustomers();
//create an empty array to hold the list of sorted Customers
List<Customer> sortedCustomers = new ArrayList<Customer>();
//get the JSON array of the ordered of sorted customers
String jsonListOfSortedCustomerId = mSharedPreferences.getString(LIST_OF_SORTED_DATA_ID, "");
//check for null
if (!jsonListOfSortedCustomerId.isEmpty()){
//convert JSON array into a List<Long>
Gson gson = new Gson();
List<Long> listOfSortedCustomersId = gson.fromJson
(jsonListOfSortedCustomerId, new TypeToken<List<Long>>(){}.getType());
//build sorted list
if (listOfSortedCustomersId != null && listOfSortedCustomersId.size() > 0){
for (Long id: listOfSortedCustomersId){
for (Customer customer: customerList){
if (customer.getId().equals(id)){
sortedCustomers.add(customer);
customerList.remove(customer);
break;
}
}
}
}
//if there are still customers that were not in the sorted list
//maybe they were added after the last drag and drop
//add them to the sorted list
if (customerList.size() > 0){
sortedCustomers.addAll(customerList);
}
return sortedCustomers;
}else {
return customerList;
}
}
Now update the line in setupRecyclerView() that you get the data from:
mCustomers = SampleData.addSampleCustomers();
to:
mCustomers = getSampleData();
Here is the source of my answer you can find more information and description about every single step.
I'm trying to access the facility String of this enum in java script
public enum FacilityEnum {
CAR_VALET("carValet"),
INDOOR("indoorPark"),
DISABLED_ACCESS("disabledAccess"),
EV_CHARGE("evCharge"),
private String facility;
private FacilityEnum(String facility) {
this.facility = facility;
}
public String getFacility() {
return facility;
}
public void setFacility(String facility) {
this.facility = facility;
}
}
This enum is used in a Facility.class
#Entity
public class Facility {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long facilityId;
#Enumerated(EnumType.STRING)
private FacilityEnum service;
#ManyToMany(mappedBy = "facilities")
#JsonBackReference("parks-facilities-services")
private Set<Park> parks;
}
public FacilityEnum getService() {
return service;
}
public void setService(FacilityEnum service) {
this.service = service;
}
which has a ManyToMany relation with Park.class.
The problem comes when i need to use the facility String in javascript
This the javascript interested part, i'm using Spring + Thymleaf
var parcheggi = JSON.parse([[${parks}]]); //my list of Parks
parcheggi.forEach(function (arrayItem) { //it's ok
var parcheggio = arrayItem;
var services = parcheggio.facilities; //it's ok, i get Facility objects
var servicesDiv = '<div>';
services.forEach(function (service){
var s = service; //the single Facility
servicesDiv += '<img src="/images/park_icons/facilities/' + s.service + '.png" />'
});
servicesDiv += '</div>';
//rest of the code...
In this case s.service is the rough Enum (CAR_VALET, INDOOR...) if i try s.service.facility I get undefined.. I need to have carValet, indoor, disabledAccess and so on...
One way to do what you want is to configure object mapper to serialize enums using toString method. You would add the following to the object mapper configuration:
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
(Note that previous Jackson versions have equivalent to this property but it's different).
Then just add toString to your enum:
#Override
public String toString ()
{
return facility;
}
You are getting undefined because your Enum can't be deserialized in JSON, you have two options here:
Either change the Implementation of your Enum, so it contains only the Stringconstants and it will be correctly mapped by Jackson.
Your code would be:
public enum FacilityEnum {
CAR_VALET,
INDOOR,
DISABLED_ACCESS,
EV_CHARGE;
}
Or you should override the toString() method in your Enum so it can
be deserialized and returned as a String.
Your code would be:
public enum FacilityEnum {
CAR_VALET("carValet"),
INDOOR("indoorPark"),
DISABLED_ACCESS("disabledAccess"),
EV_CHARGE("evCharge"),
private String facility;
private FacilityEnum(String facility) {
this.facility = facility;
}
public String getFacility() {
return facility;
}
public void setFacility(String facility) {
this.facility = facility;
}
#Override
public String toString() {
return facility;
}
}
I have a map application that show bicycle stops in Tehran.
it looks like this
what I want to do is that whenever I click on one of the spinner item, it zooms closely on that item's location. like this:
I tried to make it right but it doesn't work.
here is my code:
public class MainActivity extends android.support.v4.app.FragmentActivity implements android.widget.AdapterView.OnItemClickListener, LocationListener {
public Marker marker1;
GoogleMap googleMap;
GoogleMap mGoogleMap;
Spinner spr_place_list;
Toolbar toolbar;
ImageView menu_icon;
String[] mPlaceType = null;
String[] mPlaceTypeName = null;
ImageView share_button;
double mLatitude = 0;
double mLongitude = 0;
static final LatLng JAVANMARDAN = new LatLng(35.747394, 51.267577);
static final LatLng BAKERYHIPERSTAR = new LatLng(35.725623, 51.295175);
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_two);
toolbar = (Toolbar) findViewById(R.id.toolbar);
menu_icon = (ImageView) findViewById(R.id.menu_icon);
//SHARE BUTTON
View.OnClickListener handler = new View.OnClickListener() {
#Override
public void onClick(View v) {
shareUrl();
}
};
findViewById(R.id.share_button).setOnClickListener(handler);
// A rray of place types
mPlaceType = getResources().getStringArray(R.array.place_name);
// Array of place type names
// mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceType);
// Getting reference to the Spinner
spr_place_list = (Spinner) findViewById(R.id.spr_place_list);
final List<String> categories = new ArrayList<String>();
categories.add("جوانمردان 1");
categories.add("هایپر استار");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, categories);
// Setting adapter on Spinner to set place types
spr_place_list.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item
);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.map);
fragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
Marker marker1 = googleMap.addMarker(new MarkerOptions().title("بوستان جوانمردان").position(JAVANMARDAN));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(JAVANMARDAN, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
googleMap.addMarker(new MarkerOptions().title("بزرگراه شهید باکری - هایپر استار").position(BAKERYHIPERSTAR));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BAKERYHIPERSTAR, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
});
spr_place_list.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String selectedItem = parent.getItemAtPosition(position).toString();
if (selectedItem.equals("جوانمردان 1")) {
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Enabling MyLocation in Google Map
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
private void shareUrl() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//TEXT
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "اپلیکیشن دوچرخه سواری");
shareIntent.putExtra(Intent.EXTRA_TEXT, "؟؟؟؟؟");
//IMAGE
String imagePath = Environment.getExternalStorageState() +
"/share_image.png";
File imageFileShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileShare);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share link!"));
}
/**
* A method to download json data from url
*/
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("Ex downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
if (selectedItem.equals("جوانمردان 1")) {
googleMap.addMarker(new MarkerOptions().title("بزرگراه شهید باکری - هایپر استار").position(BAKERYHIPERSTAR));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BAKERYHIPERSTAR, 21));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(21), 2000, null);
//googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(BAKERYHIPERSTAR,20));
//googleMap.animateCamera(CameraUpdateFactory.zoomTo(21), 5000, null);
}
}
/**
* A class, to download Google Places
*/
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
// Clears all the existing markers
mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Inside your eventListener, try adding
map.setZoom(9);
map.panTo(curmarker.position);
As mentioned in W3Schools Tutorial - Google Maps Events, attach an event handler to a marker that zooms the map when clicked then, with panTo(), pan the map back to the marker.
You may try it yourself in W3schools tutorial and solution given in this SO post - Zoom in to marker google.maps might be helpful too.
How to send data from activity class to custom view class I have written following program?
I am using this program for selecting the color and then shape using OnTouchListener. Please, could you give me more detail how I can complete this task. Thank you in advance
Activity class
package com.easyway2win;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button butnPink;
#Override
protected void onCreate(Bundle savedInstanceState) {
butnPink = (Button)findViewById(R.id.pinkColor);
super.onCreate(savedInstanceState);
/* MyViewActivity mv = new MyViewActivity(this);*/
setContentView(R.layout.activity_main);
}
public void clickMe(View view){
int intColor = 0;
String hexColor = null;
switch(view.getId()){
case R.id.pinkColor:
intColor = getResources().getColor(R.color.pink);
// hexColor = String.format("#%06X", (0xFFFFFF & intColor));
// Log.d("Hi", "I am pink color code " + hexColor);
break;
case R.id.blueColor:
intColor = getResources().getColor(R.color.blue);
// hexColor = String.format("#%06X", (0xFFFFFF & intColor));
// Log.d("Hi", "I am Blue color " + hexColor);
break;
case R.id.squaretool:
Log.i("Hi","I am square");
}
hexColor = String.format("#%06X", (0xFFFFFF & intColor));
Log.d("Hi", "I am color code " + hexColor );
}// end [ clickMe method ]
PaintView paintView = new PaintView();
}
Custom View Class
package com.easyway2win;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class PaintView extends View {
private Paint paint;
public PaintView(Context context) {
super(context);
//context.getResources().getColor(Color.parseColor()) // I don't know how to do it coding
}
public PaintView(Context context, AttributeSet attrs ){
super(context, attrs);
}
public PaintView(Context context, AttributeSet attrs, int defStyle/*Context context, Rect rectangle, Paint paint*/) {
super(context,attrs,defStyle);
// this.rectangle = rectangle;
// this.paint = paint;
}
public void setColour(String colour){
// need code here
}
#Override
protected void onDraw(Canvas canvas) {
/* canvas.drawRect(rectangle,paint);*/
}
}
There are multiple ways to achieve your goal. But creating a class with global variables to hold your color and call it when necessary is a good approach for your scenario.
Check this question for more info on how to create and access global variables from a class or an activity.
Summary: I have a web control that is dynamically added to the page. The control has a HiddenField child control. I am passing the control's ClientID to a jquery widget that is setting the value to a string (json converted to string). When the form is posted back to the server, the value of the HiddenField is a blank string. I value is in the Request.Form[UniqueID] object. The value is making it back to the server. The problem is that, I don't have access to the Request object when I need the value without modifying a lot of legacy code.
The strange thing is that the selectmany control is the one I am having a problem with, but it inherits from the SelectOne that is working properly. I think I am doing something wrong in the selectmany class because even if I try to push a value into the SelectOneHiddenValue it does not work ,but it works properly when the SelectOne uses it.
SelectOne:
[ToolboxData("<{0}:SelectOne runat=server></{0}:SelectOne>")]
public class SelectOne : Panel, IControl,ISelectOne
{
#region structure
private readonly Panel _selectOneTextboxContainer = new Panel();
protected readonly TextBox SelectOneTextbox = new TextBox();
protected readonly HiddenField SelectOneHiddenValue = new HiddenField();
private readonly Panel _selectOneDropdownImageContainer = new Panel();
private readonly Image _selectOneDropDownImage = new Image();
#endregion
private readonly IList<LookupItem> _selectedItems = new List<LookupItem>();
#region properties
public IList<LookupItem> SelectedItems { get { return _selectedItems; } }
public bool MultiSelect { get; set; }
public DisplayOption Display { get; set; }
public string Name { get; set; }
[DefaultValue(0)]
public int LookupValueOrgID
{
get
{
EnsureChildControls();
return Convert.ToInt32(String.IsNullOrEmpty(SelectOneHiddenValue.Value) ? "0" : SelectOneHiddenValue.Value);
}
set
{
EnsureChildControls();
SelectOneHiddenValue.Value = value.ToString();
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
EnsureChildControls();
return SelectOneTextbox.Text;
}
set
{
EnsureChildControls();
SelectOneTextbox.Text = value;
}
}
/// <summary>
/// The minimum number of characters a user has to type before the autocompleter activates.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(1)]
[Localizable(true)]
public int MinChars
{
get
{
int b = (ViewState["MinChars"] == null ? 1 : (int)ViewState["MinChars"]);
return b;
}
set
{
ViewState["MinChars"] = value;
}
}
/// <summary>
/// The number of backend query results to store in cache. If set to 1 (the current result), no caching will happen. Must be >= 1.
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[DefaultValue(10)]
[Localizable(true)]
public int CacheLength
{
get
{
int b = (ViewState["CacheLength"] == null ? 10 : (int)ViewState["CacheLength"]);
return b;
}
set
{
ViewState["CacheLength"] = value;
}
}
public string OuterMarkupClientID
{
get { return "SelectOne_Container" + ClientID; }
}
/// <summary>
/// If true, target input text is appended to
/// If false, target input text is replaced
/// </summary>
public bool AppendSelectedTextToInput { get; set; }
public virtual string ContainerClass
{
get { return "SelectOneContainer"; }
}
#endregion
#region constructor
public SelectOne()
{
SetCssClasses();
}
#endregion
#region lifecycle overrides
protected override void CreateChildControls()
{
base.CreateChildControls();
AddChildrenToControlCollection();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
SetupClientEvents();
ControlHelper.AddRequiredControl(this);
var resourceName = string.Empty;
var cs = Page.ClientScript;
resourceName = "UI.Controls.resources.images.DropDownButton.gif";
_selectOneDropDownImage.ImageUrl = cs.GetWebResourceUrl(GetType(), resourceName);
SelectOneTextbox.Attributes.Add("lookupOrgID", LookupOrgID.ToString());
SelectOneTextbox.Attributes.Add("cacheLength", CacheLength.ToString());
SelectOneTextbox.Attributes.Add("service", Service);
SelectOneTextbox.Attributes.Add("selectOneTextboxId", SelectOneTextbox.ClientID);
SelectOneTextbox.Attributes.Add("selectOneHiddenValueId",SelectOneHiddenValue.ClientID);
}
#endregion
#region private helpers
private void SetCssClasses()
{
this.CssClass = ContainerClass + " AutocompleteContainer";
_selectOneDropDownImage.CssClass = "SelectOneDropDownImage";
SelectOneTextbox.CssClass = "SelectOneTextbox QuantifiTextBox";
_selectOneTextboxContainer.CssClass = "SelectOneTextboxContainer";
_selectOneDropdownImageContainer.CssClass = "SelectOneDropDownImageContainer";
}
private void SetupClientEvents()
{
ControlHelper.RegisterAutoCompleteScript(this);
var resourceName = "UI.Controls.resources.scripts.SelectOne.js";
string js;
using (var sr = new StreamReader(GetType().Assembly.GetManifestResourceStream(resourceName)))
{
js = sr.ReadToEnd();
sr.Close();
}
ClientScriptProxy.Current.RegisterStartupScript(this, typeof(SelectOne), "SelectOneJS", js, true);
_selectOneDropDownImage.Attributes.Add("onclick", "SelectOne_ImageClick('" + SelectOneTextbox.ClientID + "');");
}
private void AddChildrenToControlCollection()
{
_selectOneTextboxContainer.Controls.Add(SelectOneTextbox);
this.Controls.Add(_selectOneTextboxContainer);
_selectOneDropdownImageContainer.Controls.Add(_selectOneDropDownImage);
this.Controls.Add(_selectOneDropdownImageContainer);
this.Controls.Add(SelectOneHiddenValue);
}
#endregion
}
Select Many:
[ToolboxData("<{0}:SelectMany runat=server></{0}:SelectMany>")]
public class SelectMany : SelectOne, ISelectMany
{
#region structure
private readonly Panel _selectedItemsPanel = new Panel();
private readonly HiddenField _selectManyHiddenField = new HiddenField();
public override string ContainerClass
{
get
{
return "SelectManyControlContainer";
}
}
#endregion
public SelectMany()
{
MultiSelect = true;
}
#region lifecycle overrides
protected override void CreateChildControls()
{
base.CreateChildControls();
_selectManyHiddenField.ID = "SelectedItemsHiddenValue";
this.Controls.Add(_selectedItemsPanel);
this.Controls.Add(_selectManyHiddenField);
SelectOneTextbox.Attributes.Add("data-multiselect", MultiSelect.ToString());
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
var resourceName = "jquery.SelectedItemCollection.js";
ClientScriptProxy.Current.RegisterClientScriptInclude(this, Page.ClientScript.GetWebResourceUrl(this.GetType(),resourceName));
var serializer = new JavaScriptSerializer();
var startupScript = String.Format("\n$('#{0}').each(function(){{" +
"var selectedPlugin = $(this).SelectedItemCollection(" +
" {{" +
" itemData: {1}," +
" deleteImageUrl: '{2}'," +
" selectedTextId: '{3}', " +
" hiddenTextFieldId: '{4}' " +
" }});}});\n",
this.ClientID,
serializer.Serialize(SelectedItems),
GetDeleteImageUrl(),
SelectOneTextbox.ClientID,
_selectManyHiddenField.ClientID
);
ClientScriptProxy.Current.RegisterStartupScript(this,this.GetType(),"SelectedItemsJs_" + this.ClientID,startupScript,true);
}
#endregion
#region public api
public void BindForm()
{
EnsureChildControls();
this.DataBind();
var jsonString = _selectManyHiddenField.Value;
SelectedItems.Clear();
if (!jsonString.IsNullOrEmpty())
{
Json.Decode<IEnumerable<LookupItem>>(jsonString).ForEach(li => SelectedItems.Add(li));
}
}
#endregion
private string GetDeleteImageUrl()
{
var cs = Page.ClientScript;
const string resourceName = "UI.Controls.resources.images.close.gif";
return cs.GetWebResourceUrl(this.GetType(), resourceName);
}
}
Well, it was something stupid. And it took me forever to find. Basically, don't misuse the EnsureChildControls() method. The base class was calling that before some of it's properties were accessed. This called RecreateChildControls() after ViewState was restored, but before I could check the values.
To correct this, I added EnsureChildControls() in the OnInit override for both the base class and the derived class. That way, all my controls will be created properly and ViewState is restored after their creation.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}