When to use "new" keyword android API - java

I am new to programming and trying to understand why sometimes it appears that objects are instantiated without a "new" keyword. For instance the basic tutorial app from google's android tutorial:
In the "Build an Intent" example, an Intent is created using the new keyword:
/** Called when the user taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
...
}
But later in "Display the Message", they make an Intent object this way if I am understanding correctly:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
...
}
And use the getIntent() method. Also, where is getIntent() method defined? It is a method from the Intent class?
Also on the previous section (https://developer.android.com/training/basics/firstapp/starting-activity.html) they make a new editText but I still don't understand why the "new" keyword isn't used:
EditText editText = (EditText) findViewById(R.id.editText);
Thanks for any help.

Good to learn that you want to start learning code.. I have added the solutions to your two questions, best is to just keep going and then everything will start to look logical, step by step.. The beginning is the hardest..
Intent intent = getIntent();
This instantiates an Intent object, the value comes from the function getIntent().. In the following link you can find that it is a method from the class Activity and returns the intent that started this activity.
https://developer.android.com/reference/android/app/Activity.html
EditText editText = (EditText) findViewById(R.id.editText);
This is a referral to a field "editText", defined in your Layout File.
You refer to the ressource in the layout..
Better and clear is to use another naming..
EditText "how you want to name the field" = (EditText) findViewById (R.id."name of the field in the layout")
As suggested below, try to take some basic classes online, watch some tutorials and hang in there!
Good luck!

Related

Passing data from one view to another using intents

I know there are other questions that have already been asked on this topic and I've already looked through a lot of them and tried their answers but none of them have worked.
I've got 2 activities, MainActivity and Main2Activity (that was the given name) (I'll refer to them as 1 and 2 respectively) each with their own respective XML files. What I'm trying to do is have a user enter something into an EditText field on 2 and then when they press enter, what they entered will appear in a TextView on 1. I'm trying to first get it to work when they press a button but it refuses to work. The ultimate goal is for it to get it to get transferred to 1 when they press/tap the enter key on the keyboard that pops up, so if it's easier to just skip the button and go straight to the enter key then by all means.
Any help that I can get is greatly appreciated. I'll put my (relevant) code as well as a couple screenshots below. Thank you.
Java code for 2 (Main2Activity):
public class Main2Activity extends AppCompatActivity {
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
et = (EditText) findViewById(R.id.editText);
}
EditText text;
public void CLICK_THIS (View v)
{
Intent intent = new Intent();
intent.putExtra("TextValue", et.getText().toString());
intent.setClass(Main2Activity.this, MainActivity.class);
startActivity(intent);
}
Intent intent = getIntent(); //i honestly forgot what this line is doing here
//i think it's here from some other thing i was trying to do and i just forgot to delete it.
}
Java code for 1 (MainActivity):
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
view = (ImageView) findViewById(R.id.imageView3);
backgroundImageName = String.valueOf(view.getTag());
TextView text = (TextView) findViewById(R.id.textView2);
String s = getIntent().getStringExtra("TextValuie");
text.setText(s);
}
Screenshot 1 (this is what MainActivity (1) looks like):
The text that's highlighted is just to show where the TextView is. it's "not supposed to be here".
Screenshot 2 (this is what Main2Activity (2) looks like):
Screenshot 3 (this just shows the keyboard) (ultimately the user would type something into the "Enter Your Text Here" and then press the Check mark and it would appear where the highlighted text is in 1 instead of clicking the button in 2 for that to happen). If I've confused anyone at any point please don't hesitate to ask for more information.
First of all you are retrieving the input using a wrong label "TextValuie" instead of "TextValue"
The other thing is that are you entering the text that on Button Click the EditText can get the entered value or the default would be an empty string?
You can always debug and put a break point on the intent to see the data that you are getting back from the activity.

Passing textview value across activities

I am trying to pass a value to a text view into a different activity but only when the button in the activity is clicked.
Here is the activity I am trying to set the text...
public static Button yes;
public static final String TEST_KEY = "test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question19);
yes = (Button) findViewById(R.id.finalYes);
yes.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent myIntent = new Intent(v.getContext(), Question13Activity.class);
startActivity(myIntent);
Intent i = new Intent(Question12Activity.this, HighRiskActivity.class);
i.putExtra(TEST_KEY, "SOME STRINGSSS");
}
});
Here is the HighRiskActivity that is the destination for updating the textview's value...
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.high_risk);
t = (TextView) findViewById(R.id.abusedOrNah);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
String value = extras.getString(TEST_KEY);
t.setText(value);
}
My problem is that no text is printing at the desired activity, am I passing in the wrong data?? Any help would be amazing, this is the last step to the app that I am creating :D
UPDATE
I do not want the Question12Activity to be directed to the HighRiskActivity when the button is clicked. I want it to go to the next activity but still be able to pass the text onto the HighRiskActivity once the button is clicked. Sorry for the confusion, hopefully that makes more sense :)
Try to pass data this way:
Intent i = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“test”, "Data you want to pass");
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
Now in your SecondActivity class you retrieve data as below:
Bundle bundle = getIntent().getExtras();
//get the data…
String stuff = bundle.getString(“test”);
I don't know what exactly you are trying to achieve by starting the first activity with the statements below
Intent myIntent = new Intent(v.getContext(), Question13Activity.class);
startActivity(myIntent);
But if the Activity you want to start is the HighRiskActivity then the following should fix your issue:
Get rid of the statements related to the Question13Activity mentioned above.
and add the call to start the actual HighRiskActivity like below:
Intent i = new Intent(Question12Activity.this, HighRiskActivity.class);
i.putExtra(TEST_KEY, "SOME STRINGSSS");
startActivity(i); //This line is important to start the new Activity.
So, I guess your major issue here is you didn't start the activity with the startActivity(i); call.
In Activity A you are using the internal intent bundle that is not public to you and private to the intent. In the Activity B you are asking the intent to instead look for a bundle that you provided yourself.
Try something like this in your Activity A
Intent intent = new Intent(context, YourActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("EXTRA1", "string data");
intent.putExtra(TEST_KEY, bundle);
startIntent(intent);
Here is a good writeup on the subject (see answer) Advantages of using Bundle instead of direct Intent putExtra() in Android
You dont need to define two intents in order to connect two Activities. Put the following inside onClick method
Intent i = new Intent(Question12Activity.this, HighRiskActivity.class);
i.putExtra(TEST_KEY, "SOME STRINGSSS");
startActivity(i);

AutoCompleteTextView wont work as EditText did

I replaced an EditText with an AutoCompleteTextView in my app to make things a little more user friendly, but I am having an error.
In the app, the user types in the name of a plant, and then clicks a button to be taken to a new activity where some information about the plant is displayed.
The error: the app crashes after I press the button to be taken to the next activity after the user types in the name of the plant. This didnt happen when I still had an EditText. Perhaps I am using the AutoCompleteTextView wrong?
Heres the relevant code:
public class Main2Activity extends AppCompatActivity {
AutoCompleteTextView edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//this is the AutoComplete
AutoCompleteTextView edit = (AutoCompleteTextView) findViewById(R.id.et_item);
//this is the list of suggestions for the AutoComplete
String[] items = getResources().getStringArray(R.array.items_array);
java.util.Arrays.sort(items);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
edit.setAdapter(adapter);
//this is the method that is called when the button is pressed
public void find(View view) {
String name = edit.getText().toString();
//basically, whatever is typed into the AutoComplete is turned into a string, and
//if the string matches one of the existing plants, the user is taken to
//the next activity
if(name.equalsIgnoreCase("Sunflower")){
Intent intent = new Intent(this, Sunflower.class);
startActivity(intent);
}
else if(name.equalsIgnoreCase("Cactus")){
Intent intent = new Intent(this, Cactus.class);
startActivity(intent);
}
Can anyone see why this does not work?
Change below:
AutoCompleteTextView edit = (AutoCompleteTextView) findViewById(R.id.et_item);
To:
edit = (AutoCompleteTextView) findViewById(R.id.et_item);
Your autocomplete textview scope is limited to onCreate() and
edit.getText().toString();
You are trying to get text from it which is not initialized yet. So it will get null pointer exception.

Creating a menu but one of the two buttons does not properly work

public class SuperActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button registerButton = (Button) findViewById(R.id.register_button);
registerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(SuperActivity.this, Register.class);
startActivity(myIntent);
}
});
Button loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(SuperActivity.this, Login.class);
startActivity(myIntent);
}
});
}
}
My register buttons works but not the login button. Is something wrong with my code?
The code posted looks fine. What exactly doesn't work? Do you get an error?
Since you mention it works for 'register' but not for 'login', you may want to double check if you didn't forget to add Login to your manifest.
Is button with id login_button declared in main layout? If I had to guess this button is not declared in main layout is declared somewhere else.
double check if button with id login_button declared in main layout
Since you are not posting your logcat view,it's very difficult to see where the problem this.I'm suggesting you few things which you should make sure that are inplace as said by me.If not then please correct them and let me know if that solved your problem or not.
Firstly,you should make sure that you have declared a button with same id in your main.xml file.It will look something like this:
<button android:id="#+id/login_button" >
</button>
Secondly you should make sure that you have declared your Login.class in your AndroidManifest.xml file.It will look something like this:
<application>
<activity android:name=".Login"></activity>
</application>
Check if these things are in place or not.
Have you declared all the activities? ;)

Android get different content in single activity

actually I'm searching a way to show different content in one activity everytime when it's created.Here is what actually I'm thinking to do but not really sure if there is a way and how can I do it. Basically I have two activities. The first one contains a listview with 100 elements on it.I want to be able to show different content in activity 2 when I click a listview item in Activity 1. I need to be able to change two textviews and one imageview.
Any suggestions how can I do that? Thanks in advance!
You want to use Intents to pass Payload between your Activitys.
On Activty1 you make a new Intent like:
Intent myIntent = new Intent(view.getContext(),
Activty2.class);
myIntent.putExtra("detailtext", ((TextView) view).getText());
startActivityForResult(myIntent, 0);
the putExtra Method is for your Payload.
then in Activty2 you can extract the Intent with:
getIntent().getStringExtra("detailtext"));
hope that helps
Do somethins like this :
Activity 1:
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("someKey","someValue");
startActivityForResult(Intent, 0);
Activity 2:
String i = getIntent().getStringExtra("someKey"));
TextView txt = (TextView) findViewById(R.id.textView); //your textview's id
txt.setText(i);
That should work!

Categories