New coder, doing third project, can not get app to run - java

I am a new coder, creating a higher or lower guessing game app in Android Studio using the Java language. My goal for this project is for the user to be able to input a number between 1 and 100, and for the app to be able to pick a random number each time the user plays the game, and for the app to be able to tell the user if the number they picked is the correct answer, or higher or lower. I am using Android studio using Java. I have all the code there, I just keep getting a couple error answers. For instance, on my "if (guess < theNumber) statements, the word "guess is in red" and says it cannot resolve symbol guess. And the statement "private Button btnGuess" the btnGuess is in grey and it says that it's never used, but I have the id in the design tab of Android Studio and it's id is labeled btnGuess and I thought that I wired it into the code, when I try to run the app through the emulator it just does not even run. I've tried googling around for the answer, but since I am new to coding I'm not sure that I'm asking the correct questions, I've included the code for reference, thank you very much in advance.
ckage com.example.billyhodgesguessinggame;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.billyhodgesguessinggame.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText txtGuess;
private Button btnGuess;
private TextView lblOutput;
private int theNumber;
public void checkGuess() {
String guessText = txtGuess.getText().toString();
String message = "";
try {
int Guess = Integer.parseInt(guessText);
if (guess < theNumber)
message = guess + "is too low. Try again.";
else if (guess > theNumber)
message = guess + "is too high. Try again.";
else {
message = guess +
"is correct. You win! Let's play again!";
newGame();
}
} catch (Exception e) {
message = "Enter a whole number between 1 and 100.";
} finally {
lblOutput.setText(message);
txtGuess.requestFocus();
txtGuess.selectAll();
}
}
private AppBarConfiguration appBarConfiguration;
public void newGame() {
theNumber = (int)(Math.random() * 100 + 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtGuess = findViewById(R.id.txtGuess);
Button btnGuess = findViewById(R.id.btnGuess);
lblOutput = findViewById (R.id.lblOutput);
newGame();
btnGuess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
checkGuess();
}
});
com.example.billyhodgesguessinggame.databinding.ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.toolbar);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
binding.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();
}
});
}
#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 boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}

You use Guess and guess as variable names. Stick to the lowercase version and only use guess.
In this line, remove Button at the beginning. Otherwise, you declare a new variable instead of reusing the existing one which you already declared at the top.
Button btnGuess = findViewById(R.id.btnGuess);

Related

Android Studio Navigation Drawer item opening website

I used the basic "Navigation Drawer Acticity" in Anroid Studio when creating the new project. The fragments work well and I've managed to add new fragments and everything.
However, items in the drawer menu that direct you to a certain website don't work. I've tried different methods with public boolean onNavigationItemSelected(MenuItem item){} and nothing happens when I press the items.
It looks like this:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
As you can see I did nothing for the fragments to work since they work fine already but when I press the button "moodle", nothing happens.
What have I done wrong?
Here is my MainActivity:
package com.example.ustudy;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.Toast;
import com.example.ustudy.ui.home.HomeFragment;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.example.ustudy.databinding.ActivityMainBinding;
import org.jetbrains.annotations.NotNull;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//required for the top bar to be clickable
setSupportActionBar(binding.appBarMain.toolbar);
//button in the bottom right corner
binding.appBarMain.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();
}
});
DrawerLayout drawer = binding.drawerLayout;
//Navigationview for the drawer (implemented in "activity_main.xml")
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
//each screen mentioned in the columns below (R.id.xy) will show the hamburger menu in the top left corner
//on screens, not included in the columns, there will be a "back arrow" instead of the ham. menu
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_nachricht, R.id.nav_lerngruppe, R.id.nav_lehrveranstaltung)
.setDrawerLayout(drawer)
.build();
//controls what happens when one of the items in the hamburger menu is clicked on
//go to "mobile_navigation.xml" to add screens to go to
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
//required to set up the hamburger menu icon and the back-arrow icon on the top bar(without it
//the user had to slide the side of the screen to open the menu)
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
//enables the items in the hamburger menu to go to a certain screen after clicking on them
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu (three dots on the right); this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
//enables the usage of the back-arrow on every screen
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull #NotNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_moodle) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
return true;
}
return true;
}
}
Please, let me know if you need more!

In android studio cannot resolve method 'findViewById'

I am joining two activity through intent
package com.smartcodeone.newapp1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static final String STRING_VAR = "com.smartcodeone.newapp1.HELLO_WORLD";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnMsg = (Button) findViewById(R.id.btnMsg);
btnMsg.setOnClickListener(new View.OnClickListener(){
//when user click's this function will be called
public void onClick(View v){
Intent intentvar = new Intent(getApplicationContext(),Main2Activity.class);
intentvar.putExtra(STRING_VAR,"Hello World"); //this is used to pass data to next intent
startActivity(intentvar);
}
});
}
private int findViewId(int btnMsg) {
return 0;
}
#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 android.support.v4.app.FragmentManager getSupportFragmentManager() {
return null;
}
}
It might have to do with Android Studio. Try cleaning your project and then rebuilding. If that doesn't work go to File -> Invalidate Caches/Restart ...
I get those issues sometimes as well. Let me know if that works. I tried your code and it works fine.
The issue seems to be that you defined a method named: findViewById(int button) that always return 0.
Use the Activity method instead of your own:
this.findViewById(int resourceId)
Good luck!
It seems you are implementing your own findviewbyid(). I don't know if you intend to do so.
Try removing
private int findviewbyid(int btnMsg) {
}
The ActionBarActivity's findviewbyid should resolve your button from your layout file.

