I am having trouble with using OnClickListener. I am trying to start a new activity when the user presses one of the buttons in my floating action button. My app just crashes right when I run it.
In my LaunchActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
final Button buttonNote = (Button) findViewById(R.id.note);
buttonNote.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startActivity(new Intent(LaunchActivity.this, CreateNote.class));
}
});
}
In my activity_launch.xml:
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
fab:fab_addButtonColorNormal="#color/accent"
fab:fab_addButtonColorPressed="#color/accent_dark"
fab:fab_addButtonPlusIconColor="#color/window_background"
fab:fab_labelStyle="#style/menu_labels_style"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/note"
android:src="#drawable/ic_note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="16dp"
fab:fab_title="#string/note"
fab:fab_colorNormal="#color/accent"
fab:fab_colorPressed="#color/accent_dark"/>
</com.getbase.floatingactionbutton.FloatingActionsMenu>
CreateNote.java:
public class CreateNote extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_note);
}
#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_create_note, 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);
}
}
Thank you for any help, this is my first app.
try this
findViewById(R.id.note).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LaunchActivity.this, CreateNote.class));
}
});
instead
final Button buttonNote = (Button) findViewById(R.id.note);
buttonNote.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startActivity(new Intent(LaunchActivity.this, CreateNote.class));
}
});
hope it help
Please share your logcat errors here..
And try to change the object from Button to com.getbase.floatingactionbutton.FloatingActionButton.
Declare your activity in manifest file as follows
<activity
android:name=".CreateNote"
android:label="#string/app_name">
</activity>
Ok, you got it working, but for your information,
the reason why you were facing this problem was, the FAB is NOT one of those simple buttons that you create.
You have to create an object of floatingActionButton instead of creating the object of button (which you did in your case).
Related
I'm new about coding so i'm sorry for my "basic" questions.
I'm coding an Android app with Android studio; very simple, only webview that show my website but i need to have in settings menu an editText where i can modify my website url.
I made two activitys(Main and Settings) that i post; Could anyone help me to understand how can i store permanently the url that i write in my editText in order to open that url when i came back to main activity?
Hope i submit clearly my question!!
Thanks in advance
Settings.java
private EditText editsite;
private Button button;
public static TextView actSite;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
editsite = findViewById(R.id.editsite);
button = findViewById(R.id.saveButton);
actSite = findViewById(R.id.actSite);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String strData = editsite.getText().toString();
if (strData.length()<=0) {
Toast.makeText(this,"Sito non valido", Toast.LENGTH_SHORT).show();
}else {
actSite.setText(strData);
Main Activity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
WebView vista = (WebView)findViewById(R.id.vista);
vista.getSettings().setJavaScriptEnabled(true);
vista.setWebViewClient(new WebViewClient());
vista.loadUrl("www.google.com"); //examplesite
}
#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) {
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use SharedPreferences Here. And everytime the MainActivity starts you load the Shared Preferences and get the String.
Example:
set Shared Preferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("URL", "Your url");
editor.apply();
Get the value
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String url= prefs.getString("URL", "String if URL is emtpy");
I am working on a Project and testing the XML, however, whenever I try switching to my next activity, the app gets stuck on a black screen and does nothing, and I am forced to quit.
I tried switching the layouts for setContentView and that didn't work, I checked to make sure the code in the activity files was working, and now I am looking at other's questions and I am just confused.
Here is my MainActivity:
public class MainActivity extends android.app.Activity {
ImageButton startButton;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
startButton = (ImageButton)findViewById(R.id.startButton);
textView = (TextView)findViewById(R.id.textView);
textView.setTextColor(Color.WHITE);
View backgroundView = findViewById(R.id.spoopySkellington);
View root = backgroundView.getRootView();
root.setBackgroundColor(getResources().getColor(android.R.color.black));
}
#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;
}
public void startClick(View view)
{
final Intent intent = new Intent(MainActivity.this, AdventureActivity.class);
startActivity(intent);
}
#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);
}
}
Here is the activity I am trying to switch to.
public class AdventureActivity extends android.app.Activity {
Character mainCharacter;
Character skeleton;
TextView dialogueView;
EditText textField;
Button confirmButton;
String field;
ImageView enemy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_adventure);
confirmButton = (Button)findViewById(R.id.confirmButton);
dialogueView = (TextView)findViewById(R.id.dialogueView);
textField = (EditText)findViewById(R.id.inputText);
field = "";
skeleton = new Character("Skeleton", 10, 1);
String name = "";
while (field.equals("")) {
dialogueView.setText("What is your name?");
name = field;
}
mainCharacter = new Character(name);
}
public void onClick(View view)
{
field = textField.getText().toString();
textField.setText("");
}
#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);
}
}
Lastly, here is the activity xml for the one I want to switch to:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.jason.textadventure.AdventureActivity"
tools:showIn="#layout/activity_adventure">
<TextView
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/dialogueView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="..."
android:textSize="30dp"
tools:layout_editor_absoluteY="126dp"
tools:layout_editor_absoluteX="180dp"
/>
<EditText
app:layout_constraintBottom_toBottomOf="#id/dialogueView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/inputText"
android:layout_width="261dp"
android:layout_height="40dp"
tools:layout_editor_absoluteY="196dp"
tools:layout_editor_absoluteX="62dp"
android:inputType="textNoSuggestions"
/>
<Button
app:layout_constraintBottom_toBottomOf="#id/inputText"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="#id/dialogueView"
android:id="#+id/confirmButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CONFIRM"
android:onClick="onClick"
tools:layout_editor_absoluteY="184dp"
tools:layout_editor_absoluteX="148dp" />
When onCreate() is called, your code is stuck around this loop
while (field.equals("")) {
dialogueView.setText("What is your name?");
name = field;
}
I'm working on programming a android application. But as soon as I would like to test my application in my simulator, I get an instant error.
This is my code.
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button toPech = (Button)findViewById(R.id.toPech);
toPech.setOnClickListener(this);
ImageButton toInfo = (ImageButton)findViewById(R.id.toInfo);
toInfo.setOnClickListener(this);
//this button is not in the same layoutactivity as the other 2.
ImageButton backPech = (ImageButton)findViewById(R.id.backPech);
backPech.setOnClickListener(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);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.toPech:
startActivity(new Intent(getApplicationContext(), LocationActivity.class));
break;
case R.id.toInfo:
startActivity(new Intent(getApplicationContext(), InfoActivity.class));
break;
case R.id.backPech:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
break;
}
}
I would like to know what is wrong so that I can.
From your commented line:
//this button is not in the same layoutactivity as the other 2.
I think you have a NullPointerException.
While the Button "backPech" isn't in activity_main.xml, so calling findViewById(R.id.backPech); will return a null object ( backPech will be null).
And calling setOnClickListener(this); to a null object will cause the NullPointerException.
I am trying to manually implement the actions that must take place when the up button on the actionbar is pressed but for some reason nothing happens when I press it.
here is my code:
public class ActivityOne extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_one);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = (Button)findViewById(R.id.btn1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityTwo();
}
});
Button button2 = (Button)findViewById(R.id.btn2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityThree();
}
});
}
void openActivityTwo(){
Intent intent = new Intent(this, ActivityTwo.class);
startActivity(intent);
}
void openActivityThree(){
Intent intent = new Intent(this, ActivityThree.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.menu_activity_one, 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;
}
else if(id == R.id.homeAsUp){
Log.i("","Up is pressed");
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
I understand that I have to explicitly assign a parent activity for the activity I want to implement up navigation on the manifest file, but problem is that this activity has multiple parents so I thought calling the finish() method when the up button is pressed on this activity will be the better approach.
I have already tried both id == R.id.home and id == R.id.homeAsUp and they both do not work. I do not know if it is because I am using AppCompactActivity or what Please help
Here is how you can implement this, try this code
use android.R.id.home instead of R.id.home or R.id.homeAsUp
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//use onBackPressed() OR finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The correct way to do it is to override public boolean onNavigateUp() just like overriding onBackPressed().
Using android studio 3.6.2 I've found that the Up button is not displayed by default in my apps, but it can be easily added..
Go to AndroidManifest.xml and update each activity that needs an Up button as follows:
<activity
android:name=".yourClassName"
android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourPackageName" />
</activity>
The target destination for the Up button is set by changing parentActivityName. In this example I have set it as '.MainActivity' but you can change that to whatever activity you want the user to navigate to.
I am making an Facts based application. I want it to show new fact every time the user presses the button and i also want that when the user exits the app and restart it, it would resume from the same fact that user was reading.
Help me guys... I have included the java and xml code that i am using
Thanks in advance
My Java Layout
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Next(View view) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hi");
textView.setText("No One is here to sleep");
textView.setText("This sounds like fun");
textView.setText("Men will be men");
}
#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);
}
}
Xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#ff7922ff">
<TextView android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="35dp"
android:layout_above="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="106dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button"
android:layout_marginBottom="158dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="Next" />
</RelativeLayout>
TextView tv = (TextView)findViewById(R.id.tv);
Button bt = (Button)findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tv.setText("TEXT");
}
});
Use SharedPreferences for that
SharedPreferences prefs = getSharedPreferences("mySHaredpref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
boolean isFirst = prefs.getInt("lastFact", 0);
You could use Shared Preferences to keep a track of which was the last fact that the user had seen. Please check this link for the same How to use SharedPreferences in Android to store, fetch and edit values
What you will need to do is that on every next or previous button click you will have to store the fact number in your shared preferences. Every time the app is opened, load fact corresponding to the factnumber in the sharedpreferences.
I would advice you to do like this:
int count=0;
ArrayList<String> msgList = new ArrayList<>();
msgList.add("Hi");
msgList.add("No One is here to sleep");
msgList.add("This sounds like fun");
msgList.add("Men will be men");
Now
public void Next(View view) {
if(count==msgList.size()){
count=0;
textView.setText(msgList.get(count%msgList.size()));
}else{
textView.setText(msgList.get(count%msgList.size()));
count++;
}
}
As per your requirement, you need to save the facts in shared preferences and show the facts in TextView as user tap the button.
You also need to fetch the facts from shared preferences and show on the TextView in OnResume() of activity.
Button btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// save the facts in shared preferences
// and show the facts on the text view
}
});
and onResume()
#Override
protected void onResume() {
super.onResume();
// check the shared preferences for the facts
// If facts is available in shared preferences then show on the
// textview
}
If you want to define the onClick method on XML, then work on onClickListener to be done on the onClick method(defined in XML).