My question is if it is possible to write code before setContentView() in the onCreate() method of the main Activity. In the code below I want to call the setVariables() before setContentView() but this causes my application to crash. If I call setVariables() after setContentView(), it works fine. Why is this?
package com.oxinos.android.moc;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
public class mocActivity extends Activity {
/** Called when the activity is first created. */
public static String prefsFile = "mocPrefs";
SharedPreferences mocPrefs;
public Resources res;
public CheckBox cafesCB, barsRestCB, clothingCB, groceriesCB, miscCB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVariables();
setContentView(R.layout.main);
mocPrefs = getSharedPreferences(prefsFile,0);
}
private void setVariables(){
res = getResources();
cafesCB = (CheckBox) findViewById(R.id.cafesCheckBox);
barsRestCB = (CheckBox) findViewById(R.id.barsRestCheckBox);
clothingCB = (CheckBox) findViewById(R.id.clothingCheckBox);
groceriesCB = (CheckBox) findViewById(R.id.groceriesCheckBox);
miscCB = (CheckBox) findViewById(R.id.miscCheckBox);
}
public void submitHandler(View view){
switch (view.getId()) {
case R.id.submitButton:
boolean cafes = cafesCB.isChecked();
boolean barsRest = barsRestCB.isChecked();
boolean clothing = clothingCB.isChecked();
boolean groceries = groceriesCB.isChecked();
boolean misc = miscCB.isChecked();
SharedPreferences.Editor editor = mocPrefs.edit();
editor.putBoolean(res.getString(R.string.cafesBool), cafes);
editor.putBoolean(res.getString(R.string.barsRestBool), barsRest);
editor.putBoolean(res.getString(R.string.clothingBool), clothing);
editor.putBoolean(res.getString(R.string.groceriesBool), groceries);
editor.putBoolean(res.getString(R.string.miscBool), misc);
editor.commit();
startActivity(new Intent(this, mocActivity2.class));
break;
}
}
}
You can execute any code you want before the setContentView() method as long as it doesn't refer to (parts of) the View, which isn't set yet.
Since your setVariables() method refers to the contents of the View, it can't be executed.
The setContentView() method sets the content of your XML file as the View, which is shown by the Activity.
You're calling setVariables() before you've specified any View to be shown.
That's why the error raises. The compiler doesn't know where that View belongs to. If you want to use a ResourceView, you have to set it first.
Related
I have 1 button for changing an image and a text.
I wanted to make that same button so that if I click AGAIN, it would change back to the original image and the text. However, 'TextView' and 'ImageView' in Java code would tell me, I have already defined. Therefore, I guess I can't re-define them within 1 button.
I ended up creating 2 buttons: 1 to change and 2nd one to return back. How can I just have one button to change and return images and text? HELP!
package com.example.android.cookies;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Called when the cookie should be eaten.
*/
public void eatCookie(View view) {
// TODO: Find a reference to the ImageView in the layout. Change the image.
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.after_cookie);
// TODO: Find a reference to the TextView in the layout. Change the text.
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("Im so full");
}
public void returnCookie(View view) {
ImageView imageView = (ImageView)
findViewById(R.id.android_cookie_image_view);
imageView.setImageResource(R.drawable.before_cookie);
TextView textView = (TextView) findViewById(R.id.status_text_view);
textView.setText("I'm so hungry");
}
}
]2
I have written a well maintained code for you. You can save current state.
I don't recommend boolean. Because if you take int you can save more states in future, whereas in boolean you can save only two states- true or false.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
ImageView imageView;
TextView textView;
Button button;
final int STATE_HUNGRY = 1;
final int STATE_FULL = 2;
int currentState = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.android_cookie_image_view);
textView = (TextView) findViewById(R.id.status_text_view);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (currentState) {
case STATE_FULL:
returnCookie();
break;
case STATE_HUNGRY:
eatCookie();
break;
default: // used when there is no state available
eatCookie();
}
}
});
}
public void eatCookie() {
currentState = STATE_FULL;
imageView.setImageResource(R.drawable.after_cookie);
textView.setText("Im so full");
}
public void returnCookie() {
currentState = STATE_HUNGRY;
imageView.setImageResource(R.drawable.before_cookie);
textView.setText("I'm so hungry");
}
}
Have you tried using a static variable to keep track of the currently displayed image? Static means it will maintain its state between function calls. Then toggle it each time the function is called. The initial declaration will only be called once.
static Boolean eaten = false;
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.
I'm new to android and have have an assignment to create an email application. So I have 2 layouts and 2 activities, one for reading the email and one for writing the email. I'm trying to retain the information sent in the fields in the email writing activity for when the email is being read. The problem is at the **bolded line below - "The method setText string is undefined for the type view", and I need to get all the text view to contain the information send from the other activity. I can post the other files if its needed, all help appreciated. I have tried other ways to assign the variable to text view but can't seem to get it to work.
DisplayMessageActivity.java
package com.example.project;
import com.example.project.R.layout;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Show the Up button in the action bar.
setupActionBar();
// Get the messages from the intent
Intent intent = getIntent();
String messageto2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
String messagefrom2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE2);
String messagecc2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE3);
String messagebcc2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE4);
String messagesubject2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE5);
String messagebody2 = intent.getStringExtra(MainActivity.EXTRA_MESSAGE6);
**TextView msgto = (TextView)findViewById(R.id.to2).setText(messageto2);**
TextView msgfrom = (TextView)findViewById(R.id.from2);
TextView msgcc = (TextView)findViewById(R.id.cc2);
TextView msgbcc = (TextView)findViewById(R.id.bcc2);
TextView msgsubject = (TextView)findViewById(R.id.subject2);
TextView msgbody = (TextView)findViewById(R.id.body2);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
TIA
Try to change this:
(TextView)findViewById(R.id.to2).setText(messageto2);
to
((TextView)findViewById(R.id.to2)).setText(messageto2);
Methods are resolved according to the static type of the reference. findViewById() is declared with a return type of View and since the class View doesn't declare a method setText(), the compiler complains. Use this
TextView msgto = (TextView)findViewById(R.id.to2);
msgto.setText(messageto2);
try this..
((TextView)findViewById(R.id.to2)).setText(messageto2);
TextView msgto = (TextView)findViewById(R.id.to2).setText(messageto2);
Need to be changed to
TextView msgto = (TextView) findViewById(R.id.to2);
msgto.setText(messageto2);
That should help.
I want to make password protected android app, but when in this simple program system is not matching two strings.
package com.pokmgr;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainPM extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pm_layout);
final EditText pin = (EditText) findViewById(R.id.pinET);
final String pass = pin.getText().toString();
final String code = "ajaj";
Button enter = (Button) findViewById(R.id.enterBtn);
enter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (pass.equals(code)) {
Intent in = new Intent(MainPM.this, Menu.class);
startActivity(in);
}
else {
Intent in = new Intent(MainPM.this, Menu2.class);
startActivity(in);
}
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pm_layout, menu);
return true;
}*/
}
I have made Menu and Menu2 class, but every time Menu2 class is accessed. Even if I enter same pass that is "ajaj" [in this code to test]
i have defined both activities in manifest file.
Can't understand why pass.eqals(code) is not working
The problem is that you are setting pass to the contents of the EditText when the activity gets created. Instead you have to retrieve the contents of your EditText inside the OnClickListener.
Like this:
public void onClick(View v) {
final String pass = pin.getText().toString();
if (pass.equals(code)) {
// do something
} else {
// do something different
}
}
Put pin.getText().toString(); inside onClick of button. You are setting variable pass before the user actually entered something in pinEt EditText.
Ok, thanks to below dude biggest issue is fixed. But whatever I print out, none is printed and I cannot print out the message what is typed in class 2 (nimekysija) as well :(. I really need that it stores name and in future it will write down name every time! Thanks for your help!
Problem must be in 2nd class tho. When I update editor.putString("nimi2", nimiS); nimiS into "plapla", then plapla actually shows up :/. So I have really no idea, what is problem!
(updated below classes too to the newest)
Class 1:
package viimane.voimalus;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class MainStuff extends Activity {
TextView tere;
String nimi;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
tere = (TextView) findViewById(R.id.tvTere);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean nimiOlemas = preferences.getBoolean("nimionolemas", false);
if (nimiOlemas == false){
startActivity(new Intent("viimane.voimalus.NIMEKYSIJA"));
finish();
}
if (nimiOlemas == true){
nimi = preferences.getString("nimi2", "");
System.out.print("töötab!");
tere.setText("Tere " + nimi);
}
System.out.print("töötab2!");
}
}
CLASS 2
package viimane.voimalus;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class nimekysija extends Activity {
EditText nimi;
SharedPreferences preferences;
String nimiS;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nimekysija);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
nimi = (EditText) findViewById(R.id.etNimekysija);
nimiS = nimi.getText().toString();
Button kysOk = (Button) findViewById(R.id.bNimekysija);
kysOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = preferences.edit();
editor.putString("nimi2", nimiS); // nime kirjutamine
editor.putBoolean("nimionolemas", true); // nimi on kirjutatud!
editor.commit();
startActivity(new Intent("viimane.voimalus.MAINSTUFF"));
finish();
}
});
}
}
Ok I'm guessing you may be new to Java, forgive me if I'm incorrect. You never READ from nimiOlemas.
boolean nimiOlemas = preferences.getBoolean("nimionolemas", false);
nimiOlemas = false;
startActivity(new Intent("viimane.voimalus.NIMEKYSIJA"));
finish();
nimiOlemas = true;
I think what you are trying to do is initialize nimiOlemas and then, if it is false, start an activity, call finish, then set nimiOlemas to true, but this is not what you are doing. Is this what you want?
boolean nimiOlemas = preferences.getBoolean("nimionolemas", false);
if (nimiOlemas == false)
{
startActivity(new Intent("viimane.voimalus.NIMEKYSIJA"));
finish();
nimiOlemas = true;
}
= is an assignment, == is a boolean comparison. You say in your question that you check the value of your boolean, but you never do, you only assign to it.
Assuming that nimiOlemas is inherited from activity and not used in the activity class, or other supper class, then yes it is not used in nimekysija (Class 2). It IS used in class 1. But this should just be a warning... You will get this warning for every class that extends activity and doesn't use nimiOlemas.