error when getting data from another class - java

I am creating a simple Android app. The part I am having trouble is when I am trying to get a String value from the class randomFailureQuotes the method that is important is as follows
public String getQuote(String[] quotes, int indexPosition) {
String quoteToBeDisplayed = new String(quotes[indexPosition]);
return quotes[indexPosition];
}
I try to make this the label of a textView with this code in my EditorActivity class the code for this is as follows.
randomFailureQuotes quote = new randomFailureQuotes();
String Fq = quote.getQuote;
setContentView(R.layout.activity_editor);
TextView quoteDisplay = new TextView(this);
quoteDisplay.setText(Fq);
The error is with when I am trying to set a string value named Fq to the value that the method getQuote returns. The IDE says it can't find the symbol getQuote.
Any help would be greatly appreciated. Feel free to point out any other unrelated errors in my code as I am new at Java and Android development and would love to learn.
EDIT
as requested by RScotCarson here is the rest of my code from both classes
randomFailureQuotes
public class randomFailureQuotes {
List<String> quotes = new ArrayList<>();
double indexPosition = (Math.random() * 4);
protected void onCreate(Bundle savedInstanceState) {
quotes.add("Failure Does't mean the game is over, it means try again with Experience");
quotes.add("Failure is an event not a person. Yesterday ended Last night - Zig Ziglar");
quotes.add("We learn from failure not success");
quotes.add("If you're not prepared to be wrong, you'll never come up with anything original - Ken Robinson");
}
public String getQuote(String[] quotes, int indexPosition) {
String quoteToBeDisplayed = new String(quotes[indexPosition]);
return quotes[indexPosition];
}
}
EditorActivity
package com.example.slick.thegiftoffailure;
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.TextView;
import java.util.Random;
import static android.R.attr.id;
public class EditorActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// the quote label
randomFailureQuotes quote = new randomFailureQuotes();
String Fq = quote.getQuote();
setContentView(R.layout.activity_editor);
TextView quoteDisplay = new TextView(this);
quoteDisplay.setText(Fq);
}
}

Let's take a look at your getQuote definition:
public String getQuote(String[] quotes, int indexPosition)
It takes in an array of Strings as well as a position used to index into the array. That means that when you call getQuote it should look more like this...
// quotes is an array declared and instantiated previously
// index is an integer that is also declared and instantiated previously
String Fq = quote.getQuote(quotes, index)
From your question it seems like quote exists in another class. Can you please post the rest of your code from both classes?
If both the index and the array of quotes belong to the RandomFailureQuotes class as member, then you don't need to pass them in to the method as long as they have been instantiated.
EDIT
After the OP provided the extra code, the issue is in the randomFailureQuotes class has a few issues.
onCreate() is NOT a constructor. onCreate is a part of the Android framework and is part of the Activity lifecycle. A standard Java class looks like this...
RandomFailureQuote.java
// It is Java convention to have class names capitalized each word
public class RandomFailureQuotes {
private List<String> quotes = new ArrayList<>();
// The constructor does not need any arguments since you are
// generating the quotes yourself.
public RandomFailureQuotes() {
quotes.add("Failure Does't mean the game is over, it means try again with Experience");
quotes.add("Failure is an event not a person. Yesterday ended Last night - Zig Ziglar");
quotes.add("We learn from failure not success");
quotes.add("If you're not prepared to be wrong, you'll never come up with anything original - Ken Robinson");
}
// Because the index and quotes array are member variables,
// you do not need the arguments in the method definition.
// Also, to get a random number each time you get a quote
// you will need to move the random variable to the method.
// you will need to cast the double value of indexPosition to an int value
public String getQuote() {
double indexPosition = (Math.random() * 4);
String quoteToBeDisplayed = quotes.get((int) indexPosition);
return quoteToBeDisplayed;
}
}
As for the EditorActivity, there are issues there as well. I'm assuming you're not even using the toolbar, so I'm going to remove that from the activity and the activity_layout.xml file.
EditorActivity.java
package com.example.slick.thegiftoffailure;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class EditorActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// the quote label
randomFailureQuotes quote = new randomFailureQuotes();
String Fq = quote.getQuote();
// You must retrieve the textview from your
// activity_layout.xml file
TextView quoteDisplay = (TextView) findViewById(R.id.text_view);
quoteDisplay.setText(Fq);
}
}
I then modified the xml to only have one TextView that displays a single failure quote. Note that the app will have to be restarted for it to choose a different quote.
activity_editor.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
Finally, from a developer, I suggest you spend some time learning Java before jumping in to Android. There are intricacies to both that take a little time to learn. There are a million step-y-step tutorials out there on the web to get you started with both. Find one you like and follow it closely! Good luck learning!

