I am new to Android.I am building one Tabbed app having 5 Tabs.I use different ViewGroups, each tab have there respactive ViewGroup according to as per need & there child Activities.First tab is TabGroupHome having different child Activities.TabGroupHome first start GoogleMapActivity (having overlayItems) as its child activity. these overlays reprasents different users. I get the data of these users from one JSONArray which is returned by one php file on server having data of differnt users. when i launch my App its look->
launching_view!
it have one actionbar on the top having different buttons(e.g., List, profile & refresh). when i click on List it show me one list of all users ->
list of Users! & user_profile!!
& when i click on listItem it show me complete profile of respactive User pointed above
Where i stuck off is-> ??? i want to show this profile of user when i tap on MapPin...
my code to do this is->
public class GoogleMapActivity extends MapActivity implements ActionBar {
Button btnOnMapList, btnProfileHome, btnRefresh;
Intent intent;
private JSONArray jArray;
private JSONObject jFan_Data;
private ItemBean bean;
private FansData fansdata;//reference of FansData class that return me JSONArray
HelloItemizedOverlay itemizedOverlay;//..........
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
btnProfileHome = (Button) findViewById(R.id.btn_profile_home);
btnOnMapList = (Button) findViewById(R.id.btn_list_home);
btnRefresh = (Button) findViewById(R.id.btn_refresh_home);
super.onCreate(savedInstanceState);
setContentView(R.layout.googlemapactivity);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
// mapView.setSatellite(true);
/**TG_1 -> Here i write code to get my current location(e.g., through LocationManager)
* after getting location, i write my location`s latitude & longitude into
* shearedPreference */
//geading preference to get my unique id
SharedPreferences myUid=GoogleMapActivity.this.getSharedPreferences("uid", MODE_WORLD_READABLE);
String myId=myUid.getString("myId", "");
Log.i("MyUid", myId);
/** calling FansData class to get all users data. Currently i am providing my hard codded location but i have to get it from LocationManager */
fansdata=new FansData();
jArray=fansdata.jFanDataArray(1000, 12.9716060, 77.5903760, "h9ow0");
System.out.println(jArray.toString());
/** to showing Users on map as pins */
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.small_football_icon);
HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(
drawable, getParent());
for(int i=0;i<jArray.length();i++){
try {
jFan_Data=jArray.getJSONObject(i);
GeoPoint geoPoint = new GeoPoint((int) (jFan_Data.getDouble("lat")* 1E6),
(int) (jFan_Data.getDouble("lang")* 1E6));
OverlayItem overlayitem = new OverlayItem(geoPoint, jFan_Data.getString("name"),
jFan_Data.getString("uniqid"));
itemizedOverlay.addOverlay(overlayitem);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mapOverlays.add(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onHomeList(View view) {
Intent in = new Intent(getParent(), MapPinsList.class);
TabGroupActivity prnt = (TabGroupActivity) getParent();
prnt.startChildActivity("MapPinsList", in);
}
#Override
public void onHomeProfile(View view) {
Intent in = new Intent(getParent(), ProfileActivity.class);
TabGroupActivity prnt = (TabGroupActivity) getParent();
prnt.startChildActivity("ProfileActivity", in);
}
#Override
public void onHomeRefresh(View view) {
// TODO Auto-generated method stub
}
#Override
public void onListMap(View view) {
// TODO Auto-generated method stub
}
#Override
public void onListProfile(View view) {
// TODO Auto-generated method stub
}
}
My HelloItemizedOverlay Class is->
public class HelloItemizedOverlay extends ItemizedOverlay {
private static final int VIEW_PROFILE = 1;
private static final int SEND_MASSAGE = 2;
OverlayItem item;
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public HelloItemizedOverlay(Drawable defaultMaker, Context context) {
// super(defaultMaker);
super(boundCenterBottom(defaultMaker));
mContext = context;
}
#Override
public boolean onTap(int index) {
// Option to select on clicking pin
final String[] option = new String[] { "View Profile", "Send Massage",
"Cancle" };
// to hold option
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
android.R.layout.select_dialog_item, option);
//OverlayItem item = mOverlays.get(index);
item = mOverlays.get(index);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(item.getTitle());
// builder.setMessage(item.getSnippet());
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// TODO Auto-generated method stub
if (i == 0) {
String fId=item.getSnippet();
Toast.makeText(mContext, "Profile View is on Progress...!"+fId,
Toast.LENGTH_SHORT).show();
Intent in = new Intent(mContext, FanProfile.class);
Bundle fBundle= new Bundle();
fBundle.putString("fanId", fId);
in.putExtras(fBundle);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.getApplicationContext().startActivity(in);
} else if (i == 1) {
Toast.makeText(mContext,"Send Massage View is on Progress...!",
Toast.LENGTH_SHORT).show();
} else if (i == 2) {
dialog.cancel();
}
}
});
builder.show();
// AlertDialog dialog= builder.create();
return true;
}
public void addOverlay(OverlayItem overlayItem) {
// for(int i=0;i<=size();i++){
mOverlays.add(overlayItem);
populate();
// }
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
}
FanProfile in "onTap" is the same activity which i call when i click on listItem of user`s list!
above code works but it start the view over my tabView which hides my Tabs...
[this] http://i.stack.imgur.com/lgT2G.png
i am not getting where i commit mistake or doing WRONG.
Your suggestions are valuable for me!!!
I would greatly appreciate pointers or sample code to where I get the solution of this problem...
One possible solution is to add Tabs to the FanProfile activity which are same as the Previous activity
here after a long R&D i get the solution the correct way to show FanProfile when i tap on MapPin is
#Override
public void onClick(DialogInterface dialog, int i) {
// TODO Auto-generated method stub
if (i == 0) {
//getting the unique-id of fan, whose pin is clicked on map`s pins
String fId=item.getSnippet();
Toast.makeText(mContext, "Profile View is on Progress...!"+fId,
Toast.LENGTH_SHORT).show();
//getting the parent context(cast the context of GoogleMapActivity into its Parent e.g.,"TabGroupActivity")
/** i cast the mContext into its parent Activity`s context which extends ViewGroup */
tga=(TabGroupActivity)mContext;
//1.intent that start my "FanProfile" Activity
Intent in = new Intent(tga, FanProfile.class);
//2.Bundle that hold data which i want to send to "FanProfile" Activity.
Bundle fBundle= new Bundle();
//3.putting values into bundle
fBundle.putString("fanId", fId);
//4.Binding the bundle with the intent
in.putExtras(fBundle);
//5.Starting intent
tga.startChildActivity("FanProfile", in);
} else if (i == 1) {
Toast.makeText(mContext,
"Send Massage View is on Progress...!",
Toast.LENGTH_SHORT).show();
} else if (i == 2) {
dialog.cancel();
}
}
This Works well & now i am happy that i get which need -> this!
Tanks a lot #Rajdeep Dua for youe`s Valuable suggestion!!! I will again thankful to "StackOverFlow" & you all & hoping the same cooperation & suggestions from all...
StackOverFlow is really a nice fantastic -> fabulous ->
fantabulous ... :)
Related
//imports
public class MainActivity extends Activity implements OnCheckedChangeListener
{
int count=0,ints......;
TextView textviews...;
int itemCode,month;
ArrayList<String> Name = new ArrayList<String>();
AlertDialog alertDialog ;
SharedPreferences sp;
EditText EtItemCode;
Editor editor ;
RadioButton RbForItemCode,RbForItemName;
RadioGroup RgForItemVsName;
PopupWindow popupWindowItems;
String popUpItems[];
ProgressDialog pDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//shared prefs
sp = this.getSharedPreferences("MySharedPrefsFile", Context.MODE_PRIVATE);
editor = sp.edit();
intForShardPref= sp.getInt("NEW_INSTALLATION",1); // getting Integer(1 is for no)
if(intForShardPref==1){
Intent intent = new Intent(this,Verify.class);
startActivityForResult(intent, 1);
}
else{
//do nothing
}
EtItemCode.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ToCheckItemCodeOfEdittext = EtItemCode.getEditableText().toString();
DatabaseHandler db=new DatabaseHandler(MainActivity.this);
List<Item> Items = db.getAllItemWithSubString(ToCheckItemCodeOfEdittext,itemNumberOrNameSelectedInRadioButtonOptions);
if(EtItemCode.length()>2){
if(EtItemCode.length()>3||flagForPopUpWindow>EtItemCode.length())
popupWindowItems.dismiss();
Name.clear();
for (Item cn : Items) {
if(RbForItemCode.isChecked()==true){
Name.add(Integer.toString(cn.getItemNumber()));
}
else{
Name.add(cn.getName());
}
}
popUpItems = new String[Name.size()];
Name.toArray(popUpItems);
popupWindowItems = popupWindowItems();
***popupWindowItems.setFocusable(false);***
popupWindowItems.showAsDropDown(findViewById(R.id.et_item_code), -5, 0);
}
else{
if(flagForPopUpWindow==3&&EtItemCode.length()==2)
popupWindowItems.dismiss();
}
flagForPopUpWindow=EtItemCode.length();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
private void init() {
// TODO Auto-generated method stub
//some code
}
public PopupWindow popupWindowItems() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewItems = new ListView(this);
// set our adapter and pass our pop up window contents
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
this, //context for activity
android.R.layout.simple_list_item_1, //layout used
Name){ //Items to be displayed
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item.toString();
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
//listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
listViewItems.setAdapter(adapter);
// set the item click listener
listViewItems.setOnItemClickListener(new ItemsDropdownOnItemClickListener());
// some other visual settings
//popupWindow.setFocusable(true);
popupWindow.setWidth(EtItemCode.getWidth());
//popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);
popupWindow.setHeight(r.height()-3*EtItemCode.getHeight());
// set the list view as pop up window content
popupWindow.setContentView(listViewItems);
return popupWindow;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.phone_number:
Intent p = new Intent(MainActivity.this,PhoneNumber.class);
startActivity(p);
break;
case R.id.exit:
finish();
break;
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//some code
}
class LoadDataBase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("DataBase Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
Log.d("Reading: ", "Reading all Items..");
List<Item> Items = db.getAllItem();
//some code
//DatabaseHandler db1 = new DatabaseHandler(this);
count= db.getItemCount();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
public class ItemsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "Item is: ", Toast.LENGTH_SHORT).show();
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EtItemCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// dismiss the pop up
popupWindowItems.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
Toast.makeText(MainActivity.this, "Item is: " + selectedItemText, Toast.LENGTH_SHORT).show();
DatabaseHandler db =new DatabaseHandler(MainActivity.this);
Item item= new Item();
if(RbForItemCode.isChecked()==true){
item = db.getItem(Integer.valueOf(selectedItemText));
}
else if(RbForItemName.isChecked()==true){
item = db.getItem(selectedItemText);
}
itemCode=item.getItemNumber();
}
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(RbForItemCode.isChecked()==true){
itemNumberOrNameSelectedInRadioButtonOptions="id";
//some code
}
}
else if(RbForItemName.isChecked()==true){
//some code
}
}
}
This code is working fine on my phone galaxy note 2(custom rom of note 4.. Android 4.4.4).By fine I mean I can type in edittext and popupwidow shows up after 3rd text(because of condition I have put) and I can select an option from the popupwindow. When I try to run the code on any other phone like galaxy grand then callback to ItemsDropdownOnItemClickListener is not registered and I can only scroll the popupwindow and keep on typing in edittext but cannot select any of the options in the popupwindow. If I set popupWindowItems.setFocusable(false) to true i.e popupWindowItems.setFocusable(true), and then as soon as I type 3rd letter in edittext,edittext looses focus and popwindow gains it. Now I can select anything.. But now I cannot continue to type in edittext.I have to manually select edittext and type.
Now I want that after tying 3rd word in edittext a popupwindow should appear(which currently is appearing) and edittext doesn't loose focus(so that i can continue typing).. Further if I select anything from popupwindow ,ItemsDropdownOnItemClickListener should be called which is currently being not called in other phones when popupWindowItems.setFocusable(false);
I am doing this to load data from sqlite database and show in popupwindow once the user types 3rd word. Any suggestion is recommended
Edit: Problem solved. Now using AutoComplete TextView
Please help me with little thing that make me crazy
I’m trying to set text in a textview that is the last element of a dynamic Array.
I add a function inside my Adapter that return the last element of the array.
I’m coming back to the Main Activity where I’d like to show the text and during time it falls at “nullpointerexception”.
Please help
Here is my code:
public class MainActivity extends Activity implements OnClickListener{
private static Context mContext;
public Button mExit, mHistory, mRating;
public TextView mSignal;
HistoryAdapt myLastItem;
List<HistoryItems> m_myLastItem;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.mContext=getApplicationContext();
mExit=(Button)findViewById(R.id.ExitButton);
mExit.setOnClickListener(this);
mHistory=(Button)findViewById(R.id.HistoryButton);
mHistory.setOnClickListener(this);
mRating=(Button)findViewById(R.id.RateButton);
mRating.setOnClickListener(this);
mSignal=(TextView)findViewById(R.id.SignalOfTheDayTV);
//### SET LAST ELEMENT INTO TEXTVIEW
m_myLastItem = new ArrayList<HistoryItems>();
myLastItem=new HistoryAdapt(mContext, m_myLastItem );
m_myLastItem= (List<HistoryItems>) myLastItem.getLastElement();
mSignal.setText(( (HistoryItems) m_myLastItem).getTitle());
// AppRater.app_launched(this);
// AppRater.showRateDialog(this, null);
//Get a Tracker (should auto-report)
((AppManager) getApplication()).getTracker(AppManager.TrackerName.APP_TRACKER);
}//oncreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static Context getAppContext(){
return MainActivity.mContext;
}
public void ExitState(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("You're about to quit Signals4Trading");
builder.setIcon(R.drawable.five);
//builder.setMessage("Your device has been registered successfully. You'll receive signals very soon.");
builder.setMessage("Are you sure you want to quit?");
builder.setCancelable(false);//can't click on the background of the activity
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"See you soon", Toast.LENGTH_LONG).show();
finish();
}//OnClickListener PositiveButton
});//anonymous class PositiveButton
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Enjoy your visit", Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}//ExitState
public void goToHistoryActivity(){
Intent intent = new Intent(MainActivity.this, HistoryAct.class );
startActivity(intent);
}
public void rateApp(){
Intent intent = new Intent(MainActivity.this, Rate.class);
startActivity(intent);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.ExitButton:
ExitState();
break;
case R.id.HistoryButton:
goToHistoryActivity();
break;
case R.id.RateButton:
rateApp();
break;
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
//Get an Analytics tracker to report app starts & uncaught exceptions etc.
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
//Stop the analytics tracking
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
}//MainActivity
**Adapter:**
package com.Signals4Trading.push.android;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class HistoryAdapt extends BaseAdapter {
private final List<HistoryItems>items;
private final Context context;
public HistoryAdapt(Context context,List<HistoryItems>items){
this.context=context;
this.items=items;
}//constructor
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int id) {
// TODO Auto-generated method stub
return id;
}
//###FUNCTION THAT RETURN LAST ELEMENT
public HistoryItems getLastElement(){
HistoryItems lastItem = items.get(items.size());
if(items!=null && !items.isEmpty()){
lastItem = items.get(items.size()-1);
}
return lastItem;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.historyitems, null);
holder = new ViewHolder();
holder.itemTitle = (TextView) convertView.findViewById(R.id.itemTitleTV);
holder.itemDate=(TextView) convertView.findViewById(R.id.itemDateTV);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemTitle.setText(items.get(position).getTitle());
holder.itemDate.setText(items.get(position).getDate());
return convertView;
}
class ViewHolder {
TextView itemTitle;
TextView itemDate;
}
}
//HistoryAdapt
you are getting this error because you have never intialized the object of your adapter class
HistoryAdapt in requires a context and and list to pass into it ,as defined in your constructor
This may be because Listitems is still referencing to null object. Have you called HistoryAdapt(context,items) constructor before calling
HistoryItems l_myLastItem= (HistoryItems) myLastItem.getLastElement(0);
?
Do as Haresh Chhelana said
public HistoryItems getLastElement(){
return items.get(items.size()-1);
}
the reason you are getting null pointer exception is because your list has not been initialized so it is referencing null. To get rid of this error you should first initialize your ArrayList then populate it as
//### SET LAST ELEMENT INTO TEXTVIEW
m_myListItem = new ArrayList();
//then add some data to arrayList for eg:
for (i=1;i<=10;i++){
m_myListItem.add(new HistoryItem().setTitle("title " + i));
}
myLastItem=new HistoryAdapt(mContext, m_myListItem ); //this should be m_myListItem not m_myLastItem
m_myLastItem= myLastItem.getLastElement();// m_myLastItem should be of type HistoryItem as HistoryItem m_myLastItem not List<HistoryItems> m_myLastItem
mSignal.setText(m_myLastItem.getTitle());
P.S. please have a look at your variable naming convention
No need to pass last item index instead directly get index from adapter list size.
public HistoryItems getLastElement(){
return items.get(items.size()-1);
}
Hi i working on demo application for google map with custom pop-up.
please suggest me how to handle textview & image view click handle.
i can't get event. below are my code.
class PopupAdapter implements InfoWindowAdapter {
LayoutInflater inflater=null;
Context context;
PopupAdapter(LayoutInflater inflater, Context context) {
this.inflater=inflater;
this.context = context;
}
public View getInfoWindow(Marker marker) {
return(null);
}
public View getInfoContents(Marker marker) {
MyModel mapItem = (MyModel) MainActivity.markers.get(marker.getId());
View popup=inflater.inflate(R.layout.popup, null);
TextView tv=(TextView)popup.findViewById(R.id.title);
ImageView im = (ImageView)popup.findViewById(R.id.icon);
tv.setText(marker.getTitle());
tv=(TextView)popup.findViewById(R.id.snippet);
tv.setText(marker.getSnippet());
im.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("POPUP", "Image Click");
}
});
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("POPUP", "HI");
Toast.makeText(context, "HI", Toast.LENGTH_SHORT).show();
}
});
return(popup);
}
}
Main Activity
public class MainActivity extends AbstractMapActivity implements
OnNavigationListener, OnInfoWindowClickListener {
private static final String STATE_NAV="nav";
private static final int[] MAP_TYPE_NAMES= { R.string.normal,
R.string.hybrid, R.string.satellite, R.string.terrain };
private static final int[] MAP_TYPES= { GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_TERRAIN };
private GoogleMap map=null;
public static HashMap<String, MyModel> markers= new HashMap<String, MyModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (readyToGo()) {
setContentView(R.layout.activity_main);
SupportMapFragment mapFrag=
(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
initListNav();
map=mapFrag.getMap();
if (savedInstanceState == null) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
map.moveCamera(center);
map.animateCamera(zoom);
}
MyModel item = new MyModel();
item.setId("1");
item.setName("Bhavesh");
item.setAdd("Krishnanagar");
addMarker(map, 40.748963847316034, -73.96807193756104,R.string.un, R.string.united_nations,item);
item = new MyModel();
item.setId("2");
item.setName("Kunal");
item.setAdd("Bhavnagar");
addMarker(map, 40.76866299974387, -73.98268461227417,R.string.lincoln_center,R.string.lincoln_center_snippet,item);
item = new MyModel();
item.setId("3");
item.setName("Ravi");
item.setAdd("Ahmedabad");
addMarker(map, 40.765136435316755, -73.97989511489868,R.string.carnegie_hall, R.string.practice_x3,item);
item = new MyModel();
item.setId("3");
item.setName("Binitbhai");
item.setAdd("Shivranjani");
addMarker(map, 40.70686417491799, -74.01572942733765,R.string.downtown_club, R.string.heisman_trophy,item);
map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater(),MainActivity.this));
map.setOnInfoWindowClickListener(this);
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
map.setMapType(MAP_TYPES[itemPosition]);
return(true);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(STATE_NAV, getSupportActionBar().getSelectedNavigationIndex());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_NAV));
}
#Override
public void onInfoWindowClick(Marker marker) {
// MyModel mapItem = (MyModel) markers.get(marker.getId());
// Toast.makeText(this,marker.getSnippet()+ marker.getTitle() + " "+mapItem.getName() +" "+mapItem.getAdd() , Toast.LENGTH_LONG).show();
}
private void initListNav() {
ArrayList<String> items=new ArrayList<String>();
ArrayAdapter<String> nav=null;
ActionBar bar=getSupportActionBar();
for (int type : MAP_TYPE_NAMES) {
items.add(getString(type));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
nav=
new ArrayAdapter<String>(
bar.getThemedContext(),
android.R.layout.simple_spinner_item,
items);
}
else {
nav=
new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items);
}
nav.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
bar.setListNavigationCallbacks(nav, this);
}
private void addMarker(GoogleMap map, double lat, double lon, int title, int snippet,MyModel item) {
markers.put(map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(getString(title)).snippet(getString(snippet)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))).getId(), item);
// map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title(getString(title)).snippet(getString(snippet)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
Please suggest me how to do this event.
thank you..
You cannot put OnClickListeners on the contents of an info window. The info window itself is not displaying your layout, but rather a Bitmap generated from the layout. This is covered in the documentation:
As mentioned in the previous section on info windows, an info window is not a live View, rather the view is rendered as an image onto the map. As a result, any listeners you set on the view are disregarded and you cannot distinguish between click events on various parts of the view. You are advised not to place interactive components — such as buttons, checkboxes, or text inputs — within your custom info window.
You can use setOnInfoWindowClickListener() to find out when the info window itself is tapped.
As explained in other answers what you want to achieve is not supported directly by Google Maps Android API v2, but...
you can do what you need by putting yourself in front of MapFragment or MapView, handle MotionEvents to make your OnClickListeners be called.
See this answer for a nice (but hackish) how-to: https://stackoverflow.com/a/15040761/2183804
yes you cannot add listener on the view of info window. One thing you can do , onInfoWindowClick show alert menu and give the user some options.
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
final CharSequence[] items = { "message", "call"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Call");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
sendMessage();
} else {
makeCall();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Or you can try something like this..
I am not sure whether its work or not.
https://stackoverflow.com/a/15040761/1792228
I'm trying to pass an arraylist of objects to a new activity, I followed a tutorial and it looks as if I've done everything right but my program kept crashing. I've commented out the majority of the code to isolate the line that seems to be causing the crash and its the getParcelableArrayListExtra bit that seems to be the problem. Can anyone help?
New Activity:
public class DatabaseSearch extends ListActivity{
DBAdapter db = new DBAdapter(this);
ArrayList<String> listrecipes = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databasesearch);
Intent i = getIntent();
if (i != null) {
ArrayList<mydata> data = i.getParcelableArrayListExtra ("com.example.MyPantry.array");
}
}
}
Bit of code from the old activity--
I don't know if it matters but the new activity is being called within a dialog box
#Override
protected Dialog onCreateDialog(int id)
{
switch(id) {
case 0:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("List all recipes that match over:")
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
switch (item)
{
case 0:
percentageselected = 25;
break;
case 1:
percentageselected = 50;
break;
case 2:
percentageselected = 75;
break;
case 3:
percentageselected = 100;
break;
default:
break;
}
}
})
.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
if (percentageselected == 0)
{
Toast.makeText(getBaseContext(), "Please make a selection", Toast.LENGTH_SHORT).show();
}
else
{
Intent intent = new Intent(getBaseContext(), DatabaseSearch.class);
intent.putParcelableArrayListExtra("com.example.MyPantry.array", array);
startActivity(intent);
}
}
})
.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton)
{
dialog.dismiss();
}
})
.create();
}
return null;
}
My objects inside the array I want to pass--
public class mydata implements Parcelable {
private int recipeID;
private int ingredientID;
private String check = "unchecked";
private int percentage = 0;
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel data, int flags) {
// TODO Auto-generated method stub
data.writeInt(recipeID);
data.writeInt(ingredientID);
data.writeString(check);
data.writeInt(percentage);
}
//Other functions
}
Lastly I have this class that the tutorial instructed me to make...
public class MyCreator implements Parcelable.Creator<mydata> {
#Override
public mydata createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new mydata(source);
}
#Override
public mydata[] newArray(int arg0) {
// TODO Auto-generated method stub
return new mydata[arg0];
}
}
So I know it's quite a bit to look at but I'm just trying to be thorough. The problem starts to occur inside the if statement in the new activity.
When just passing data between intents, you can just mark your classes as Serializable (by implementing the Serializable marker interface) and add them directly to the intent as extras without having to do all this work with parcelable (parcelable is really only needed when binding to services).
It's hard to say why you're getting the error without seeing a stack trace or the constructor for mydata that populates the class using the Parcel.
I have a mapview, with itemizedoverlays, exactly like in the example of android developers guide: http://developer.android.com/resources/tutorials/views/hello-mapview.html
on the itemizedoverlay, i have a personalized dialog, with a button. all fine until here, but now i have problems trying to add the functionality to the button. I need that the button start's a new activity, but i can't achieve that.... ¿why? because on this line: i = new Intent (NyItemizedOverlay.class, Locate.class); i have the current Intent class as first parameter, and the target intent class at second parameter.
MyItemizedOverlay is not a Intent class... it's ItemizedOverlay extension, then it doesn't compile when i try to launch the intent, i am trying to pass a normal class as first argument, and it needs an intent class. I have to put the launcher class, but the launcher class is not an intent :S
If i try to put another intent class on the first argument, i got this error: No enclosing instance of the type AllActivity is accessible in scope .... (AllActivity is a public activity class of my app)
How i can solve this?
full code here:
public class MyItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private ArrayList<String> permissions = new ArrayList<String>();
private Context mContext;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void addOverlay(OverlayItem overlay,String permission) {
mOverlays.add(overlay);
permissions.add(permission);
populate();
}
public MyItemizedOverlay(Drawable defaultMarker, Context context) {
//super(defaultMarker);
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void clear()
{
mOverlays.clear();
permissions.clear();//lista de permisos de cada usuario, ya que hay dos campos, el email (snippet) y el permission, una lista.
}
protected boolean onTap(int index) {
try{
OverlayItem item = mOverlays.get(index);
if (permissions.size()==0)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
}
else
{
//set up dialog
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.personal_dialog);
dialog.setTitle(item.getTitle());
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
//set up text
TextView DialogEmail = (TextView) dialog.findViewById(R.id.DialogEmail);
TextView DialogPermission = (TextView) dialog.findViewById(R.id.DialogPermission);
DialogEmail.setText(item.getSnippet());
DialogPermission.setText(permissions.get(index));
final String userName=item.getTitle();
final String email=item.getSnippet();
final int cont=index;
//set up button
Button button = (Button) dialog.findViewById(R.id.DialogButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do something
Bundle bundle = new Bundle(); //bundle is like the letter
bundle.putString ("user",userName ); //arg1 is the keyword of the txt, arg2 is the txt
bundle.putString ("email", email);
bundle.putString ("permission", permissions.get(cont));
Intent i=null;
i = new Intent (MyItemizedOverlay.class, Locate.class);
i.putExtras(bundle);
startActivity(i);
}
});
//now that the dialog is set up, it's time to show it
dialog.show();
}
}catch(Exception e){}
return true;
}
}
The Intent javadoc clearly show that the first arg has to be a Context (extended by activity) and the second one the class of the activity you're trying to launch. In your case, you'll need to do :
Intent intent = new Intent(mContext, AllActivity.class);
mContext.startActivity(intent);
generally, Intent gets in one of its constructor Context as first parameter and an Activity class as the second one. So, do the following:
Intent intent = new Intent(mContext, AllActivity.class);
mContext.startActivity(intent);
To an intent constructor it should pass A Context of the application package implementing this class, check this. it is not the intent.
It must be some Activity, say MyClass that using your MyItemizedOverlay class. Best thing to do is declare a static Context say myContext there and declare its value as myContext = MyClass.this; in onCreate. Then you can declare intent like this
new Intent (MyClass.myContext , Locate.class);