Unknown class 'name' - java

I am new to Android Studio and trying to get used to it. I have tried to make a trivial app where the user could press a button and a random number would be generated. However, when I used the variables in the code it gave me "unknown class 'get'" and "unknown class 'random'" errors. Code is as follows:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button RollButton = findViewById(id.RollButton);
final TextView resultsTextView = findViewById(id.ResultsTV);
final SeekBar seekBar = findViewById(id.seekBar);
RollButton.setOnClickListener(new onClickListener()
{
Random rnd = new Random(10);
private int random = rnd.nextInt(seekBar.getProgress());
CharSequence get = resultsTextView.getText();
get = String.valueOf(random);
});
}
}

Your OnClickListener looks wrong and you can't use private in this case. So try this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button RollButton = findViewById(id.RollButton);
final TextView resultsTextView = findViewById(id.ResultsTV);
final SeekBar seekBar = findViewById(id.seekBar);
RollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rnd = new Random(10);
int random = rnd.nextInt(seekBar.getProgress());
CharSequence get = resultsTextView.getText();
get = String.valueOf(random);
}
});
}
}

Related

RunTime error in android studios, with no syntax errors. Created program programmatically

I am new to android studios and was tasked with creating an app programmatically. Depending on which button is pressed, the color description is displayed. I have a feeling it has something to do with the layout I created. Every time I run the program the app crashes and I cannot figure out why. Below is my code:
package com.example.hw3ex2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
LinearLayout layout;
LinearLayout.LayoutParams layoutParams;
String plumDescription = getResources().getString(R.string.plum_is);
String blueDescription = getResources().getString(R.string.blue_is);
String goldDescription = getResources().getString(R.string.gold_is);
String descriptionString;
TextView tv;
Button btnPlum;
Button btnBlue;
Button btnGold;
private int button_color = getResources().getColor(R.color.button_color);
private int background_color=getResources().getColor(R.color.background_color);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGUIByCode();
}
private void buildGUIByCode() {
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
//create a layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//create textview
tv = new TextView(this);
tv.setLayoutParams(params);
layout.addView(tv);
//create buttons and add them to layout
btnPlum = new Button(this);
btnPlum.setTag("plum");
btnPlum.setText("Plum");
btnPlum.setLayoutParams(params);
layout.addView(btnPlum);
btnPlum.setOnClickListener(this);
btnPlum.setBackgroundColor(button_color);
btnBlue = new Button(this);
btnBlue.setTag("blue");
btnBlue.setText("Blue");
btnBlue.setLayoutParams(params);
layout.addView(btnBlue);
btnBlue.setOnClickListener(this);
btnBlue.setBackgroundColor(button_color);
btnGold = new Button(this);
btnGold.setTag("gold");
btnGold.setText("Gold");
btnGold.setLayoutParams(params);
layout.addView(btnGold);
btnGold.setOnClickListener(this);
btnGold.setBackgroundColor(button_color);
setContentView(layout);
}
#Override
public void onClick(View view) {
Object tag = view.getTag();
if ("plum".equals(tag)) {//get plum_is string and display in textView
tv.setText(plumDescription);
} else if ("blue".equals(tag)) {//get blue_is string and display in textview
tv.setText(blueDescription);
} else if ("gold".equals(tag)) {//get gold_is string and display in textview
tv.setText(goldDescription);
}
System.out.println(descriptionString);
}
}
I see that you're invoking getResources() before onCreate,
you need to move all of those initialization that uses getResources() within onCreate
public class MainActivity ... {
String plumDescription; // don't initialize here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
plumDescription = getResources().getString(R.string.plum_is); // initialize after onCreate
}
}

How do I transform a string from EditText to a character array, to allow audio implementation?