You create a new object of type randomFailureQuotes called quote. You didn't pass in parameters for the object and then you tried to access the getQuote data member inside of the newly created object directly. If you want to use the getQuote function you would at least need to include parenthesis so it looks like this: quote.getQuote()
But remember your getQuote function is expecting an array of strings with an index in the array.
getQuote should return a string, which should be fine. It will return the string that is stored at the index value inside of the String array. BUt you need to ensure that you have either passed in the String array and value or defined it in the default constructor.

String Fq = quote.getQuote;
This refers to a member variable (field) called getQuote. It is nowhere defined.
The method getQuote() is unrelated. Variable names and method names occupy distinct namespaces.

Related

Accessing methods or classes from another java file/class from Activity

I am new to android studio but I am getting better at it as I program more and more. I have a MainActivity.java and the .xml file. And a friend provided me some code that it suppose to work with the input areas. The problem is I do not know how to access that regular java file. So that I can use it the way it is intended. He was using eclipse to build everything while I use android studio. I have the buttons all good to go and areas of input good to go but I just dont know how to implement his code. Any guidance will be greatly appreciated.
See examples to understand what I am trying to do.
"In android studio" a class is created called WaterDetails.java with a .xml file called activity_water_details.xml. There are calculations that were made for the duration that I need to be able to use or access from a java file created in eclipse called DurationCalculations.java. I have tried importing. I have tried opening the folder in explorer and putting the class in the same project. But, nothing seems to work.
Code:
public class WaterDetails extends AppCompatActivity {
Button continueWaterDetailsPart2;
EditText duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water_details);
duration = (EditText)findViewById(R.id.enter_duration);
duration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = duration.getText().toString();
if(duration.equals(" "))// if user inputs information
//Then get calculations from other java file.
}
});
Sample Code:
Second Java fie. The file I need to access.
package ScubanauiTables;
import java.util.Arrays;
public class DurationCalculations {
private int duration;
//Constructor
DurationCalculations(int duration, int maxDepth, int avgDepth, int temp, int visibility, int pressureStart,
int pressureEnd, String[] diveConditions, String[] diveActivities) {
setDuration(duration);
setMaxDepth(maxDepth);
setAvgDepth(avgDepth);
setTemp(temp);
setVisibility(visibility);
setPressureStart(pressureStart);
setPressureEnd(pressureEnd);
setAirType(21);
setDiveConditions(diveConditions);
setDiveActivities(diveActivities);
setPressureGroup();
public int getDuration() {
int temp = duration;
return temp;
}
private void setDuration(int duration) {
this.duration = duration;
}
I hope this sample code makes sense. Thank you all for your help in advance.
You want to use methods of your DurationCalculation class, and for that, you've to create an instance of that class.
You can instantiate and use your class like this
DurationCalculations durationCalculation = new DurationCalculations(
/*enter your constructor values*/);
Now you can call all public methods of your DurationCalculations class using durationCalculation variable like this
durationCalculation.getDuration();
You cannot call any private methods from outside of the class, like your setDuration() whose scope is set to private. For it be accessed outside of DurationCalculations class. You need to set it to public

How to randomize(or shuffle) order of Radio Buttons

I want to randomize my radio buttons whenever I reopen my app.
For example my layout is like below:
RBtn1
Rbtn2
Rbtn3
Rbtn4
Now I want to shuffle them whenever I open that particular activity. How can I do this?
As far I know, Layouts in resources are immutable. That means you've to make Views in the dynamic or Java way.
What you can do is use the SecureRandom class (accurate than Random for picking random numbers) to pick a random number and take one RadioButton object from the RadioButton array what you will create.
PoC: I'm explaining first by a now written and tested code →
import java.util.*;
public class HelloWorld{
static String los1 = "taotao1";
static String los2 = "taotao2";
static String los3 = "taotao3";
static String los4 = "taotao4";
static String[] X = {los1,los2,los3,los4};
public static void main(String []args){
Collections.shuffle(Arrays.asList(X));
System.out.println(Arrays.toString(X));
}
/*
Test 1 : [taotao4, taotao3, taotao2, taotao1]
Test 2 : [taotao2, taotao3, taotao4, taotao1]
Test 3 : [taotao3, taotao4, taotao1, taotao2]
Test 4 : [taotao2, taotao4, taotao1, taotao3]
*/
}
Explanation: Collections.shuffle shuffles objects in an Array as you will be able to see by running code.
Conceptual Code: I'm saying it conceptual because writing directly in Stack Answer Box without testing, Test to be done by you.
public class NoNotHelloWorld extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
RadioButton r1,r2,r3,r4; //please declare to avoid NullPtr and also declare their functionalities
LinearLayout xyz = (LinearLayout)findViewById(R.id.xyzwhatisthis);
//though unnesseary cast, but I did it.
ArrayList<RadioButton> dydx = new ArrayList<RadioButton>();
dydx.add(r1);
dydx.add(r2);
dydx.add(r3);
dydx.add(r4);
Collections.shuffle(Arrays.asList(arr));
for(RadioButton dxdy : dydx){
xyz.addView(dxdy)
}
}
}
I think it should work otherwise comment box is there.

