This question already has answers here:
How to use java classes within one activity?
(4 answers)
Closed 7 years ago.
How can you use a java class within one activity, by that I mean is having different components of that activity spread out in a bunch of java classes. I'm a little new to android and this is what I have tried so far:
MainActivity.java
package com.example.alex.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Something(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Something.java
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
public class Something {
private Activity activity;
private Button add,subtract,multiply,devide;
private EditText editA, editB, editC;
private double doubleA,doubleB,doubleC;
public Something(Activity a){
activity=a;
click();
}
public void click(){
editA = (EditText) activity.findViewById(R.id.editText);
editB = (EditText) activity.findViewById(R.id.editText2);
editC = (EditText) activity.findViewById(R.id.editText3);
doubleA =Double.parseDouble(editA.getText().toString());
doubleB =Double.parseDouble(editB.getText().toString());
add = (Button) activity.findViewById(R.id.add);
subtract = (Button) activity.findViewById(R.id.subtract);
multiply = (Button) activity.findViewById(R.id.multiply);
devide = (Button) activity.findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA+doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA-doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA*doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA/doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
}
}
So I wasn't sure why my listeners weren't working on my buttons so I tried passing the activity to the class that has the listeners added to the buttons but that didn't work in fact now my application won't even start in the emulator. All I wanted to do was have "MainActivity" handle the "Gui" and have the "Something" class handle the listeners but no matter what I do I can't seem to make them communicate with one another to form one Activity.
Someone suggested to do a pass in main activity Something s = new Something(MainActivity.this); and call it from within main activity like this s.click(); but that didn't work.
in android every class that extends activity just have a one xml Layout to view and handle this XML file just in it's Activities,and you can make a lot of java classes that send alot of parameter but when you want to handle XML behavioral you should do in own class that Extends Activity,so you can do this:
public class MainActivity extends ActionBarActivity {
Button myBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Something(this);
myBtn=(Button)findViewById(R.id.Btn);
myBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Related
I am using the code below to display images sequentially via button click. Now I want to display these images automatically after a particular time period. They should be displayed and change after a particular time and where the addition will be needed in the same code.
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static ImageView imgView;
private static Button ButtonSbm;
private int current_image_index;
int [] images={R.mipmap.ic_launcher,R.mipmap.ic_launcher1};
#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) {
Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
buttonClick();
}
public void buttonClick(){
imgView =(ImageView)findViewById(R.id.imageView);
ButtonSbm=(Button)findViewById(R.id.button);
ButtonSbm.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
current_image_index++;
current_image_index=current_image_index %images.length;
imgView.setImageResource(images[current_image_index]);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hi you can use he following code
public class TestService extends IntentService {
Context ctx;
private CountDownTimer countDownTimer;
public static final String Tag="TestService";
private long startTime= 2 * 1000;
int index = 0;
private final long interval = 1 * 1000;
public TestService() {
super("TestService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
countDownTimer = new MyCountDownTimer(startTime, interval);
countDownTimer.start();
Looper.loop();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
// do as per you required
}
#Override
public void onTick(long millisUntilFinished) {
Log.v(Tag,"Inside OnTick()");
// do as per you required
}
}
}
So i got my firstScreen that i want to be shown just on the first app use.
and i have my mainActivity which will follow the firstScreen.
Im only starting with android and i don't want to use the solutions brought in here: How to launch activity only once when app is opened for first time? AND Can I have an android activity run only on the first time an application is opened? because i dont know SharedPreferrences yet.
So how can i achieve that using Boolean flags?
I have got:boolean firstTimeUse = false; In my firstScreenActivity
And when i start myMainActivity i set the flag to true;
firstTimeUse = true;
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
The problem is the MainActivity doesn't recognize the Boolean variable.
Am i doing it wrong? Or i can still make some modifications and do it with flags?
EDIT
FirstScreen.java:
package com.example.predesignedmails;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class FirstScreen extends AppCompatActivity
{
TextView welcomeTextTextView;
String welcomeText;
ImageButton goToMainImageButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_screen);
viewsInitialization();
welcomeText = "Welcome to Pre Designed Mails.\n"
+ "In here you will have a tons of Emails templates for about every purpose you will need.\n"
+ "Just fill the small details and click Send.\n\n"
+ "Send E-mails fast and efficient!";
welcomeTextTextView.setText(welcomeText);
welcomeTextTextView.setMovementMethod(new ScrollingMovementMethod());
goToMainImageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume()
{
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true))
{
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
// First launch code
Log.d("FirstLaunchCheckUp","First Launch");
}
}
private void viewsInitialization()
{
welcomeTextTextView = (TextView) findViewById(R.id.welcome_text_text_view_id);
goToMainImageButton = (ImageButton) findViewById(R.id.go_to_main_button_id);
}
}
The onResume() method i added manually. It wasn't added automatically when i crated a new activity in Eclipse.
MainActivity.java:
package com.example.predesignedmails;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
Button hatefullMailButton;
Button loveMailsButton;
Button welcomeScreenButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color)); // Setting background color
viewsInitialization();
hatefullMailButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,HatefulMailsActivity.class);
startActivity(intent);
}
});
loveMailsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,LoveMailsActivity.class);
startActivity(intent);
}
});
welcomeScreenButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,FirstScreen.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void viewsInitialization()
{
hatefullMailButton = (Button) findViewById(R.id.hateful_email_button_id);
loveMailsButton = (Button) findViewById(R.id.love_email_button_id);
welcomeScreenButton = (Button) findViewById(R.id.welcome_screen_button_id);
}
}
In your Activity
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true)){
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
//your first launch code
}
}
SharedPreference helper class
public class SettingsManager
{
public static final String FIRST_LAUNCH= "first_lauch";
public static String getString(Context context, String key, String defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defValue);
}
public static int getInt(Context context, String key, int defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defValue);
}
public static boolean getBoolean(Context context, String key, boolean defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defValue);
}
public static void saveString(Context context, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
}
public static void saveInt(Context context, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).commit();
}
public static void saveBoolean(Context context, String key, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
}
}
For the future you can write more simple methods on this SettingsManager, like
public static int getFirstLaunch(Context context) {
return getBoolean(context, FIRST_LAUNCH, true);
}
public static int saveFirstLaunch(Context context, boolean value) {
return saveBoolean(context, FIRST_LAUNCH, value);
}
And use it like
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getFirstLaunch(this)){
SettingsManager.saveFirstLaunch(this, false);
//your first launch code
}
}
The reason why firstScreen does not recognize boolean firstTimeUse in mainActivity is because it does not yet exist. Only after you have executed the line startActivity(intent) will there exist an object of class mainActivity. Basically, you cannot set a boolean on something that does not yet exist.
Instead, what you can do is pass extra information to an activity that is to be started. When the just-started-activity is initializing itself it can read the extra information and act on it.
So build your intent for the activity you want to start and also set extra information in the 'extras':
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
intent.putExtra("firstTimeUse", true);
startActivity(intent);
Now for your MainActivity to know the value of firstTimeUse it must read the extras:
public class MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstTimeUse = getIntent().getBooleanExtra("firstTimeUse", false);
// do processing dependent on whether it's the first time or not
}
}
This should solve your problem of "the MainActivity doesn't recognize the Boolean variable".
i am having this error in this code
java.lang.runtimeexception unable to start activity componentinfo
package estimatewall.example.com.estimatewall;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
EditText inputTxt;
EditText inputTxt1;
TextView setText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputTxt = (EditText) findViewById(R.id.editText);
// Store EditText in Variable
int val = Integer.parseInt(inputTxt.getText().toString());
inputTxt1 = (EditText) findViewById(R.id.editText2);
// Store EditText in Variable
int val1 = Integer.parseInt(inputTxt1.getText().toString());
float block1,block2;
final float sum;
block1=(val*12)/7;
block2=(val1*12)/10;
sum=block1*block2;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
try {
TextView textView = (TextView) findViewById(R.id.textView3);
textView.setText("" + sum);
}catch (Exception e)
{
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Probably getting NumberFormatException because here:
int val = Integer.parseInt(inputTxt.getText().toString());
trying to convert null to int.
Use inputTxt.getText() inside onClick method of Button on click listener to get values input by user in Edittext or set some default values in xml for both EditText's as android:text="0"
I am getting the error Cannot Resolve Symbol "OnClickListener" and "Cannot Resolve Symbol "V""
I am starting to get into Java so I am not very good at this and not so familiar with the language
My code:
package com.emiliogaines.counter.counter;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button mButton = (Button) findViewById(R.id.More);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.Antal);
mTextView.setText("Some Text");
}
});
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar
// if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I'm not sure why you did that but please move the initializing and listeners to onCreate():
Simply cut these lines of code:
Button mButton = (Button) findViewById(R.id.More);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.Antal);
mTextView.setText("Some Text");
}
});
and paste them in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mButton = (Button) findViewById(R.id.More);
final TextView mTextView = (TextView)findViewById(R.id.Antal);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mTextView.setText("Some Text");
}
});
}
And then go read the basis of coding and it's standards.
U must store this into onCreate method :
#Override
protected void onCreate(Bundle savedInstanceState) {
Button mButton = (Button) findViewById(R.id.More);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final TextView mTextView = (TextView)findViewById(R.id.Antal);
mTextView.setText("Some Text");
}
});
}
I have a problem by following a tutorial for making an app. But now I get an error by adding an respond
for a button. It gives an error at public void sendMessage, but I cant see what is wrong.
package com.example.myfirstapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
/** Called when the user clicks the Send button */
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
those lines
/** Called when the user clicks the Send button */
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
go into your class, after
public class MainActivity extends ActionBarActivity {
Your function is outside the activity.
Move
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
inside Activity like this:
public class MainActivity extends ActionBarActivity {
//other code i.e. onCreate etc
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
}