This is my code:
package com.example.pembroke.finalalgorhythmic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button asdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asdf = (Button) findViewById(R.id.keybutton);
asdf.setOnClickListener(MainActivity.this);
}
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
}
What I want to do, is create a character array, so that I can use media player class to play certain sounds based on the user input after my button is clicked. Any ideas?
Have you tried
notes.toCharArray() yet?
EDIT: Long version
EDIT 2: Sample implementation
MediaPlayer mp;
char[] currentNotes;
int noteIndex;
// Create the mp in onCreate and register your onCompletion callback
#Override
public void onClick(View v) {
EditText keyInput = (EditText) findViewById(R.id.key);
String notes = keyInput.getText().toString();
currentNotes = notes.toCharArray();
noteIndex = 0;
mp.setDataSource(getNoteResource(currentNotes[0]));
mp.start();
}
// Convert tone values into
public int getNoteResource(char tone) {…}
#Override
public void onCompletion(MediaPlayer mp) {
if(++noteIndex < currentNotes.length) {
mp.setDataSource(getNoteResource(currentNotes[noteIndex]));
mp.start();
}
}

Unable to update TextView with Timer in separate class

I've created a timer and placed it in its own separate class. For some reason when I try to run it it crashes with the following error:
Java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I think it because its trying to update a textview from a class other than Mainactvity but I cant figure out how to get it to work.
Here's the code:
MainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button resetButton;
TextView textTimer;
int elapsedTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elapsedTime = 60;
textTimer = (TextView) findViewById(R.id.textTimer);
resetButton = (Button) findViewById(R.id.resetButton);
final Button resetbttn = (Button) findViewById(R.id.resetButton);
resetbttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CountUp mycountup = new CountUp();
mycountup.count();
}
});
}
}
Timer Class:
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Mat on 24-Feb-17.
*/
public class CountUp extends MainActivity{
TextView textTimer;
Button resetButton;
int elapsedTime;
Handler h;
int RATE = 1000;
MainActivity mainact = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textTimer = (TextView) findViewById(R.id.textTimer);
resetButton = (Button) findViewById(R.id.resetButton);
h = new Handler();
count();
final Button resetbttn = (Button) findViewById(R.id.resetButton);
resetbttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reset();
}
});
}
public void reset(){
elapsedTime = 60000;
}
public void count(){
elapsedTime--;
textTimer.setText(String.valueOf(elapsedTime));
h.postDelayed(r,RATE);
final String endcomparison = textTimer.getText().toString();
if (endcomparison.equals("0")){
reset();
}
}
private Runnable r = new Runnable() {
#Override
public void run() {
count();
}
};
}
findViewById() method actually looks for view in layout file.
when you set layout for activity or fragment using
setContentView(R.layout.activity_main);
findViewById() find those views in that layout. it can't find random objects on the fly.
so in second activity set layout first or create sub class in first activity and then try to update data in textview.
Your are just instantiating an activity, which it's onCreate will never get called.
CountUp mycountup = new CountUp();
mycountup.count(); // view never created so it's null
To load the views you need to use a method like startActivity.
If I am understanding you correctly, if you are extending CountUp from MainActivity then in your manifest, you'd set CountUp as your launching activity. Then using Java inheritance, you don't need to re-find the views, because in CountUp we are calling super.onCreate(savedInstanceState), which calls the MainActivity's onCreate.
public class MainActivity extends AppCompatActivity {
Button resetButton;
TextView textTimer;
int elapsedTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
elapsedTime = 60;
textTimer = (TextView) findViewById(R.id.textTimer);
resetButton = (Button) findViewById(R.id.resetButton);
}
}
public class CountUp extends MainActivity{
Handler h;
int RATE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// can access this since inheritance
resetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reset();
}
});
h = new Handler();
count();
}
//...
public void count(){
elapsedTime--;
// inheritance
textTimer.setText(String.valueOf(elapsedTime));
h.postDelayed(r,RATE);
final String endcomparison = textTimer.getText().toString();
if (endcomparison.equals("0")){
reset();
}
}
//...
}

How to set a RelativeLayout background color?

