I am new on android und I try to transfer data between two Activities.
Eclipse tell me that the line:
Intent i = new Intent(this, PostDataActivity.class);
Constructor Intent is undefined. What can I do?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.ansehen);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GpsData(StartActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String mlat = String.valueOf(latitude);
// \n is for new line
Intent i = new Intent(this, PostDataActivity.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
You are trying to initialize your Intent from inside an OnClickListener. Hence, the this parameter you are passing to your constructor refers to the listener, and not your Activity.
To fix the problem use :
Intent i = new Intent(YourActivityName.this, PostDataActivity.class);
use
Intent i = new Intent(YourActivityName.this, PostDataActivity.class);
Related
I am trying to create maximum 6 line array of place names and LatLngs and then use an intent to send it to a map class where the user can select name. The name needs to still be tied to the LatLng so the map can centre and zoom to it.
I have added edited code below. I have a mix of putExtra and putParcelable as I'm trying anything to get a working prototype. Hopefully it makes some sense.
The Sending Class Geocode is this:
private void geocodeLocation(String gPlace) {
Geocoder gGeocoder = new Geocoder(this, Locale.getDefault());
try{
List<Address> results = null;
if(Geocoder.isPresent()){
results = gGeocoder.getFromLocationName(gPlace, numberOptions);
} else {
return;
}
Iterator<Address> locations = results.iterator();
String country;
int opCount = 0;
while(locations.hasNext()){
Address location = locations.next();
raw += location+"\n";
strAddressOutput[opCount] = location.getAddressLine(0) + ", " + location.getAddressLine(1) + country + "\n";
strLatOutput[opCount] = location.getLatitude();
strLongOutput[opCount] = location.getLongitude();
gLatLng = new LatLng(location.getLatitude(),location.getLongitude());
strLatLng[opCount] = gLatLng;
opCount ++;
}
for(int i = 0; i<opCount; i++){
}
} catch (IOException e){
}
The Sending Class Intent is this:
public void onConnected(Bundle bundle) {
if (!android.location.Geocoder.isPresent()) {
return;
}
if (gAddressRequested) {
geocodeLocation(gPlace);
Intent tdMap = new Intent(this, com.dm4_map_test.todos3maps.MainMap.class);
tdMap.putExtra(Constants.RETURNEDADDRESS, strAddressOutput);
Bundle args = new Bundle();
args.putString(Constants.PLACE, gPlace);
args.putParcelable(Constants.MAPCENTRE, gMapCentre);
args.putParcelableArray(Constants.LATLNGS, strLatLng);
tdMap.putExtra("bundle", args);
startActivity(tdMap);
}
}
The Receiving Class is this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map);
MapFragment mapFrag = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if (savedInstanceState == null) {
needsInit = true;
}
mapFrag.getMapAsync(this);
mPlace = (EditText) findViewById(R.id.txAddress);
mAddressList = (Spinner) findViewById(R.id.spinAddressList);
mPlace.setText(getIntent().getStringExtra(Constants.PLACE));
String[] recAddressAA = getIntent().getStringArrayExtra(Constants.RETURNEDADDRESS); // NULLS from Geocoder?
recAddressOutput = recAddressAA;
String testAddressOutput = Arrays.toString(recAddressAA);
Bundle bundleMapCentre = getIntent().getParcelableExtra("bundle");
mMapCentre = bundleMapCentre.getParcelable (Constants.MAPCENTRE);
Bundle bundleLatLng = getIntent().getParcelableExtra("bundle");
LatLng[] mLatLng = bundleLatLng.getParcelableArrayList(Constants.LATLNGS);
mAdapter = new ArrayAdapter<String>(MainMap.this, android.R.layout.simple_spinner_item, recAddressOutput);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mAddressList.setAdapter(mAdapter);
});
}
The line 'LatLng[] mLatLng = bundleLatLng.getParcelableArrayList(Constants.LATLNGS);' errors but I have stepped back to see if this a workable approach
Intent lets you pass through ints, doubles, strings, etc. but if you want to pass a custom object you will have to create the custom object implementing Parceable. You can see a little bit about how to do that here
In the Android application I'm working on, I have one activity where the user inputs data that is saved using SharedPreferences, and is used for certain calculations on the main activity. An issue I'm having is that after saving the data, the changes do not actually take effect until after the application is restarted. Is there a way I can make it so the variables associated with these SharedPreferences are updated before restarting?
Here is where I save the data in a separate activity.
saveBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedWeight", weightString).commit();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedAge", ageString).commit();
//Intent i = new Intent("com.williammiller.capstonelapv2.MainActivity");
//startActivity(i);
finish();
}
});
And here is where I'm checking in the main activity to see what they are
String age = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedAge", "25");
String weight = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedWeight", "200");
startBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "weight = " + weightInt + " age = " + ageInt, Toast.LENGTH_LONG).show();
}
});
You can use a BroadcastReceiver to achieve that. Do as following:
Register a BroadcastReceiver in your Main Activity:
public static final String UPDATE_ACTION = "yourpackage.update";
public static final String EXTRA_KEY_AGE = "key_age";
public static final String EXTRA_KEY_WEIGHT = "key_weight";
private BroadcastReceiver mReceiver;
// In the onCreate() method
mReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(UPDATE_ACTION)){
// Here you get the update data from another activity
String age = intent.getStringExtra(EXTRA_KEY_AGE);
String weight = intent.getStringExtra(EXTRA_KEY_WEIGHT);
}
}
};
registerReceiver(receiver, new IntentFilter(UPDATE_ACTION ));
// Add the following code to onDestroy() method
unregisterReceiver(mReceiver);
Send a broadcast in your "separate activity":
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
Intent intent = new Intent(MainActivity.UPDATE_ACTION );
intent.putExtra(MainActivity.EXTRA_KEY_AGE, ageString);
intent.putExtra(MainActivity.EXTRA_KEY_WEIGHT, weightString );
sendBroadcast(intent);
}
Update: Change part of the code to unregister the BroadcastReceiver when activity is destroyed.
I am simply trying to navigate on Another Activity from my FragmentActivity having GoogleMap there. I have following code for InfoWindowClickListener
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String distance[] = marker.getSnippet().split(" - ");
String distanceString = distance[0];
String idString = marker.getId();
String stationid = markershashmap.get(idString);
Toast.makeText(getApplicationContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent dockitdetailsIntent = new Intent(
getApplicationContext(), AnotherActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
dockitdetailsIntent.putExtra("stationId", stationid);
dockitdetailsIntent.putExtra("distance", distanceString);
parentActivity.startChildActivity("Activity Name",
dockitdetailsIntent);
}
});
But when I click the InfoWindow, my device hangs and then I have to force close the not responding app. When i use startActivity(dockitdetailsIntent) it works fine but Tab removes. But I want to use the Next Activity into the similar tabs. Please suggest me why my device hangs out and doesn't respond.
Create Handler and Put Intent logic into this like below:
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker m1) {
// TODO Auto-generated method stub
try{
String[] str2=str.split("contactID");
Message mesg = new Message();
Bundle b = new Bundle();
b.putString("contact_id", str2[1]);
mesg.setData(b);
handler.sendMessage(mesg);
}catch(Exception e){
e.printStackTrace();
}
}
});
And now create one handler like below:
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
Bundle b1 = new Bundle();
b1.putString("ContactID", b.getString("contact_id"));
b1.putBoolean("showBack", true);
Intent edit = new Intent(getParent(), ContactDetails2.class);
edit.putExtras(b1);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("ContactDetails2", edit);
}
};
Try this. It's working in my case
I'm new to Android and I'm just trying to pass two doubles from one activity to another. This question has been asked several different times on this site in several different ways, but something about my implementation is causing my app to force close. I think my problem may be with my "savedInstanceState" Bundle in the activity I'm trying to pass the variables to. I left out a lot of code obviously, but I included all the places where Bundles are used.
[EDIT] - I found a bad programming solution for what I need to do. I put public static variables in the receiving class and access them from the sending class. I realize this is bad programming, but it does what I want. Thanks to all who tried to help. I'm going to continue to try to do this the proper way.
Without the i.putExtra lines and any lines involving the Bundle extra, it works fine. Here's the code:
int lat = 0;
int lon = 0;
private void createNote() {
Intent i = new Intent(this, NoteEdit.class);
i.putExtra("lat", lat);
i.putExtra("lon", lon);
startActivityForResult(i, ACTIVITY_CREATE);
}
This is the activity I sent them to:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extra = getIntent().getExtras();
int lat = extra.getInt("lat");
int lon = extra.getInt("lon");
mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID) : null;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String lattitude = mLatText.getText().toString();
String longitude = mLonText.getText().toString();
String date = mDateText.getText().toString();
String time = mTimeText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body, lattitude, longitude, date, time);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body, lattitude, longitude, date, time);
}
}
This is how you should pass values.
Bundle bundle = new Bundle();
bundle.putString("str1", str1);
bundle.putInt("int1", int1);
bundle.putDouble("double1", double1);
Intent i = new Intent(this, Activity2.class);
i.putExtras(bundle);
startActivityForResult(i);
And this is how you get them in next activity
int int1 = getIntent().getExtras().getInt("int1")
String str1 = getIntent().getExtras().getString("str1")
double double1 = getIntent().getExtras().getDouble("double1")
does this clear your doubts?
The looks fine, you problem is someplace else.
Try adding prints before setting the intent to make sure your key and value are what you really think they are
int name = getIntent().getExtras().getInt(key);
You are calling startActivityforresult.so try getting the bundle in onActivityResult not in oncreate.you can override this onActivityResult
I think this is the problem try getting the bundle using this.you will get the value to this new variable.
My main class is principal extends activity
with this code call MiMapa class:
switch(v.getId()){
case R.id.presentLocation_button:
Log.i("Button","Button 3 pushed");
Intent m = new Intent(this, MiMapa.class);
startActivity(m);
break;
work perfect.
MiMapa class is :
public class MiMapa extends MapActivity implements LocationListener {
I have this method:
public void setOverlay1(){
int foodLength = foodItem.length;
// Create itemizedOverlay2 if it doesn't exist and display all three items
if(! foodIsDisplayed){
mapOverlays = mapView.getOverlays();
drawable1 = this.getResources().getDrawable(R.drawable.golf);
itemizedOverlay1 = new Ofertas(drawable1);
// Display all three items at once
for(int i=0; i<foodLength; i++){
itemizedOverlay1.addOverlay(foodItem[i]);
}
mapOverlays.add(itemizedOverlay1);
foodIsDisplayed = !foodIsDisplayed;
// Remove each item successively with button clicks
} else {
itemizedOverlay1.removeItem(itemizedOverlay1.size()-1);
if((itemizedOverlay1.size() < 1)) foodIsDisplayed = false;
}
// Added symbols will be displayed when map is redrawn so force redraw now
mapView.postInvalidate();
}
now the problem.
into Ofertas class ( public class Ofertas extends ItemizedOverlay {)
in the tap method My code is:
protected boolean onTap(int i){
GeoPoint gpoint = myOverlays.get(i).getPoint();
double lat = gpoint.getLatitudeE6()/1e6;
double lon = gpoint.getLongitudeE6()/1e6;
String toast = "Title: "+myOverlays.get(i).getTitle();
toast += "\nText: "+myOverlays.get(i).getSnippet();
toast += "\nSymbol coordinates: Lat = "+lat+" Lon = "+lon+" (microdegrees)";
Toast.makeText(principal.context, toast, Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.setClass(principal.context,Popup.class);
principal.context.startActivity(intent);
intent.putExtra("message", "My popup number " + mCount);
mCount++;
//startActivity(intent);
return(true);
}
but don't work.
I had tried
intent.setClass(MiMapa.context,Popup.class);
or
intent.setClass(principal.this,Popup.class);
or
intent.setClass(MiMapa.this,Popup.class);
Nothing work.
please, help me.
thanks
Pass your Activity into your ItemizedOverlay (e.g., via the constructor) and use that for your startActivity() call.