global variables between different classes java

i am on the creation of an app in android. its a calculator app. the main activity is where the user could input the equation, and the second activity is where the user can add/edit/delete variables. so i made a new class in another file named Global.java. then i extended it to application, imported everything i need, made s private string, made some public functions, edited the manifest, and initialized it right on my main activity. everything works fine while im only using a string to be passed by the functions but when i started adding what i need, an ArrayList, and made some functions so i could access the list then run it, the app closes. i think its because the arraylist is not allowed to be passed to different classes? am i right or am i just missing something?
please dont downvote my post if i didn't post something needed. i am using aide so there is no log output. code:
Global.java
...
import android.app.*;
import java.util.*;
public class Global extends Application
{
private String s;
public static ArrayList<String> sList;
public String getS() {
return s;
}
public void setS(String ss) {
s=ss;
}
public void add() {
sList.add(s);
}
}
MainActivity.java
...
String s;
...
global=(Global)getApplicationContext();
...
global.setS("jian"); //this one works
global.sList.add("jian"); // this one dont
...
Are you sure you initialized sList, like this:
sList = new ArrayList<String>();
If you didn't, you might want to change its declaration to include this initialization.
public static ArrayList<String> sList = new ArrayList<String>();
Just do
global.add("jian");
since you have an add function to take care of the addition of item to arraylist.
Also, try with this:
public void add(String ss) {
sList.add(ss);
}
You are not instantiating your arraylist.
public static ArrayList<String> sList = new Arraylist<String>();
Also you should read beginner tutorials on Java and android, using a public extension of application like this is a bad idea and you can get log outputs from different apps if Aide doesn't provide that, search play store

Android: Referring to a string resource when defining a log name

