Greeting peeps, need help on this error. trying googling but did not solve the issue. i did put remarks in which lines the errors occur.
notice below code have 2 different java class
[IMG="screenshot"]http://i.imgur.com/XYFHZOz.png[/IMG]
public class QuestionAndAnswer {
public List<String> allAnswers; // distractors plus real answer
public String answer;
public String question;
public String selectedAnswer;
public int selectedId = -1;
public QuestionAndAnswer(String question, String answer, List<String> distractors) {
this.question = question;
this.answer = answer;
allAnswers = new ArrayList<String>(distractors);
// Add real answer to false answers and shuffle them around
allAnswers.add(answer);
Collection.shuffle(allAnswers); //error on this line
}
public boolean isCorrect() {
return answer.equals(selectedAnswer);
}
}
public class UjiSalah extends Activity {
RadioGroup rg;
int currentQuestion = 0;
TextView tv;
List<QuestionAndAnswer> quiz = new ArrayList<QuestionAndAnswer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uji_salah);
tv = (TextView) findViewById(R.id.tvque);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
// Setup a listener to save chosen answer
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId > -1) {
QuestionAndAnswer qna = quiz.get(currentQuestion);
qna.selectedAnswer = ((RadioButton) group.findViewById(checkedId)).getText().toString();
qna.selectedId = checkedId;
}
}
});
String[] question = {"Bilangan Rokaat Solah Zuhur ?","Bilangan Rokaat Solat Subuh ?","Bilangan Rokaat Solat Maghrib ?"};
String[] answer = { "4 rokaat","2 rokaat","3 rokaat" };
String[] distractor = { "5 rokaat","1 rokaat","4 rokaat","2 rokaat","3 rokaat","4 rokaat","4 rokaat","5 rokaat","3 rokaat" };
ArrayList<String> distractorList = Arrays.asList(distractor); //error on this line
int length = question.length;
for(int i = 0; i < length; i++)
quiz.add(new QuestionAndAnswer(question[i], answer[i], distractorList.subList(i * 3, (i + 1) * 3)));
Collection.shuffle(quiz); //error here
fillInQuestion();
}
public void fillInQuestion() {
QuestionAndAnswer qna = quiz.get(currentQuestion);
tv.setText(qna.question);
// Set all of the answers in the RadioButtons
int count = rg.getChildCount();
for(int i = 0; i < count; i++)
((RadioButton) rg.getChildAt(i)).setText(qna.allAnswers.get(i));
// Restore selected answer if exists otherwise clear previous question's choice
if(qna.selectedId > -1)
rg.check(qna.selectedId);
else
rg.clearCheck();
}
}
+1#Prerak Sola, you can either declare allAnswers as ArrayList or cast it like so:
Collection.shuffle((ArrayList)allAnswers);
List doesn't implement Collection interface, but ArrayList does:
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
List quiz = new ArrayList<>();
to
ArrayList<QuestionAndAnswer> quiz = new ArrayList<>();
Related
I wrote a quiz game in android. I want every time that game goes to next question, all buttons texts also update with each string that exists in string.xml. My string.xml file has include <string> values like below for every questios:
<!-- Second question-->
<string name="secondQ_A1">Oracle</string>
<string name="secondQ_A2">Apple</string>
<string name="secondQ_A3">Sun Microsystems</string> <!-- Right answer -->
<string name="secondQ_A4">IBM</string>
And here's the code:
private Question[] questions = new Question[] {
new Question(R.drawable.first, R.string.first_question_text, R.string.firstQ_A2),
new Question(R.drawable.second, R.string.second_question_text, R.string.secondQ_A3),
new Question(R.drawable.third, R.string.third_question_text, R.string.thirdQ_A2),
};
private ImageView questionImage;
private TextView questionText;
private Button[] answerButtons;
private int currentQuestion = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_play);
//Initializing
initializeFields();
int textQ = questions[currentQuestion].getResQuestionText();
questionText.setText(textQ);
int imageQ = questions[currentQuestion].getResQuestionImg();
questionImage.setImageResource(imageQ);
for (Button button : answerButtons) {
button.setOnClickListener(v -> {
if (currentQuestion + 1 < questions.length) {
currentQuestion += 1;
updateQuestion();
}
});
}
}
public void updateQuestion() {
int textQ = questions[currentQuestion].getResQuestionText();
questionText.setText(textQ);
int imageQ = questions[currentQuestion].getResQuestionImg();
questionImage.setImageResource(imageQ);
List<Integer> firstQ_answers = new LinkedList<>();
firstQ_answers.add(R.string.firstQ_A1);
firstQ_answers.add(R.string.firstQ_A2);
firstQ_answers.add(R.string.firstQ_A3);
firstQ_answers.add(R.string.firstQ_A4);
for (int i = 0; i< answerButtons.length; i++) {
questions[currentQuestion].setOptions(firstQ_answers);
answerButtons[i].setText(questions[currentQuestion].getOptions().get(i));
}
}
And also Question class:
public class Question {
private int resQuestionText;
private int resQuestionImg;
private int resAnswer;
public Question(int resQuestionImg, int resQuestionText, int resAnswer) {
this.resQuestionImg = resQuestionImg;
this.resQuestionText = resQuestionText;
this.resAnswer = resAnswer;
}
public int getResQuestionText() {
return resQuestionText;
}
public int getResQuestionImg() {
return resQuestionImg;
}
public int getResAnswer() {
return resAnswer;
}
}
The updateQuestion() method just work for question's image and text, but the buttons has no text. I want to update buttons text with that string.xml file values above. Actually I got no idea about it, anyone can guide me?
From your code , you are not even updating it , so you have to do something like this in your updateQueation() method :
answerButtons[0].setText(getString(R.string.secondQ_A1));
answerButtons[1].setText(getString(R.string.secondQ_A2));
answerButtons[2].setText(getString(R.string.secondQ_A3));
answerButtons[3].setText(getString(R.string.secondQ_A4));
As best practice you should define a global two dimensional array to hold all questions index and its options like :
int[][] myOptions ={{allFirstQuestionAnswersResHere},{second},{third},...};
And then in updateQuestion() use question number to get the options from your global array like :
for(int i=0;i<answerButtons.length();i++){
answerButtons[i].setText(myOptions[questionIndex][i]);
}
Enjoy !
you are using int as a text in your question that's why it cant be set so
questionText.setText(" "+textQ);
or change int questionText to String questionText.
You can achieve the same by changing your question class like this
public class Question {
private int resQuestionText;
private int resQuestionImg;
private int resAnswer[];
public Question(int resQuestionImg, int resQuestionText, int resAnswer[]) {
this.resQuestionImg = resQuestionImg;
this.resQuestionText = resQuestionText;
this.resAnswer = resAnswer;
}
public int getResQuestionText() {
return resQuestionText;
}
public int getResQuestionImg() {
return resQuestionImg;
}
public int [] getResAnswer() {
return resAnswer;
}
}
and then in your updateQuestion method
public void updateQuestion() {
// you can get array of button text for each question like below and can update your buttons text by iterating through this array
int buttonTexts[] = questions[currentQuestion].getResAnswer();
int textQ = questions[currentQuestion].getResQuestionText();
questionText.setText(textQ);
int imageQ = questions[currentQuestion].getResQuestionImg();
questionImage.setImageResource(imageQ);
}
The program is supposed to use the premade question and answers and check if the true or false button is pressed. It has a main activity file and one class file called Question, but when it's ran the output says that "error: local variable questions is accessed from within inner class; needs to be declared final", how do I fix it? adding the final keyword in front of the array list declaration doesn't work, thanks.
public class MainActivity extends Activity {
private TextView display_question;
private TextView display_result;
private static int rand_int;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random random = new Random();
display_question = findViewById(R.id.txt_question);
display_result = findViewById(R.id.txt_result);
ArrayList<Question> questions; //in class method
questions = Question.getQuestions(); //in class method, arraylist
rand_int = random.nextInt(4);
display_question.setText(questions.get(rand_int).getQuestion());// where i is an integer
Button btn_true = findViewById(R.id.btn_true);
btn_true.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean input = true;
String output = "correct answer";
String output2 = "incorrect answer";
if (questions.get(rand_int).isAnswer()==input){
display_result.setText(output);
}
else {
display_result.setText(output2);
}
}
});
Button btn_false = findViewById(R.id.btn_false);
btn_false.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean input = false;
String output = "correct answer";
String output2 = "incorrect answer";
if (questions.get(rand_int).isAnswer()==input){
display_result.setText(output);
}
else {
display_result.setText(output2);
}
}
});
Button btn_next = findViewById(R.id.btn_next);
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rand_int = random.nextInt(4);
display_question.setText(questions.get(rand_int).getQuestion());// where i is an integer
}
});
}
}
Question class:
import java.util.ArrayList;
public class Question {
private String question;
private boolean answer;
private Question(String question, boolean answer) {
this.question = question;
this.answer = answer;
}
public String getQuestion() {
return question;
}
public boolean isAnswer() {
return answer;
}
public static ArrayList<Question> getQuestions(){
ArrayList<Question> questions = new ArrayList<>();
questions.add(new Question("B", false));
questions.add(new Question("A", true));
questions.add(new Question("c", false));
questions.add(new Question("d", false));
questions.add(new Question("e", true));
return questions;
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
i'm making an anagramm app in android. I have some problem, i have buttons with text "A", "B", "C" for example. My code generate string "ABC", and my ans[i] = "ABC". But when i compare them, it returns me false. Help pls.
There are code example, i have problem in
if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
public class MainActivity extends AppCompatActivity {
public List<Button> btns;
public List<String> ans;
String word = "";
String checkStr;
EditText text;
private static final int[] btn_id = {
R.id.btn1,
R.id.btn2,
R.id.btn3,
R.id.btn4,
R.id.btn5,
R.id.btn6,
R.id.btn7,
R.id.btn8
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btns = new ArrayList<Button>();
ans = new ArrayList<String>();
text = findViewById(R.id.txt);
text.setEnabled(false);
fillAnswers();
for (int i = 0; i < btn_id.length; i++){
Button b = findViewById(btn_id[i]);
btns.add(b);
}
}
public void fillAnswers(){
ans.add("ERATO");
ans.add("MARI");
ans.add("AIR");
}
public void onClick(View v){
Button b = (Button)v;
char str = b.getText().charAt(0);
addToString(str);
text.setText(word);
b.setEnabled(false);
// Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
}
public void okClick(View v){
//Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
/* for (int i = 0; i < 3; i++){
// Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
if (checkStr == ans.get(i)){
Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
}
}*/
word = "";
text.setText(word);
for (int i = 0; i < btn_id.length; i++){
Button b = findViewById(btn_id[i]);
b.setEnabled(true);
}
}
public void addToString(char s){
word += s;
}
}
You have to compare string values with equals
ans[i].equals("ABC");
Or
if (word.equals("ERATO")) Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
I implemented AsyncTask to execute results. Here is the error I get...
FATAL EXCEPTION: AsyncTask #1
Process: ai69.psoui, PID: 3287
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.app.Activity.<init>(Activity.java:754)
at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:31)
at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:37)
at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:30)
at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:79)
at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
at ai69.psoui.MainActivity.<init>(MainActivity.java:0)
at android_tests.CustomUseCase.<init>(CustomUseCase.java:19)
at android_tests.TestFactory.getTest(TestFactory.java:15)
at ai69.psoui.ParticleActivity.runTest(ParticleActivity.java:91)
at ai69.psoui.ParticleActivity$runTests.doInBackground(ParticleActivity.java:53)
at ai69.psoui.ParticleActivity$runTests.doInBackground(ParticleActivity.java:50)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
I have looked at different SOF posts about "Looper.prepare()" but the thing is, prior to a few changes in changing static variables to getter/setter methods, my UI was working fine.
Here is my code...
public class ParticleActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "PSOUI.MESSAGE";
private ProgressDialog pd;
private double[] results = {-1.0, -1.0, -1.0};
EditText particles;
EditText iterations;
EditText userSol;
EditText userBatt;
private double battery;
private double solution;
//int numberOfDimensions = MainActivity.dimensions.size();
//public ArrayList<Double> costData = MainActivity.costDATA; //costs that
the user enters for each resource
//public ArrayList<Double> costWlan = MainActivity.costWLAN;
//public ArrayList<Double> costUtilities = MainActivity.costUTILITY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_particle);
particles = (EditText) findViewById(R.id.particles);
iterations = (EditText) findViewById(R.id.iterations);
userSol = (EditText) findViewById(R.id.solution);
userBatt = (EditText) findViewById(R.id.battery);
pd = null;
runPSOButton();
}
#Override
public void onPause(){
super.onPause();
if(pd != null)
pd.dismiss();
}
public class runTests extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //sort this out
results = runTest("CustomUseCase"); //i only want to run this one!!!
return null;
}
#Override
protected void onPostExecute(Void v) {
if (results != null && results.length > 0 && results[0] != -1) {
loadIntent(results);
} //otherwise it will evaluate the next logic statement results[0] != -1 with no chance of NulLPointerException
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(ParticleActivity.this, "Busy", "Algorithm is currently executing");
pd.setCancelable(true);
pd.show();
}
}
public void runPSOButton() {
final Button runPSO = (Button) findViewById(R.id.runpso);
runPSO.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
new runTests().execute();
}
});
}
public double[] runTest(String test) {
int noPart = Integer.parseInt(particles.getText().toString());
int noIter = Integer.parseInt(iterations.getText().toString());
return new TestFactory(noPart, noIter).getTest(test).test();
}
public void loadIntent(double[] result) {
double[] results = result;
Intent intent = new Intent(this, SolutionActivity.class);
intent.putExtra(EXTRA_MESSAGE, results);
startActivity(intent);
}
public double setBatteryCost(){
battery = Double.parseDouble(userBatt.getText().toString());
return battery;
}
public double getBatteryCost(){return setBatteryCost();}
public double setUserSolution(){
solution = Double.parseDouble(userSol.getText().toString());
return solution;
}
public double getUserSolution(){return setUserSolution();}
}
Can someone explain whats happening? New to Android Studio and have been developing for only 3 months in Java, so for any solutions can I kindly request an explanation for it too? Much appreciated thank you
UPDATE:
Here is my mainActivity...
public class MainActivity extends AppCompatActivity {
//declare variables
EditText name;
EditText data;
EditText wlan;
EditText utility;
Button addservice;
ListView lv;
ListView lv2;
ListView lv3;
ListView lv4;
public ArrayList<String> servicenames;
public ArrayList<String> dimensions;
public ArrayList<Double> costDATA;
public ArrayList<Double> costWLAN;
public ArrayList<Double> costUTILITY;
ArrayAdapter<String> namesAdapter;
ArrayAdapter<Double> dataAdapter;
ArrayAdapter<Double> wlanAdapter;
ArrayAdapter<Double> utilityAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//map the components to the variables
name = (EditText) findViewById(R.id.servicename);
data = (EditText) findViewById(R.id.data);
wlan = (EditText) findViewById(R.id.wlan);
utility = (EditText) findViewById(R.id.utility);
addservice = (Button) findViewById(R.id.addservice);
lv = (ListView) findViewById(R.id.lv);
lv2 = (ListView) findViewById(R.id.lv2);
lv3 = (ListView) findViewById(R.id.lv3);
lv4 = (ListView) findViewById(R.id.lv4);
//create arraylists for each component
servicenames = new ArrayList<String>();
dimensions = new ArrayList<String>();
costDATA = new ArrayList<Double>();
costWLAN = new ArrayList<Double>();
costUTILITY = new ArrayList<Double>();
//create adapters to pass on the arraylist
namesAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, servicenames);
dataAdapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, costDATA);
wlanAdapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, costWLAN);
utilityAdapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, costUTILITY);
//display each arraylist in the listviews
lv.setAdapter(namesAdapter);
lv2.setAdapter(wlanAdapter);
lv3.setAdapter(dataAdapter);
lv4.setAdapter(utilityAdapter);
namesAdapter.notifyDataSetChanged();
dataAdapter.notifyDataSetChanged();
wlanAdapter.notifyDataSetChanged();
utilityAdapter.notifyDataSetChanged();
dimensions.add("DATA");
dimensions.add("WLAN");
onClickBtn();
}
public void onClickBtn() { //when user clicks button, the user input is added to the listview, and cleared for the next service
addservice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String namesOfService = name.getText().toString(); //user input for service names
String costOfData = data.getText().toString(); //user input for data costs
String costOfWLAN = wlan.getText().toString(); //user input for wlan costs
String costOfUtility = utility.getText().toString(); //user input for utility costs
Double doubleWLAN = Double.parseDouble(costOfWLAN); //convert user input into double
Double doubleData = Double.parseDouble(costOfData);
Double doubleUtility = Double.parseDouble(costOfUtility);
costDATA.add(doubleData); //add the double costs to each resource arraylist
costWLAN.add(doubleWLAN);
costUTILITY.add(doubleUtility);
servicenames.add(namesOfService);
dimensions.add(namesOfService);
namesAdapter.notifyDataSetChanged();
dataAdapter.notifyDataSetChanged();
wlanAdapter.notifyDataSetChanged();
utilityAdapter.notifyDataSetChanged();
name.setText(""); //empty the edit text fields when button is clicked
wlan.setText("");
data.setText("");
utility.setText("");
}
});
}
public void nextButton(View view) //next button, onto the next activity
{
Intent intent = new Intent(MainActivity.this, ParticleActivity.class);
startActivity(intent);
}
public int getDimensions(){ return dimensions.size();}
public ArrayList<String> getElements(){ return servicenames;}
public ArrayList<Double> getCostDATA(){;return costDATA;}
public ArrayList<Double> getCostWLAN(){return costUTILITY;}
public ArrayList<Double> getCostUTILITY(){return costUTILITY;}
}
As you can see, the arraylists that store the user input is accessible using getters and setters rather than setting the arraylists static (which I did before). I access these arraylists in another class called CustomUseCase and CustomService. Here is the code for customUseCase:
public class CustomUseCase extends Test {
MainActivity mainActivity = new MainActivity();
ParticleActivity particleActivity = new ParticleActivity();
private int numberOfDimensions = mainActivity.getDimensions();
private ArrayList<Double> costData = mainActivity.getCostDATA(); //costs that the user enters for each resource
private ArrayList<Double> costWlan = mainActivity.getCostWLAN();
private ArrayList<Double> costUtilities = mainActivity.getCostUTILITY();
private double batteryCost = particleActivity.getBatteryCost();
private int maxIter;
private int noParticles;
public CustomUseCase(int noParticles, int maxIterations) {
this.noParticles = noParticles;
this.maxIter = maxIterations;
}
#Override
public double[] test() {
long max = 10000; //maximum number of iterations, override //2 bits for the WLAN/DATA and the rest for the amount of services the user inputs
double[] results = new double[numberOfDimensions]; //new array of results with numOfBits as number of elements
for (int i = 1; i <= max; i++) {
BinaryPso bpso = new BinaryPso(noParticles,
numberOfDimensions);
ParticleActivity getUserInput = new ParticleActivity();
CustomService customService =
new CustomService(batteryCost, costData, costWlan, costUtilities);
long start = System.currentTimeMillis(); //start time
bpso.setSolution(getUserInput.getUserSolution()); //changed this to user selection
bpso.optimize(maxIter, customService, true);
this.found += (bpso.getFound() ? 1 : 0);
this.iterations += bpso.getSolIterations(); //use the method in bpso to get number of iterations taken
long end = System.currentTimeMillis() - start; //end time minus start time
this.sumTimes += end; //override the time spent variable
System.out.println("P-value: " + Particle.getValue(Particle.bestGlobal()));
System.out.println("P-bitCombo: " + Arrays.toString(Particle.bestGlobal()));
System.out.println("P-goodness: " + customService.getGoodness(Particle.bestGlobal()));
}
System.out.println("Time: " + sumTimes / max);
System.out.println("Iterations: " + iterations / max);
System.out.println("Success Rate: " + found);
boolean[] bestCombo = Particle.bestGlobal();
for (Boolean b : bestCombo) {
System.out.print(b + " ");
}
System.out.println();
results[0] = sumTimes / max;
results[1] = iterations / max;
results[2] = found;
return results;
}
public static List<Boolean> getBestComboArray() { //method to get best global array
boolean[] bestCombo = Particle.bestGlobal(); //calculate best global
List<Boolean> bestCombi = new ArrayList<>(bestCombo.length);
for (int x = 0; x < bestCombo.length; x++) {
bestCombi.add(bestCombo[x]);
}
return bestCombi;
}
}
And here is my CustomService class:
public class CustomService implements Goodness {
MainActivity mainActivity = new MainActivity();
private int numOfDimensions = mainActivity.getDimensions();
private ArrayList<String> serviceNames = mainActivity.getElements();
private ArrayList<Double> costData = mainActivity.getCostDATA();
private ArrayList<Double> costWlan = mainActivity.getCostWLAN();
private ArrayList<Double> costUtilities = mainActivity.getCostUTILITY();
private double batteryCost;
public void setBatteryCost(double batteryCost) {
this.batteryCost = batteryCost;
}
public CustomService(double batteryCost, ArrayList<Double> costData, ArrayList<Double> costWlan,
ArrayList<Double> costUtilities) {
if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
}
this.batteryCost = batteryCost; //make sure you add battery field to UI, user enters battery level
this.costData = costData;
this.costWlan = costWlan;
this.costUtilities = costUtilities;
}
public double getGoodness(boolean[] bits) {
double utility = 0.0;
double rcost = 0.0;
ArrayList<Double> resourceCost = new ArrayList<Double>();
Collections.sort(costUtilities); //sort the costUtilities arraylist
double maxValue = Collections.max(costUtilities); //get the maximum value from the costUtilities arraylist
if(bits[0] && bits[1]){
return -500;
}
if(!bits[0] || bits[1]){
return -1000;
}
for(int x = 1; x < numOfDimensions; x++){
if(bits[x] == costUtilities.contains(maxValue)){
return -1900;
}
}
if (bits[0]) {
resourceCost = costData;
} else if (bits[1]) {
resourceCost = costWlan;
}
for (int i = 2; i <= serviceNames.size(); i++) { //if i = 2, 2<=4
if (bits[i]) {
utility += costUtilities.get(i-2);
rcost += resourceCost.get(i-2);
}
}
if (rcost < batteryCost) {
return utility;
}
return utility * 0.50;
}
}
you can not update UI items on nonUIThread.
search usage of runOnUiThread on google.
call your method in runOnUiThread().
#Override
protected Void doInBackground(Void... params) { //sort this out
runOnUiThread (new Runnable() {
public void run() {
results = runTest("CustomUseCase");
}
}
return null;
}
This explains all: "Can't create handler inside thread that has not called Looper.prepare()" and it seems your TestFactory() method creates a Handler without a Looper.
Inside a secondary Thread a Handler should be like this
....
Looper.prepare();
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// do work with received messages
}
};
Looper.loop();
....
More info : What is the purpose of Looper and how to use it?
i would like to generate 24 string values on 24 textview which i created the xml file in android and also i code for the getid and set listener but not mentioned here.
In the override oncick method i define the click fun method.
In this code i simply code for the integer values but now i would like to compare from the string array which has static values like
String[] value = {11,12,13,14,15,16,17,18,19,20,21,22,11,12,13,14,15,16,17,18,19,20,21,22};
Please help me to resolve my problem.
public class GameDemo extends Activity implements AnimationListener, OnClickListener
{
FrameLayout iv1,iv2,iv3,iv4,iv5,iv6,iv7,iv8,iv9,iv10,iv11,iv12,iv13,iv14,iv15,iv16,iv17,iv18,iv19,iv20,iv21,iv22,iv23,iv24;
TextView tv1,tv2,tv3,tv4,tv5,tv6,tv7,tv8,tv9,tv10,tv11,tv12,tv13,tv14,tv15,tv16,tv17,tv18,tv19,tv20,tv21,tv22,tv23,tv24;
Animation an1,an2;
int i1,counter,score,rev_count,level_counter;
boolean r_c,s_c;
Integer[] no;
FrameLayout[] count,rem,revise;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_demo);
an1 = AnimationUtils.loadAnimation(this,R.anim.flip1);
an1.setAnimationListener(this);
an2 = AnimationUtils.loadAnimation(this,R.anim.flip1);
an2.setAnimationListener(this);
level_counter=24;
getIDForAll();
setListnerForAll();
counter=1;
rev_count=0;
no = new Integer[25];
count = new FrameLayout[3];
rem = new FrameLayout[3];
revise = new FrameLayout[8];
int i=0;
for(i=0 ; i<24 ; i++)
{
Random r = new Random();
i1 = r.nextInt(25 - 1) + 1;
if(i!=0)
{
while(Arrays.asList(no).contains(i1))
{
r = new Random();
i1 = r.nextInt(25 - 1) + 1;
}
no[i]= i1 ;
}
else
{
no[i]= i1 ;
}
}
public void click_fun(FrameLayout arg0, TextView arg1, int n)
{
if(counter<2)
{
arg0.setAnimation(an1);
if(no[n]<=12)
{
arg1.setText(""+no[n]);
arg0.setBackgroundResource(android.R.color.white);
}
else
{
arg1.setText(""+(no[n]-12));
arg0.setBackgroundResource(android.R.color.white);
}
arg0.setTag(no[n]);
count[counter] = arg0;
counter++;
Log.i("animate", "anim2");
}
else
{
Log.i("animate", "animo1");
arg0.setAnimation(an1);
if(no[n]<=12)
{
arg1.setText(""+no[n]);
arg0.setBackgroundResource(android.R.color.white);
}
else
{
arg1.setText(""+(no[n]-12));
arg0.setBackgroundResource(android.R.color.white);
}
arg0.setTag(no[n]);
count[counter] = arg0;
counter++;
Log.i("animate", "animo2");
Uri uri = Uri.parse("android.resource://com.game/drawable/ic_launcher");
int temp1 = (Integer) count[1].getTag();
int temp2 = (Integer) arg0.getTag();
Log.i("animate", "animo3");
if((temp1-temp2)==-12 || temp1-temp2==12)
{
rem[1]=count[1];
rem[2]=count[2];
s_c=true;
score=score+10;
score_lbl.setText("Score : "+score);
score=score+10;
score_lbl.setText("Score : "+score);
level_counter=level_counter-2;
}
else
{
rev_count++;
revise[rev_count]=count[1];
rev_count++;
revise[rev_count]=count[2];
r_c=true;
score=score-2;
score_lbl.setText("Score : "+score);
}
counter=1;
}
}
I don't think I understand your situation fully.
1. Create an array of String resources:
private Integer[] Strings = { many, strings, R.string.stringa };
2. Call a method to get a random resource:
getRandomString(int);
3. Return a random String:
private String getRandomString(int random)
return getString( Strings[ random ] );