I want to use the value of 2 editTexts from one activity in another. Here is my code so far. I am getting:
java.lang.NullPointerException.
The Code:
public class AddJob extends AppCompatActivity{
// vars
private BottomNavigationView bottomNavigationView;
private EditText editTextLat, editTextLng;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_job);
TextView textView = findViewById(R.id.activityTitleAddJob);
textView.setText("Add a Job");
editTextLat = findViewById(R.id.editTextLat);
editTextLng = findViewById(R.id.editTextLng);
}
public int getLatitude() {
return new Integer(editTextLat.getText().toString());
}
public int getLongitude() {
return new Integer(editTextLng.getText().toString());
}
}
The Stack Trace:
Here is the code snippet from the map class:
AddJob aj = new AddJob();
int lat = aj.getLatitude();
int lng = aj.getLongitude();
Toast.makeText(aj, lat + " " + lng, Toast.LENGTH_LONG).show();
Please read about the Activity lifecycle. You should never
create an Activity directly with
new MyActivity()
This will not launch any of the lifecycle events (onCreate, etc...) or bind it to a context, set a view hierarchy on it, or do any of the regular Activity things you may be expecting. Your program is returning null because onCreate is never called on the activity, and if you were to simply try to call it yourself it would likely crash.
If you want data from one activity to be available in another activity, an easy way to achieve this is to save the data in SharedPreferences in the AddJob activity (whenever the values are updated) and access it in MapActivity from the SharedPreferences. You can also pass the data from one Activity to the next by adding data to the Intent when you launch it.
One advantage to using SharedPreferences here is that the user's choices will be saved from one app session to the next, and if you have multiple things that can launch the MapActivity they don't have to keep passing that data to it.
hello would it not be better using an Intent
Intent i = new Intent(MainActivity.this, NEXTActivity.class);
i.putExtra("latitude", lat);
i.putExtra("longitude", lng);
startActivity(i);
NEXTActivity
Bundle extras = getIntent().getExtras();
double latitude = extras.getDouble("latitude");
double longitude = extras.getDouble("longitude");
You shouldn't create activity objects, you can start activity with Intent and pass data through it. Check out the relevant answer in the link below:
https://stackoverflow.com/a/2091482/10116426
It seems that you are instantiating the AddJob class. This may raise problems on the back-stack of android, which may create lifecycle management problems. So, as mentioned by #NoobAndroid, it is better to use the recommended way not to run into unexpected errors.
use this code .
package com.example.cloudanalogy.introscreen;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private EditText editTextLat, editTextLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.activityTitleAddJob);
textView.setText("Add a Job");
editTextLat = findViewById(R.id.editTextLat);
editTextLng = findViewById(R.id.editTextLng);
}
public int getLatitude() {
return Integer.parseInt(editTextLat.getText().toString());
}
public int getLongitude() {
return Integer.parseInt(editTextLng.getText().toString());
}
public void onclick(View view) {
int lat = getLatitude();
int lng = getLongitude();
Toast.makeText(this, ""+lat+" and "+lng, Toast.LENGTH_SHORT).show();
}
}
Related
I'm a beginner in android studio and i want to write a code with 3 activities.
1st is for starting the app.2nd is for showing an English word and 3rd is for showing the English word and a description of it in two texts.
I want to transfer data of English word itself and its description and the number of the word to show the words one by one.
I wrote the code with help of tutorial clips but it ain't work and in 3rd activity shows nothing.
these are my codes:
main activity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View view)
{
Intent i = new Intent(this,ActivityOne.class);
startActivity(i);
}
}
ActivityOne
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ActivityOne extends AppCompatActivity {
int a=0;
String E , P;
private Button show;
private TextView Eword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
Eword = (TextView) findViewById(R.id.Eword);
show = (Button) findViewById(R.id.show);
}
public void show(View view)
{
Intent intent = new Intent(this,ActivityTwo.class);
startActivity(intent);
int a = getIntent().getIntExtra("counter",0);
Eword.setText(Eng[a]);
E = Eword.getText().toString();
P = Fa[a];
a++;
intent.putExtra("counter",a);
intent.putExtra("EWord",E);
intent.putExtra("PWord",P);
}
private String[] Eng = {
"Abundance",
"Anxiety",
"Bruxism",
"Discipline",
"Drug Addiction"
};
private String[] Fa = {
"Abundance Description",
"Anxiety Description",
"Bruxism Description",
"Discipline Description",
"Drug Addiction Description"
};
}
ActivityTwo
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class ActivityTwo extends AppCompatActivity {
TextView Eng , Fa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
Eng = (TextView) findViewById(R.id.eng);
Fa = (TextView) findViewById(R.id.fa);
// recieve data from activity one
String EWord = getIntent().getStringExtra("EWord");
String PWord = getIntent().getStringExtra("PWord");
int a = getIntent().getIntExtra("counter",0);
Eng.setText(EWord);
Fa.setText(PWord);
}
public void iknow(View view)
{
Intent myIntent = new Intent(this,ActivityOne.class);
startActivity(myIntent);
int a = getIntent().getIntExtra("counter",0);
myIntent.putExtra("counter",a);
}
public void idknow(View view)
{
Intent myIntentTwo = new Intent(this,ActivityOne.class);
startActivity(myIntentTwo);
int a = getIntent().getIntExtra("counter",0);
myIntentTwo.putExtra("counter",a);
}
}
And it shows this result:
It is the third activity and it can clear the pretext that was set in design page but can not replace EWord or PWord
Can someone help me?????
(1) To get you started, you need to put your variables into the intent before you start the activity. (2). I don't think its a good idea to have activity one start two, which then can start one. It is better to just close second activity which then automatically returns to one. (3) To pass data back to the activity you are returning you need to startActivityForResult https://developer.android.com/training/basics/intents/result.html
activity one starts activity two using startActivityForResult. Activity Two returns an intent (which is the result intent) and activity one recieves this in onActivityResult.
check out this: Android: how to make an activity return results to the activity which calls it?
I'm having this peculiar problem in Android studio. I made this simple app, to understand screen rotation. I understand the concept when the screen rotates the Activity gets destroy, and recall the onCreate method. For you to save data you have to put it in a Bundle by Overriding the onSaveInstanceState method. I made an app with 2 buttons and a number in the middle. the number will change depending on what button is click. But for some reason, when I rotate the screen the number reset, but still kept the value it was on before the screen got to rotate. For Example, if I set the number to 5, and I rotate the screen the number goes to zero, but if I increase it, it goes to 6 if I decrease it goes 4. Somehow it still kept its value but reset to zero, I don't know why. Here's the code
package com.example.android.application;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button upButton, downButton;
TextView amount;
int change;
private static final String banza = "Bundle";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
change = savedInstanceState.getInt(banza);
}
upButton = (Button) findViewById(R.id.activity_main_up_button);
downButton = (Button) findViewById(R.id.activity_main_down_button);
amount = (TextView) findViewById(R.id.activity_main_textview_id);
upButton.setOnClickListener(this);
downButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == upButton) {
change++;
amount.setText(Integer.toString(change));
}
if (view == downButton) {
change--;
amount.setText(Integer.toString(change));
}
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(banza, change);
}
}
You missed the code of
amount.setText(Integer.toString(change));
in onCreate that's why it don't show value while rotating but have correct value when you increment or decrement.
I'm new to Android Studio and Java, currently I'm learning about intents and sending data/text from one activity to another. On the second activity I get "Cannot resolve symbol 'intent'" even though it's in onCreate field. What I'm trying to do is to have two text fields for first and last name, sending the text from first activity to the second one which will read it, and all done with onButtonClick method. I'm only trying to do the first name and the code looks like this MainAcitivty
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClicked(View view) {
EditText nameText = (EditText)findViewById(R.id.firstName);
TextView messageText = (TextView) findViewById(R.id.messageTextView);
if(nameText.getText().toString().trim().length() == 0){
messageText.setText("text here");
} else {
String textForSecondAcitivity = "your name is: " + nameText.getText();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, textForSecondAcitivity);
startActivity(intent);
`
The problem is the second Activity that gives me the error "Cannot resolve symbol 'intent'". And here is the code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent scIntent = getIntent();
String messageText = intent.getStringExtra("EXTRA_TEXT");
TextView messageView = (TextView)findViewById(R.id.textView);
messageView.setText(messageText);
}
It wont show the error here but it's int this line
String messageText = intent.getStringExtra("EXTRA_TEXT");
I apologize in advance because surely I messed up something bad, I'm a beginner and if you have some advice on what's the best way to do what I'm actually trying to accomplish feel free to tell me.
The app should look like this in the end 1.The first activity
1.The second one showing first name and last name
You have no local variable named intent
Replace it with scIntent
Here you are making it wrong
intent.putExtra(Intent.EXTRA_TEXT, textForSecondAcitivity);
instead you use this
intent.putExtra("EXTRA_TEXT", textForSecondAcitivity);
As a N00bie to android, I'm trying to build a simple map-app. I started out doing everything in the same class, but for obvious reasons that got out of hand, fast. So I wanted to split the class, with the base class as the main flow for the activity, and the subclass as the 'utility' class.
So I instantiate an Subclass object, and in the subclass's onCreate I start calling methods. These methods never run though. What am I doing wrong? As soon as I create the subclass object, the sub's onCreate should fire, no? And, is it even the smart way of doing this in a subclass, instead of a whole other class?
Thanks in advance!
Base class:
package com.example.TestMap;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class MyActivity extends Activity {
private GoogleMap mMap;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationClass locationClass = new LocationClass();
}
public void setMap(){
Log.i("TestMap", "setMap");
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
}
public void setCamera(Location location) {
Log.i("TestMap", "setCamera");
final LatLng locationLatLng = new LatLng( (location.getLatitude() ), location.getLongitude() );
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(locationLatLng) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
Subclass
package com.example.TestMap;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
public class LocationClass extends MyActivity implements LocationListener {
private LocationManager locationManager;
private String provider;
private List<String> providers;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TestMap", "LocationClass OnCreate");
GetProivder();
}
public void GetProivder (){
Log.i("TestMap", "LocationClass GetProivder");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(2);
provider = locationManager.getBestProvider(criteria, false);
providers = locationManager.getProviders(true);
Location location = locationManager.getLastKnownLocation(provider);
Log.i("TestMap", "providerlist = " + providers);
Log.i("TestMap", "getBestProvider = " + provider);
Log.i("TestMap", "Location = " + location);
if (location != null) {
Log.i("TestMap", "Provider " + provider + " has been selected.");
super.setCamera(location);
super.setMap();
} else {
Log.i("TestMap", "location is null.");
}
}
#Override
public void onLocationChanged(Location location) {
Log.i("TestMap", "onLocationChanged");
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("TestMap", "onStatusChanged");
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Log.i("TestMap", "onProviderDisabled");
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Your code
LocationClass locationClass = new LocationClass(); does not create it. It just makes an object of it, but it does not tie to the lifecycle and call the methods.
You need to start it with an intent to make it appear (and take the entire screen based on skimming your code). Android will fire the appropriate method calls when you do so.
Like this:
Intent intent = new Intent(this, LocationClass.class);
startActivity(intent);
More information can be found here: http://developer.android.com/training/basics/firstapp/starting-activity.html#StartActivity
It must be defined in your manifest too or it will crash. There are other noticeable oddities things in your code, do you want LocationClass to extend MyActivity and not Activity? Your LocationClass also does not call setContentView() in onCreate, so you're not going to see a UI (as far as I can tell), unless you wanted it through the extends part.
EDIT :
If you extend subclass and put this intent code in onCreate, you're probably going to crash, as it will call super() in MyActivity (calling onCreate() again as it's the superclass), and will keep making more intents to start the activity. You should not subclass MyActivity if that's what the 'parent' class is.
You should only subclass Activity or a global parent activity (e.g. in my project right now, I extend SpiceActivity, as they all use common components related to Spice).
The subclass' onCreate method should be called when it is created by Android (see Understanding the Lifecycle Callbacks), which for example happens when an Intent to that Activity is issued.
Edit: I just saw #Mgamerz answer and realised that line in your superclass Activity was where you were trying to make Android create the subclass Activity. This next paragraph is somewhat irrelevant now, but note that you do still need to add the subclass activity to the manifest file.
Are you sure you're application is actually starting the subclass Activity, or is it still starting the superclass Activity? You might have to have a look at your project's "AndroidManifest.xml" file and check that there's an <activity /> element corresponding to the subclass Activity.
I think splitting the class into a superclass and a subclass is sensible if the superclass has functionality which can/will be re-used by multiple subclass Activities. For example you might have subclass activities like DirectionsActivity and SearchActivity which have some common map-related activity provided by their superclass MapActivity. Even if you have only one subclass Acitivty now, it may still make sense to have a superclass and a subclass if you think you're likely to write additional map-related activities later on. I my opinion it's not sensible to split the class into a superclass and a subclass just because the single class was getting too long. If you do just want a helper class and you don't expect to have more MapActivity subclasses in the future, you could make a MapUtils class in the same package as the Activity class, which would define some static helper methods. For example, you could put your GetProvider method into such a helper class. Sketch example (note the package-private access of MapHelper):
class MapHelper {
static Location getProvider() {
// ...
return location;
}
// Other helper methods here
}
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
setCamera(MapHelper.getProvider());
setMap();
}
// Other activity methods here
}
Can I ask if someone knows how to pass the data entered from one activity to another activity? The string to be passed to that activity will be compared to the images in the database of the Android phone..
Here is the code sirs:
AlphabetConversion.java
package com.mobilebasedsignlanguage;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AlphabetConversionMenu extends Activity {
EditText et_conv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alphaconv);
Button alphaConv = (Button)findViewById(R.id.btn_alphaconv);
et_conv = (EditText)findViewById(R.id.et_convtxt);
alphaConv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String checkWord = et_conv.getText().toString();
Bundle word = new Bundle();
word.putString("key", checkWord);
Intent a = new Intent(AlphabetConversionMenu.this, AlphabetCompareClass.class);
a.putExtras(word);
startActivity(a);
}
});
}
}
Here is the java for the second activity
package com.mobilebasedsignlanguage;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class AlphabetCompareClass extends Activity {
String get;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabetcompare);
Bundle gotWord = getIntent().getExtras();
get = gotWord.getString("key");
TextView Word = (TextView)findViewById(R.id.textView1);
Word.setText(get);
for(int x = 0; x > gotWord.getString("key").length(); x++){
//if(gotWord.getString("key").charAt(0) == "SELECT * from " + TABLE_CONTACTS)
// Get Image from the Database
// Set it on Image View
// set timer 2 secs
}
};
}
The comments in the second activity I think I don't know how to code that. Really need someones help. Thank you very much.
Did you try to save information on the shared preferences?
Allows you you to save "key-value".
http://developer.android.com/reference/android/content/SharedPreferences.html
try this on AlphabetConversion.java
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String checkWord = et_conv.getText().toString();
Intent a = new Intent(AlphabetConversionMenu.this, AlphabetCompareClass.class);
a.putExtra("key",checkWord);
a.putExtras(word);
startActivity(a);
}
and in the onCreate of second activity
Bundle b;
b = this.getIntent().getExtras();
mssg = b.getString("key");
Select Statement will return the resultset object. If you want to compare it to the specific column then fetch the column name only. For comparing the string objects you can use String.compare method or simple == will be sufficient.
First, you should put it into extras in the first activity:
Intent intent = new Intent(this, AlphabetCompareClass.class);
intent.putExtra("STRING_KEY", yourString);
In the second activity you can take it from extras:
String yourString = getIntent().getExtras().getString("STRING_KEY");
Or you can use shared preferences to store information. It's more convenient if you should save info for more than one activity change.
In your first activity call like this :
Intent a = new Intent(AlphabetConversionMenu.this, AlphabetCompareClass.class);
a.putExtras("key", checkWord);
startActivity(a);
And in second activity get value like this
get = getIntent().getStringExtra("key",""); // here if no extra found then default "" return.