In my Android app, I want to use a single variable for the log name in multiple files. At the moment, I'm specifying it separately in each file, e.g.
public final String LOG_NAME = "LogName";
Log.d(LOG_NAME, "Logged output);
I've tried this:
public final String LOG_NAME = (String) getText(R.string.app_name_nospaces);
And while this works in generally most of my files, Eclipse complains about one of them:
The method getText(int) is undefined
for the type DatabaseManager
I've made sure I'm definitely importing android.content.Context in that file. If I tell it exactly where to find getText:
Multiple markers at this line
- Cannot make a static reference to the non-static method getText(int)
from the type Context
- The method getText(int) is undefined for the type DatabaseManager
I'm sure I've committed a glaringly obvious n00b error, but I just can't see it! Thanks for all help: if any other code snippets would help, let me know.
That's because getText is a method of Context. It does not matter if you import the Context class; what matters is that you invoke that method from a Context (for instance, the Activity class is a Context (it inherits Context)).
In that case, what I'd recommend, is creating a Application class that returns the context you want. Here I explain how to do it. After that you can do something like:
public final String LOG_NAME = (String) App.getContext().getText(R.string.app_name_nospaces);
Depending on what sort of 'files' you are using, you can define a TAG that is used.
For example, when I create an app, I like to create a base class for my Activity classes...
Suppose my app is called 'Wibble', and my package is com.mydomain.Wibble...I create my base Activity like so...
package com.mydomain.Wibble
public class WibbleActivity extends Activity {
final protected String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// I'll explain how this next line works later
android.util.Log.d(TAG, "Entered onCreate()...");
}
}
Now suppose I derive an activity as follows...
package com.mydomain.Wibble
public class SomeActivity extends WibbleActivity {
#Override
protexted void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Don't Log "Entered onCreate()..." - WibbleActivity does it for me
android.util.Log.d(TAG, "SomeText");
}
}
Then I derive another Activity...
package com.mydomain.Wibble
public class SomeOtherActivity extends WibbleActivity {
#Override
protexted void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Don't Log "Entered onCreate()..." - WibbleActivity does it for me
android.util.Log.d(TAG, "SomeOtherText");
}
When onCreate() is called for SomeActivity, the output will be...
com.mydomain.Wibble.SomeActivity Entered onCreate()...
com.mydomain.Wibble.SomeActivity SomeText
...when onCreate() is called for SomeOtherActivity however, the output will be...
com.mydomain.Wibble.SomeOtherActivity Entered onCreate()...
com.mydomain.Wibble.SomeOtherActivity SomeOtherText
Neither activity needs to know specifics through an explicit string and the package name is prefixed. Obviously it will only work in certain situations but I find it useful.

Passing a String Array Between Java Classes Android App

I am writing an Android app where I need to pass a string array between two classes. The string initializes fine and I can output the contents of the string fine in the one class but as I try to pass it to another class I get a Null Pointer Exception error. The following is the stripped down version of my code:
accelerometer.java:
public class accelerometer extends Service {
public String movement[];
public void onCreate() {
movement = new String[1000000];
}
public void updatearray() {
movement[arraypos]=getCurrentTimeString();
//Toast.makeText(this, movement[arraypos] , Toast.LENGTH_SHORT).show(); //this correctly displays each position in the array every time it updates so I know the array is working correctly in this file
arraypos+=1;
}
public String[] getmovement(){
return movement;
}
}
wakeupalarm.java:
public class wakeupalarm extends Activity {
private TextView herestext_;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wakeup);
herestext_ = (TextView) findViewById(R.id.TextView01);
accelerometer accelerometercall = new accelerometer();
String movearray[] = accelerometercall.getmovement();
herestext_.setText(movearray[2]);
}
}
I have a feeling I'm missing something very simple but any help would be greatly appreciated!
Thanks,
Scott
You're creating a new accelerometer class, which is completely uninitialized since there is no constructor, then you access its member. Of course it'll be null.
Not sure how your two classes are related, but if the activity is called by the service, then you need to pass the string through the intent (through an extra, for example).
Side note: Class names should always start with a capital letter. Method/variable names should have camel case, i.e. "updateArray". Also, you can format your code here by selecting it and pressing CTRL+K.
Your first problem, I think, is that you are creating an array with a million slots in it. Do you really mean to be doing that? It's going to take a lot of memory---quite possibly more than is available. You should instead look to having a Vector of Strings that you extend as necessary.

Categories