Working in Android Studio and I've run into a few small issues so I figured I would ask for help / advice.
I am currently working on a small testing application that would allow users to open the application and select practice test or timed test (as displayed in picture 1). If users select practice test they have unlimited time to select an answer and the systems tells them if they have picked the correct answer. If the user selects timed than the system allots a predetermined amount of time and after each question the score is added and calculated, here lies my issues.
1.) Right now my code loops endlessly, ideally (at least for the timed aspect) I want my code to go through the 5 questions scoring the correct or incorrect based on the users selection. Then I want to display the # correct and in correct.
So my question is two fold, first how do I go about preventing my code from looping endless so I can begin to record iterations as ++correctAnswer ++incorrect answer. And, when it comes time to display the results, should I create a new activity to display the results.
Android is a bit confusing to me, I hope I have provided enough information and I appreciate and helping advice.
Thank You
** Code **
private int currentQuestion;
private String[] questions;
private String[] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init()
{
questions = new String[]{"What is the acronym for Computer Science and Information Management?",
"What is the CSIT corse number of the class you are currently in?",
"What Android program do we use to create android applications?"};
answers = new String[]{"CSIT","2250", "Android Studio"};
currentQuestion = -1;
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView)
findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
answerButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
checkAnswer();
}});
questionButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
showQuestion();
}});
}
// Display current quesiton
public void showQuestion()
{
currentQuestion++;
if(currentQuestion == questions.length)
currentQuestion =0;
questionView.setText(questions[currentQuestion]);
answerView.setText("");
answerText.setText("");
}
// Return true if answer is correct
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(answers[currentQuestion]));
}
// Display correct or incorrec results
public void checkAnswer()
{
String answer = answerText.getText().toString();
if(isCorrect(answer))
answerView.setText("You are correct!");
else
answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);
}}
Home Screen
Quiz Screen
Just have a condition check if currentQuestion == 5 at the end of checkAnswer(). If so proceed to the results screen
Related
I have a problem that I want to use jsoup to grab news but always fail.
this is news website.
https://www3.nhk.or.jp/news/
this is my picture . which I circle is I wanted data.
https://drive.google.com/open?id=1KJAyOSdHO8APPD6_A9MjxkoFjekcQLXt
but no matter what I do. it always get wrong data or empty.
this is my program.
public class News extends AppCompatActivity {
Button ok;
private static final String url ="https://www3.nhk.or.jp/news/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
ok=(Button)findViewById(R.id.ok);
ok.setOnClickListener(okbtn);
}
private Button.OnClickListener okbtn=new Button.OnClickListener(){
public void onClick(View v){
try{
Connection.Response response = Jsoup.connect(url).execute();
String body = response.body();
Document data = Jsoup.parse(body);//visible-phone print_hide
Elements country=data.select("main");
Elements main=data.select("div[id=module module--news-main index-main]");
for(Element e1: country)
{
mytoast(e1+"");
}
}
catch(Exception ex){ex.printStackTrace() ;}
}
};
private void mytoast(String str)
{
Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
please help me
thanks
You can try to see it's HTML first.
If you can't see it, you don't use jsoup.
There's a small hint in its comment:
このページではJavaScriptを使用しています
=>This is generated by JavaScript
If it's generated, you can't find it from Jsoup.
In this case, I'll use Chrome's tool to monitor the XHR tab
Look into each XHR request, and find the most possible one,
for example, I see this
https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640
A part of the response:
"id":"193411",
"title":"三菱UFJ銀行 新規口座は原則デジタル通帳に",
"pubDate":"Thu, 30 May 2019 04:03:11 +0900",
"cate":"5",
...
"id":"193437",
"title":"エアレース世界選手権 今季限りで終了",
"pubDate":"Thu, 30 May 2019 09:40:37 +0900",
So this is exactly what you want. It comes from another link!
You don't need Jsoup, just HttpGet the link
https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640
And I think the numbers looks like UnixTime,
So I check the current time is : 1559184830782, that's it.
Just use that link as API and time as parameter.
I'm currently working on a school project in Android Studio and so far I've written a code which generates random equations.
Now I display two equations on the screen and the user then has to decide wether the second equation is bigger or smaller than the first one. If the second is bigger, the user presses the button 'bigger', if the second one is smaller, the user presses the button with 'smaller'.
Now I'm trying to write the code that if the user pressed correct, it generates a new equation, if he was wrong, the process stops.
I was thinking of if statements like so:
final ArrayList<String> arrayListCheck = new ArrayList<String>();
if(doubleAnswer1 > doubleAnswer2){
arrayListCheck.add("smaller");
} else {
arrayListCheck.add("bigger");
}
final Button buttonBigger = (Button)findViewById(R.id.button_bigger);
final Button buttonSmaller = (Button)findViewById(R.id.button_smaller);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger)){
arrayListCheck.add("bigger");
} else {
arrayListCheck.add("smaller");
}
}
};
buttonBigger.setOnClickListener(listener);
buttonSmaller.setOnClickListener(listener);
In the arraylist arrayListCheck it will store either 'bigger' or 'smaller'. Now I want to check if the elements in the arraylist are both the same (either both 'bigger' or 'smaller'), if so a new equation will be generated. If the elements in the arraylist are different (not both the same), the process will be stopped.
I don't know if that really works, so it would be nice if someone could help me with this.
If there is anything unclear in my question, feel free to ask and I will try to clarify the problem :)
Thank you already in advance for your help!
I wouldn't use an ArrayList for that.
I would do the following:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleAnswer1 < doubleAnswer2) {
Log.v("TAG", "you are right");
} else if(v.equals(buttonSmaller) && doubleAnswer1 > doubleAnswer2) {
Log.v("TAG", "you are right");
} else {
Log.v("TAG", "you are wrong");
}
}
};
Arrays are not really neccessary for this kind of simple comparison.
I'm making a android app .
I wanna make a RSS reader application .
I get help of an Udemy's course , I almost copy all the codes , what codes he has said on course , but I've got problem! contrariwise video course !
I have problem in this codes :
private String mFileContents;
private Button btnParse;
private ListView xmlList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnParse = (Button) findViewById(R.id.btnParse);
btnParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseApplications parseApplications = new ParseApplications(mFileContents);
parseApplications.process();
ArrayAdapter<Application> arrayAdapter = new ArrayAdapter<Application>(
MainActivity.this, R.layout.list_item, parseApplications.getApplications());
xmlList.setAdapter(arrayAdapter);
}
});
xmlList = (ListView) findViewById(R.id.xmlList);
DownloadData downloadData = new DownloadData();
downloadData.execute("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=10/xml");
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
my APP will connect to 10 top apps of apple market and show them ( show apps' name and artist and release date between two line )
It should be like this :
App
instead that my app get error and stop ! and as far as I know that get error for 'mFileContents' , it is string but as Android Studio comment : I must make a public string in ParseApplications class ! but when I do that , app doesn't work still ! how can I resolve that ?
I am creating a quiz game which is working fine,but the problem am encountering is that whenever the user selects the correct answer, its shows it as wrong answer,meanwhile it's the correct answer, it's turns out the correct answer is not at the correct location.
Here is my code so far, any ideas how i can fix this.
public class RiddleGuessActivity extends AppCompatActivity {
TextView riddleQuestionTextView;
Button btn1, btn2, btn3, btn4, btnContinue, btnOk;
ArrayList<String> riddles = new ArrayList<>();
ArrayList<String> answers = new ArrayList<>();
int locationOfCorrectAnswers = 0,incorrectAnswers = 0;
ArrayList<String> options = new ArrayList<>();
LinearLayout gameOverLayout;
LinearLayout buttonLayout;
RelativeLayout resultLayout;
TextView timerTextView;
TextView answerTextView;
TextView levelTextView, scoreTextView;
TextView gameOverTextView;
int levelCounter = 1, scoreCounter, riddleCounter = 0;
public void chosenRiddle (View view) {
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswers))) {
//Toast.makeText(RiddleGuessActivity.this, "Correct", Toast.LENGTH_SHORT).show();
levelCounter++;
scoreCounter+=60;
riddleCounter++;
levelTextView.setText(String.valueOf(levelCounter));
scoreTextView.setText(String.valueOf(scoreCounter));
result();
}else {
Toast.makeText(RiddleGuessActivity.this, "Wrong, It was " +
answers.get(riddleCounter), Toast.LENGTH_SHORT).show();
gameOver();
}
}
public void generateRiddles () {
riddles.add("I kiss my mother before i die. What am i ?");
riddles.add("It is greater than God and more evil than the devil. The poor have it, the rich need it and if you eat it you'll die. What am i ?");
riddles.add("It walks on four legs in the morning, two legs at noon and three legs in the evening. What am i ?");
riddles.add("I am the beginning of the end, and the end of time and space. I am essential to creation and i surround everyplace. What am i ?");
riddles.add("What always runs but never walks, often murmurs, never talks, has a bed but never sleeps, has a mouth but never eats. What am i ?");
riddles.add("At night they come without being fetched, By day they are lost without being stolen. What am i ?");
riddles.add("The one who makes it, sells it. The one who buys it, never uses it. The one that uses it never knows that he's using it. What am i ?");
riddles.add("The more you have of it, the less you see. What am i ?");
riddles.add("I am always hungry, i must be fed, the finger i touch will soon turn red. What am i ?");
riddles.add("If you break me, i do not stop working, if you touch me, i may snared, if you lose me, nothing will matter. What am i ?");
answers.add("Matches");
answers.add("Nothing");
answers.add("Man");
answers.add("Letter E");
answers.add("River");
answers.add("The Stars");
answers.add("A Coffin");
answers.add("Darkness");
answers.add("Fire");
answers.add("Heart");
answers.add("The Moon");
answers.add("Food");
answers.add("Love");
answers.add("Mouth");
answers.add("Money");
Random random = new Random();
riddleQuestionTextView.setText(riddles.get(riddleCounter));
locationOfCorrectAnswers = random.nextInt(4);
options.clear();
for (int i = 0; i < 4; i++) {
if (i == locationOfCorrectAnswers &&
!options.contains(answers.get(riddleCounter))) {
options.add(answers.get(riddleCounter));
}else {
incorrectAnswers = random.nextInt(answers.size());
while (incorrectAnswers == riddleCounter) {
incorrectAnswers = random.nextInt(answers.size());
}
if(!options.contains(answers.get(incorrectAnswers)))
options.add(answers.get(incorrectAnswers));
else --i;
}
}
btn1.setText(options.get(0));
btn2.setText(options.get(1));
btn3.setText(options.get(2));
btn4.setText(options.get(3));
}
Are you missing an onCreate method??
Anyways, I suggest you add the correctAnswer followed by the incorrect options. Basically, forget random numbers and while loops.
Then Collections.shuffle() the list.
Then scan the list for the location of the correct answer.
I have people complaining my application gets FC when they launch it (meanwhile others never had a single problem). Here is my full activity source. Since it happens on devices I don't own I can not fix it. From what they tell me it doesn't work on: Motorola Blackflip, Motorola Dext, Motorola CLIQ XT. Guess Motorola doesn't like my app after all...
Could it be that I allow a minSdkVersion="3"? I tested 1.5 on the emulator and worked fine...
Thank you in advance for your responses.
public class workit extends Activity implements OnClickListener {
Button yay;
Button yay0;
Button yay1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
yay = (Button) findViewById(R.id.gostart);
yay.setOnClickListener(this);
yay0 = (Button) findViewById(R.id.dontstart);
yay0.setOnClickListener(this);
yay1 = (Button) findViewById(R.id.exit);
yay1.setVisibility(ImageView.GONE);
ImageView inizio = (ImageView)findViewById(R.id.start);
inizio.setVisibility(ImageView.VISIBLE);
inizio.setBackgroundResource(R.drawable.start);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == yay0) {
finish();
}
if (v == yay) {
ImageView inizio = (ImageView)findViewById(R.id.start);
inizio.setVisibility(ImageView.GONE);
WebView work = new WebView(this);
setContentView(work);
work.loadUrl("file:///android_asset/index1.html");
work.setWebViewClient( new work());
work.setBackgroundColor(0);
work.getSettings().setBuiltInZoomControls(true);
work.getSettings().setDefaultZoom(ZoomDensity.FAR);
}
if (v == yay1) {
finish();
}
}
private class work extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("exit.html")) {
// TODO: do what you have to do
finish();
}
view.loadUrl(url);
return true;
}
}
}
Your best bet is to ask somebody to send you the LogCollector output (in my experience, users are very happy to provide you information to debug problems. There are some really cool people out there). That should give you a callstack, and information on what kind of exception you triggered (NullPointerException, etc).
Next up - what are you building your app against? There should be an "Android x.x" entry in your project structure somewhere. If you're building something that is supposed to run on Android 1.5, then make sure you actually build against 1.5. You CAN build against 2.0 if you want, but if you need to use 2.0-specific functions, you'll have to encapsulate them properly. (This has been explained in detail on stackoverflow several times.)
On an unrelated note - I recommend more informative variable names. "yay0" doesn't mean anything to anyone who hasn't been working intimately with the code for a while.