My program crashes and I don't know why

I'm learning how to program in Java for Android and my program keeps crashing. It's suppoesed to convert from Celsius to Fahrenheit.
package com.example.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener
{
public static final int MY_CODE=2;
EditText temp;
RadioButton converttoF,converttoC,selectedtype;
RadioGroup conversion;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conversion = (RadioGroup)findViewById(R.id.conversion);
conversion.setOnCheckedChangeListener(this);
converttoF = (RadioButton)findViewById(R.id.converttoF);
converttoC = (RadioButton)findViewById(R.id.converttoC);
}
#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);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
selectedtype = (RadioButton) findViewById(checkedId);
Intent i = new Intent(this, Activity4Result.class);
i.putExtra("temper", temp.getText().toString());
if(selectedtype.equals(converttoC))
{
Toast.makeText(this,"C chosen", Toast.LENGTH_SHORT).show();
i.putExtra("type", 'c');
startActivityForResult(i, MY_CODE);
}
else
{
Toast.makeText(this,"F chosen", Toast.LENGTH_SHORT).show();
i.putExtra("type", 'f');
startActivityForResult(i, MY_CODE);
}
}
}
My guess is that the problem is happening in the "onCheckedChanged", because it crashes when I push any RadioButton.
I assume (It would be better if you post the crash log along with your question, so that we can help you better and stop assuming) you are getting a null pointer exception on the following code:
i.putExtra("temper", temp.getText().toString());
In your code you declared temp, but it is never initialised. You need to initialise temp before using it.

Trying to make a Fibonacci Android App

I am a newbie android app developer, and I wanted to challenge myself by making an app where a user input is taken, converted into integer, and entered into the Fibonacci formula. The result should show all the fibonacci numbers, looping the formula a user-given number of times.
So far, I think I have isolated the problem to the ContentViewer, but then again any help would be greatly appreciated. BTW I'm using Eclipse Juno if that helps
MainActivity.java
package com.example.myfirstapp;
//importing the API for this app
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
//I based this on the first app I learnt (as I haven't done much app development so far)
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
//this method creates a default layout when a "new app" is started
#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);
}
//This method sends the information of the user input to a second activity screen,
//through the use of intents
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
The input goes into a second activity screen called DisplayMessageActivity.java
package com.example.myfirstapp;
//import all the relevant API for this app
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
//main class extending Activity superclass
public class DisplayMessageActivity extends Activity {
//This main method is where the fibonacci formula is worked out the result is shown
//For some reason, the ContentViewer is not working for me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int messages = Integer.parseInt(message);
int[] fib = new int[messages + 1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= messages; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(60);
StringBuilder builder = new StringBuilder();
for (int j : fib)
{
builder.append(j);
}
String text = builder.toString();
textView.setText(text);
}
// Set the text view as the activity layout
setContentView(textView);
#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);
}
}
The error message I'm getting is
DisplayMessageActivity.java
activity_display_message cannot be resolved or is not a field (Line 18)
Return type for this method is missing (Line 46)
Syntax error on token "textView", VariableDeclaratorId expected after this token (Line 46)
textView cannot be resolved to a type (Line 46)
Hope that's enough information. Funnily enough, I was following the developer.android.com tutorial on making the first app, with tweaks to make it do Fibonacci.
Many thanks.
Edit: Thanks for your quick response. I checked and there was no activity_display_message.xml so I just created that and copied everything from the activity_main.xml. I also moved the textviewer to inside the onCreate method. Now I'm just tidying up everything so thanks for relieving me from another sleepless night.
you have apparently not created activity_display_message (or another less likely possibility is you are referring to a file that is not in the layouts folder). You are setting the view to a file that does not exist. Also from the code, I can see that you are putting in setContentView() in some random place. It should be within the body of a method (preferably within onCreate() in your case).
the setContentView(textView); is out side the method i mean it is a global make sure it is with in onCreate method

run as>android application in eclipse giving no response

I am new to android programming on eclipse and just doing it as a hobby...I have made and run 2 apps successfully and so their is no question of me not knowing how to run the app...i have restarted my pc but the problem sill persists..my 2 apps are still working on pressing the run button and i am using a device to run them(not an AVD) but the third app is not working...in fact their is no response..their are no errors in code but 3 lint warnings..the program is very simple(taking 2 numbers from user and displaying the sum)...Please help.MY code is as following:
package com.example.app3;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.*;
import android.view.View.*;
import android.widget.*;
public class MainActivityapp3 extends ActionBarActivity {
int num1,num2,sum;
Button button1;
EditText textf1,textf2;
TextView textv3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activityapp3);
textf1=(EditText)this.findViewById(R.id.editText1) ;
textf2=(EditText)this.findViewById(R.id.editText2);
textv3=(TextView)this.findViewById(R.id.textView3);
button1=(Button)this.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
num1 = Integer.parseInt(textf1.getText().toString());
num2 = Integer.parseInt(textf2.getText().toString());
sum = num1 + num2;
textv3.setText("sum" + "");
}
});
}
#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_activityapp3, 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);
}
}
Would really need to see the output of logcat. You can find it in the DDMS tabs of Eclipse.
Anyway, without more information I would ask: did you remember changing the activity name in AndroidManifest?

Categories