I am trying to set a RelativeLayout backgroundColor and I get cannot resolve symbol
here is my code
package com.example.butka.clickme;
import android.graphics.Color;
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.widget.Button;
import android.widget.RelativeLayout;
import java.util.Random;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
//set layout
super.onCreate(savedInstanceState);
RelativeLayout layout1 = new RelativeLayout(this);
layout1.setBackgroundColor(Color.BLACK);
//LayoutParameters
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.CENTER_VERTICAL);
//button
Button btn = new Button(this);
btn.setText("Click me");
btn.setBackgroundColor(Color.WHITE);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
colors();
}
});
//add stuff
layout1.addView(btn, params);
setContentView(layout1);
}
//void on button click
private void colors()
{
Random random = new Random();
short num1 = (short)random.nextInt(9);
if(num1 == 0)
{
layout1.setBackgroundColor(Color.BLACK);
}
}
}
everything runs good, until the color void. the error is cannot resolve symbol But the interesting thing is that I can set the color using layout.setBackgroundColor() before the void.
So the question is, how do you set a layout backgroudColor?
Use this:
layout1.setBackgroundColor(ContextCompat.getColor(this, R.color.black));
or
layout1.setBackgroundColor(Color.parseColor("#000000"));
Your RelativeLayout is in the onCreate() method scope, you must move it to class scope. Like this:
public class MainActivity extends AppCompatActivity {
RelativeLayout layout1; // Make it class scope.
#Override
protected void onCreate(Bundle savedInstanceState) {
//set layout
super.onCreate(savedInstanceState);
RelativeLayout layout1 = new RelativeLayout(this);
layout1.setBackgroundColor(Color.BLACK);
...
}
// Then you can access it from other method:
private void colors() {
Random random = new Random();
short num1 = (short)random.nextInt(9);
if(num1 == 0) {
layout1.setBackgroundColor(Color.BLACK); // You can access it now.
}
}

Android getAllCellInfo() returns null

I'm new to android, and I work on a project that goes to collect all cells information that observed by phone. I have used TelephonyManager.getAllCellInfo() method, but it always returns null.
My Code ::
public class NetworkCoverageActivity extends AppCompatActivity {
private String str;
private TextView TV;
private Button getCellsInfoBtn;
private TelephonyManager TM;
private List<CellInfo> cellInfoList;
private PhoneStateListener PSL;
private int event;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_coverage);
TV = (TextView)findViewById(R.id.iv);
getCellsInfoBtn = (Button)findViewById(R.id.getCellsInfoBtn);
TM = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
PSL = new PhoneStateListener();
event = PSL.LISTEN_CELL_INFO | PSL.LISTEN_CELL_LOCATION;
getCellsInfoBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
TM.listen(PSL, event);
cellInfoList = TM.getAllCellInfo();
if(cellInfoList != null)
TV.append("cellInfoList = null");
else{
...
}
}
});
}
I'm working on android 4.4.2 level 17 and set min API level to 17. and I try to collect information from GSM network.
Also, I added the following permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I have got the solution of my question. that's replaced getAllCellInfo() function by getNeighboringCellInfo() function, although I am running with android level 17 that should be support getAllCellInfo() function and getNeighboringCellInfo() function should be no longer supported.
Anyway, the following is the solution.
package ayad.bslm.com.networkcoverage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class NetworkCoverageActivity extends AppCompatActivity {
private TextView TV;
private TelephonyManager TM;
private List<NeighboringCellInfo> neighboringCellInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network_coverage);
TV = (TextView)findViewById(R.id.iv);
Button getCellsInfoBtn = (Button)findViewById(R.id.getCellsInfoBtn);
TM = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
getCellsInfoBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
neighboringCellInfoList = TM.getNeighboringCellInfo();
if(neighboringCellInfoList == null)
TV.setText("neighboringCellInfoList == null\n");
else
TV.setText("There are " + neighboringCellInfoList.size() + " Cells\n");
}
});
}
}

Categories