I have an application that gets your current location. It will return your current address, latitude and longitude. When you click convert it takes you to a new class.
I want to get latitude and longitude (if it has something) into a textView in another class.
FIRST CLASS
public class MainActivity extends AppCompatActivity {
private static Button newWindowBtn; //new window button
Button btnShowLocation;
GPSTracker gps;
Double latitude;
Double longitude;
String addressStr;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shareIt();
}
});
final TextView address = (TextView)findViewById(R.id.textView);
onClickButtonListener(); //NEW WINDOW CLICK LISTENER
btnShowLocation = (Button) findViewById(R.id.show_location); //GPS BUTTON
final Geocoder geocoder = new Geocoder(this,Locale.ENGLISH);
btnShowLocation.setOnClickListener(new View.OnClickListener()
{ //GPS CLICK LISTENER
#Override
public void onClick(View v) { //SHOWS LOCATION
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
try{
List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);
if(addresses != null)
{
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex();i++){
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
address.setText(strReturnedAddress.toString() + "Latitude: " + latitude + "\nLongitude: " + longitude);
addressStr = strReturnedAddress.toString();
}
else
{
address.setText("No address returned");
}
}
catch(IOException e){
e.printStackTrace();
address.setText("Can't get address");
}
}else{
gps.showSettingsAlert();
}
}
});
}
SECOND CLASS
public class secondActivity extends AppCompatActivity {
Button convertBtn;
TextView latitudeTxt;
TextView longitudeTxt;
TextView latitudeDMS;
TextView longitudeDMS;
convertTo convert = new convertTo();
MainActivity mainActivity = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shareIt();
}
});
convertBtn = (Button) findViewById(R.id.convertBtn);
latitudeTxt = (TextView)findViewById(R.id.latitudeTxt);
longitudeTxt = (TextView)findViewById(R.id.longitudeTxt);
latitudeDMS = (TextView)findViewById(R.id.latitudeDMS);
longitudeDMS = (TextView)findViewById(R.id.longitudeDMS);
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
So I would want latitudeTxt to have the latitude from the previous screen (first class). I'm a student and trying to learn.
I've tried adding this to the first class:
secondActivity secondActivity = new secondActivity();
secondActivity.latitudeTxt.setText(latitude);
This didn't work.
I tried in the second class
MainActivity mainActivity= new MainActivity();
latitudeTxt.setText(mainActivity.latitude);
This approach is totally wrong and discouraged by Android.
MainActivity mainActivity= new MainActivity();
never EVER do that.
What you in fact are looking for is sharing data between activities, (there are a lot of questions like this in the community)
in the fisrt class (actually activity) use this as ref.:
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
and in the second:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
Send the latitude ,longitude values from 1st class to 2nd using bundle extras. Extract the value in 2nd class and set the values to the respective text view.
You should not create Objects of Activities like this,
MainActivity mainActivity= new MainActivity();
Activities are started by using Intents and if you need to refer to current object of your activity then you can do it by MainActivity.this.
And as far as, "This didn't work." is concerned, that is because you are creating a new object of your Activity class (which is correct syntax wise). And the new object will have its own copy of instance variables. So it will not be having values of already existing Activity object (which is shown to you).
To pass your values from say, FirstActivity to SecondActivity, do something like,
FirstActivity
Intent secondActivity = new Intent(FirstActivity.this, SecondActivity.class);
secondActivity.putExtra("latitude", value);
secondActivity.putExtra("longitude", value);
startActivity(secondActivity);
Then in SecondActivity
Intent intent = getIntent();
String latitude = intent.getStringExtra("latitude");
String longitude = intent.getStringExtra("longitude");
Related
I'm kind of new to android. I want to get an int value id(id of dynamically generated buttons) from class MainPage into class Note when a button is clicked. but the value of id always turns to zero in Note class.
here's the summerized code:
MainPage class:
public class MainPage extends AppCompatActivity {
public int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int j=0; j<allnotes.size(); j++) {
//generating buutons
final Button preview_text = new Button(this);
preview_text.setId(j)
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id=v.getId();
startActivity(new Intent(MainPage.this, Note.class));
}
});
}
}
}
Notes class:
public class Note extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
MainPage obj=new MainPage();
int id=obj.id
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout,Integer.toString(id) , 10000);
mySnackbar.show();
}
in snackbar message, id is always zero.
You need to add the id to the Intent you use to start the Note activity. You do this by using Intent.putExtra(...) and in Note you retrieve it via getIntent().getIntExtra(...)
Here I implemented #Riccully Answer in your code.
MainPage.java
preview_text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//getting id of the clicked button
id = v.getId();
Intent intent = new Intent(MainPage.this, Note.class);
intent.putExtra("id_value", id);
startActivity(intent);
}
});
Note.java
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
int id = getIntent().getIntExtra("id_value", 0);
View parentLayout = findViewById(android.R.id.content);
Snackbar mySnackbar = Snackbar.make(parentLayout, Integer.toString(id), 10000);
mySnackbar.show();
}
we can do this via intent Because Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services, etc.
In Our case, we can send the v.getId() to Note.java, viaputExtra
intent.putExtra("view_id",v.getId());
and receive the value in Note.java by using
getIntent().getIntExtra("view_id", 0);
Problem: I cannot pass the rating value/data from the rating bar to another intent. It only shows me this instead of the value/data from the rating bar.
Rating: MainActivity#79b604
I think the error is that it did not properly get the value from the rating bar or it did not pass the value correctly. Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
String rating_float = "0.0";
private TextView txtRatingValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rating_float = String.valueOf(rating);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Context context = getApplicationContext();
CharSequence text = "";
Intent intent_rating = new Intent(this, SecondActivity.class);
intent_rating.putExtra("rating_float", toString());
startActivity(intent_rating);
return super.onOptionsItemSelected(item);
}}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView Msg;
String PassedValue = null;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
PassedValue = getIntent().getStringExtra("rating_float");
Msg = (TextView) findViewById(R.id.Msg);
Msg.setText("Dimension: 479\nFormat: JPEG\nSize: 360x360\nRating: " + PassedValue);
}
Questions:
Am I doing the right way on getting the value for the rating bar?
How to pass the value/data from the rating bar into the next activity/intent and how to get it from the SecondActivity.java?
That is because you pass the result of MainActivity.toString() to your second activity
Instead of
intent_rating.putExtra("rating_float", toString());
you should presumably write
intent_rating.putExtra("rating_float", this.rating_float);
You are receiving it well but not sending what you have to.
Just use this:
intent_rating.putExtra("rating_float", rating_float);
First you need to save your value into the putExtra of the intent you use to go to the another activity
intent_rating.putExtra("rating_float", rating_float);
to get the value in the SecondActivity you just need to do this wherever you need the value.
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String rating_value =(String) b.get("rating_float");
}
Simple and Clear Solution
//1stActivity
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float rating = rate.getRating();
Intent intent = new Intent(ContactActivity.this,RatingIntentSOF.class);
Bundle bundle = new Bundle();
bundle.putFloat("totalRating",rating);
intent.putExtras(bundle);
startActivity(intent);
//2nd Activity, get the data of 1st Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating_intent_sof);
TextView textView = (TextView) findViewById(R.id.text);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
float totalRating = bundle.getFloat("totalRating");
textView.setText(String.valueOf(totalRating));
}
I have been trying to get a string to go from one java class to another for a project of mine. The code I have been experimenting with is not working. When I press the button, I know it opens the other Java class because it creates the other layout, but it doesn't show the string. Please help me.
First Java Class:
public class MainActivity extends AppCompatActivity {
private Button button;
Context context;
private EditText editText;
String number = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString() != null) {
String value = "value";
Intent secondscreenIntent = new Intent(context, SecondScreenJ.class);
secondscreenIntent.putExtra("Number", editText.getText().toString());
startActivity(secondscreenIntent);
}
}
});
}
}
Second Java Class:
public class SecondScreenJ extends Activity {
String number = null;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
textView = (TextView) findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if (extras != null){
number = extras.getString("number");
}
textView.setText(number);
}
}
you are putting "Number" as key but, in your second activity you are trying to retrieve "number"
so change number to Number and it will work.
Its case Sensitive.
Don't make your keys hard-coded in that way.
Just declare public static variable in MainActivity and use it from SecondScreenJ
public class MainActivity extends AppCompatActivity {
private Button button;
Context context;
private EditText editText;
public static String NUMBER_KEY = "Number";
String number = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString() != null) {
String value = "value";
Intent secondscreenIntent = new Intent(context, SecondScreenJ.class);
secondscreenIntent.putExtra(NUMBER_KEY , editText.getText().toString());
startActivity(secondscreenIntent);
}
}
});
}
}
Second Java Class:
public class SecondScreenJ extends Activity {
String number = null;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
textView = (TextView) findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if (extras != null){
number = extras.getString(MainActivity.NUMBER_KEY);
}
textView.setText(number);
}
}
Beware when using the key for putting and getting the extras. They're case sensitive. Replace "number" with "Number" in your second activity.
I develop a simple app with cards with 2 textViews. Have just 2 activities. On the second activity i put data and send it to MainActivity for showing it on the card.
When i create the first card with data, everything good, but if i want to create another one with another data, i get on MainActivity exactly the same card with data from the first time. `
MainActivity:
public class MainActivity extends ActionBarActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
public ArrayList<DataObject> dataObject;
FloatingActionButton fab;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataObject = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter(dataObject);
recyclerView.setAdapter(adapter);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddNewCard.class);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data==null)
return;
String title = data.getStringExtra("title");
String text = data.getStringExtra("text");
dataObject.add(i, new DataObject(title, text));
i++;
}
}
And the code of the second activity:
public class AddNewCard extends ActionBarActivity {
TextView mTitle, mText;
Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_card);
initElements();
}
private void initElements() {
mTitle = (TextView) findViewById(R.id.editTitle);
mText = (TextView) findViewById(R.id.editGoal);
mButton = (Button) findViewById(R.id.sendButton);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("title", mTitle.getText().toString());
intent.putExtra("text", mText.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
});
}
}
Also i have DataObject class with 2 Strings, constructor and getters and recycler adapter which works fine.
An easier, faster, but not stronger way to pass data between activities is to use a public static classs with static variables. As I said before, this is maybe not the right way to do it, but it works. Is not rocket science, but it is very useful if you create small projects.
I have two views named: first_view and second_view.
The first view consists of a button and an editable text view. The second view consists of a single text view.
In my first view, I want to put a number in the datable text view. As I click the button, it should display the number in the second view.
How can I code Java classes for the two views?
I am assuming that you want to setText within the same Activity, if not so then tell me, Ill change my answer.
Here is what you have to do.
public class MyActivity extends Activity {
Button btn;
EditText et;
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.yourbtnID);
et = (EditText) findViewById(R.id.yourEtID);
tv = (TextView) findViewById(R.id.yourtvID);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myText = et.getText().toString();
tv.setText(myText);
}
});
}
}
If you want to pass text between two Activities then use Intent.
In your current Activity do this.
Intent i = new Intent(YourCurrentActivity.this, YourNextActivity.class);
String str = yourEditText.getText().toString();
i.putExtra("edittextvalue" , str);
startActivity(i);
Then in next Activity do this..
Bundle extras = getIntent().getExtras();
String myEtText;
if (extras != null) {
myEtText = extras.getString("edittextvalue");
yourTextView.setText(myEtText);
}
if Two Views in the same Activity , you can do that
Button btn;
EditText txtInput;
TextView txtShow;
//btn=firstView.findViewWithTag(tag)
btn=firstView.findViewById(R.id.**);
txtInput=firstView.findViewById(R.id.**);
txtShow=secondView.findViewById(R.id.**);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String input=txtInput.getText().toString();
txtShow.setText(input);
}
});
if you have Two Activity :
Button btn;
EditText txtInput;
String VALUE_KEY="show";
private void test()
{
btn=(Button)findViewById(R.id.**);
txtInput=(Button)findViewById(R.id.**);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String input=txtInput.getText().toString();
Intent intent=new Intent(this, AnotherActivity.Class);
intent.putExtra(VALUE_KEY, input);
}
});
}
On the AnotherActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=this.getIntent();
String value=intent.getStringExtra(VALUE_KEY);
TextView view=(TextView)findViewById(R.id.txt);
view.setText(value);
}
Try this,
put your value in String: String et_str = EditText.getText().toString();
When you call the other intent,
Intent i = new Intent(first_view .class, second_view.class);
i.putExtra("REF",et_str);
StartActivity(i);
In The Second View, get this value using getExtra()