Further guidance with a Spinner - java

after testing out examples given here and here, I thought I would be able to add a score-point if the user selected the correct drop-down item. (I'm making a simple quiz app that toasts the final score).
Obviously this is too advanced for me, but I really don't want to give up and wondered if anyone might have any idea as to what I'm doing wrong please?
Here is how I have it set out in the MainActivity.java, with my failed attempts of implementing a way of checking the selected item stripped out:
First I set out the questions:
package com.example.android.arabic;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.android.arabic.Nature.Nature;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
int arabicScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add emoji Q1
TextView q1 = findViewById(R.id.Q1_question);
q1.setText(Nature.HONEY_BEE);
// add emoji A2_option1
TextView qa2Option1 = findViewById(R.id.A2_option1);
qa2Option1.setText(Nature.GOAT);
// add emoji A2_option2
TextView qa2Option2 = findViewById(R.id.A2_option2);
qa2Option2.setText(Nature.BIRD);
// add emoji A2_option3
TextView qa2Option3 = findViewById(R.id.A2_option3);
qa2Option3.setText(Nature.HORSE);
//Q3 audio
Button q3Sound = this.findViewById(R.id.Q3_sound);
final MediaPlayer q3 = MediaPlayer.create(this, R.raw.camel);
q3Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q3.start();
}
});
// add emoji Q4_question
TextView q4 = findViewById(R.id.Q4_question);
q4.setText(Nature.ANT);
// Start of spinner Q4
Spinner a4 = findViewById(R.id.A4);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence>adapter = ArrayAdapter.createFromResource(this,
R.array.a4_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
a4.setAdapter(adapter);
a4.setOnItemSelectedListener(this);
//Q5 audio
Button q5Sound = this.findViewById(R.id.Q5_sound);
final MediaPlayer q5 = MediaPlayer.create(this, R.raw.cow_bird);
q5Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q5.start();
}
});
//A5
// add emoji A5_option1
TextView qa5Option1 = findViewById(R.id.A5_option1);
qa5Option1.setText(Nature.COW);
// add emoji A5_option2
TextView qa5Option2 = findViewById(R.id.A5_option2);
qa5Option2.setText(Nature.PIG);
// add emoji A5_option3
TextView qa5Option3 = findViewById(R.id.A5_option3);
qa5Option3.setText(Nature.SNAKE);
// add emoji A5_option4
TextView qa5Option4 = findViewById(R.id.A5_option4);
qa5Option4.setText(Nature.BIRD);
}
//Display Result
public void results(View view){
// Check point for Q1
EditText a1EditText = findViewById(R.id.A1);
String a1Entry = a1EditText.getText().toString();
if (a1Entry.contains("نحلة")) {
arabicScore = arabicScore + 1;
}
// Check point for Q2
RadioButton a2Radio = findViewById(R.id.A2_option2);
boolean isa2RadioChecked = a2Radio.isChecked();
if (isa2RadioChecked){
arabicScore = arabicScore + 1;
}
// Check point for Q3
EditText a3EditText = findViewById(R.id.A3);
String a3Entry = a3EditText.getText().toString();
if (a3Entry.contains("جمل")) {
arabicScore = arabicScore + 1;
}
// Check point for Q4
Toast resultToast = Toast.makeText(this, "You got " + arabicScore + " of 7 questions right.", Toast.LENGTH_LONG);
resultToast.show();
}
Preview of layout
}
Thank you very much for your advice in advance! I've been stuck on this for months! :'D

Related

Trying to add to an arraylist on a different activity each time a button is pressed

So just to practice I've created a Pythagorean theorem calculator app. I want each answer that I obtain to be stored in another activity(a "history" page). I'm trying to use intents to send/receive the arraylist and items. I get the most recent one, but it is overwritten after each press of the button.
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
//ToDo history button is broken. doesn't display listview when pressed.
public void toHistory(View view) {
// Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
//
// startActivity(intent);
}
public void findHypno(View view) {
Log.i("Info", "button pressed");
EditText editTextNumberA = (EditText) findViewById(R.id.editTextNumberA);
EditText editTextNumberB = (EditText) findViewById(R.id.editTextNumberB);
TextView textViewAnswer = (TextView) findViewById(R.id.textViewAnswer);
String message;
String cSquared;
if (editTextNumberA.getText().toString().isEmpty() || editTextNumberB.getText().toString().isEmpty()) {
message = "Please enter a number for each dimension";
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
} else {
Number numberA = new Number();
Number numberB = new Number();
Number numberC = new Number();
numberA.number = Double.parseDouble(editTextNumberA.getText().toString());
numberB.number = Double.parseDouble(editTextNumberB.getText().toString());
numberA.squareNumber();
numberB.squareNumber();
numberC.number = numberA.number + numberB.number;
numberC.squareRoot();
Log.i("test numberA", String.valueOf(numberA.number));
Log.i("test numberB", String.valueOf(numberB.number));
Log.i("test numberC", String.valueOf(numberC.number));
cSquared = Double.toString(numberC.number);
textViewAnswer.setText(cSquared);
ArrayList<String> historyList = new ArrayList<String>();
historyList.add("test");
Intent intent = new Intent(getApplicationContext(), HistoryActivity.class);
intent.putExtra("answer", cSquared);
intent.putStringArrayListExtra("arrayList", historyList);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package com.example.hypnotenusecalculatorrebuild;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleBiFunction;
public class HistoryActivity extends AppCompatActivity {
public void back(View view) {
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Intent getList = getIntent();
ArrayList<String> historyList = getList.getStringArrayListExtra("arrayList");
historyList.add(getList.getStringExtra("answer"));
ListView listViewHistory = (ListView) findViewById(R.id.listViewHistory);
ArrayAdapter historyListArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, historyList);
listViewHistory.setAdapter(historyListArrayAdapter);
// ToDo - intent isn't working as attended, only saves one item and gets overwritten each time
//Intent historyIntent = getIntent();
// get extra needs a name from put extra
// String testGetIntent = historyIntent.getStringExtra("answer");
// Log.i("testIntentString", testGetIntent);
// historyList.add(historyIntent.getStringExtra("answer"));
}
}
here is a different approach. make a public interface in a separate file named "extensions" or whatever and initialize your arraylist there like so:
public interface ext {
ArrayList<String> myArray = new ArrayList<String>();
}
this interface is created when the app runs and lives for as long as the app lives meaning you can always access and manipulate it anywhere in your app without worrying whether the activity is being killed or not. so you can add or remove elements to or from it wherever you want.
Access the array this way:
ext.myArray.add("new item")

how to use an if else statement with a spinner?

this is my code I don't know how to use if else statement with two spinner
//(spinner1.equals"THB" && spinner2.equals"USD") <--something like that
https://drive.google.com/file/d/1e_TbY6e-KAE7Iq6GLq2CFy9WA1VBy1qx/view?fbclid=IwAR1s7C9SVm2S202uAmURjwTilHu2ppwkHclvN7gDT3cEFFwZkqyktZv6MRE
If you are talking about the values of the spinner that the user has chosen:
Spinner spinner1 = findViewById(R.id.your_spinner1);
Spinner spinner2 = findViewById(R.id.your_spinner2);
if(spinner1.getSelectedItem().toString().equals("THB") && spinner2.getSelectedItem().toString().equals("USD"){
//do stuff here
}
Like the user f1sh in the comment said, post your code in the question.
Extend an interface AdapterView.OnItemSelectedListener
package com.example.acer.spinner;
import android.accessibilityservice.GestureDescription;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.lang.ref.SoftReference;
public class MainActivity extends AppCompatActivity {
Spinner spn,spn1;
EditText inmoney;
TextView answer;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inmoney=findViewById(R.id.text);
answer=findViewById(R.id.textView);
btn=findViewById(R.id.button);
// first spinner
spn=findViewById(R.id.spinner);
spn1=findViewById(R.id.spinner2);
String [] legion ={"THB","USD","EUR","JPY","SGD","MYN","CNY"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,legion);
spn.setAdapter(adapter);
spn1.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exrate();
}
});
}
public void exrate(){
double num=Double.parseDouble(inmoney.getText().toString());
if (spn1.getSelectedItem().toString().equals("THB") && spn.getSelectedItem().toString().equals("USD")){
double ans=num*5;
answer.setText(String.valueOf(ans));
}
else{
//do other currency conversions
}
}
}
You can also use else if(condition) instead of just else, to do other comparison and conversions
It is called as Ladder-if in Java jargon

unable to search database from button.setOnClick .getText as String becomes null

I am making android app that takes user input from EditText on press of button from button.setOnClick() and use the string.getText() to search the database. But the string becomes null and no way i can send it
DbBackend.class where the search function is.
I checked and database works fine on static query which you can set to = "xyz" but no way i am able to use the user input to query the database.
Here is my code: MainActivity.java
package com.vadhod.dictcopy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import static android.app.PendingIntent.getActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText searchBar;
Button searchButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DbBackend dbBackend = new DbBackend(MainActivity.this);
searchBar = (EditText) findViewById(R.id.searchBar);
searchButton = (Button) findViewById(R.id.searchButton);
textView = (TextView)findViewById(R.id.textView);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String input = searchBar.getText().toString();
ArrayList<String> terms = dbBackend.getList(input);
StringBuilder builder = new StringBuilder();
for (String details : terms) {
builder.append(details + "\n");
}
textView.setText(builder.toString());
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
DbBackend.java
package com.vadhod.dictcopy;
import ...
public class DbBackend extends DatabaseObject {
public DbBackend(Context context){
super(context);
}
public ArrayList<String> getList(String search){
ArrayList<String> kWords = new ArrayList<String>();
String searchQuery = "SELECT kName FROM dictionary WHERE eName LIKE '%" + search + "%'";
try {
Cursor kCursor = this.getDbConnection().rawQuery(searchQuery, null);
if (kCursor != null){
kCursor.moveToFirst();
for (int i = 0; i < kCursor.getCount(); i++ ){
String sword = kCursor.getString(kCursor.getColumnIndexOrThrow("kName"));
kWords.add(sword);
kCursor.moveToNext();
}
kCursor.close();
return kWords;
}
return kWords;
}catch (Exception e){
e.printStackTrace();
}
return kWords;
}
}
Any help please on how to use the string when user press the search button and search that through the database and return the query?
Updated the moved code
Assuming that inside the searchButton.setOnClickListener(new View.OnClickListener() {...}); the search is working, and outside - not. The problem is your
//Option 1 not working
ArrayList<String> terms2 = dbBackend2.getList(input);
is called during the Activity setup before any view is shown to the user. So, the input is not filled at that time. You have to move this code into an onclick listener, like you did in the code above these lines.
Or provide some other source for the input.
Upd:
For the NullPointer: in your layout file activity_main you need to have a TextView with id textView. Because you do the following:
// find the textview in the layout
textView = (TextView)findViewById(R.id.textView);
// do the search, get results
...
// set textview's text, at this moment textView must not be null
textView.setText(kbuilder.toString());

Android Programming with Java, how to use R.id

studio to create an android app that adds a string from an editText with an id of input and displays it into textView with an id of output. But
EditText input = EditText(findViewById(R.id.input));
and
TextView output = TextView(findViewById(R.id.output));
doesnt work as it says Method call expected. Any kind of help would be great, thankyou.
package com.example.toshb.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
private Model model;
public MainActivity() {model = new Model();}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void processInput(View view)
{
EditText input = EditText(findViewById(R.id.input));
TextView output = TextView(findViewById(R.id.output));
model.addString(editText.getText().toString());
output.setText(model.getList());
input.setText("");
}
}
You need to add proper declaration of EditText And TextView . Before write a code please have a look here:
https://developer.android.com/index.html
EditText input = (EditText)findViewById(R.id.input);
TextView output =(TextView)findViewById(R.id.output);
model.addString(input.getText().toString());

Syntax error setOnClickListener?

ok if you didnt see my previous question I asked how 2 Command button to import text to textview from edittext using Scanner? Here is what I have done:
I keep geting this error
"Syntax error on token
"setOnClickListener",
VariableDeclaratorId expected after
this token"
what am I missing or doing wrong?
package test.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import java.util.Scanner;
import android.R.layout;
public class test extends Activity {
Scanner what = (new Scanner(System.in));
private int addbtn;
Button btn = (Button) findViewById(addbtn);
btn.setOnClickListener = (new OnClickListener() {
public void onClick(View v) {
int txtbox;
EditText txt = (EditText) findViewById(txtbox);
int tv1;
TextView txt1 = (TextView) findViewById(tv1);
txt.setText( txt.getText().toString() );}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
You're missing a closing brace } on the new OnClickListener block.
Also you shouldn't be attempting Button btn = (Button) findViewById(addbtn); before the onCreate(...) method has called setContentView(...).
On top of that, addbtn isn't a valid resource id.
Use findViewById() method before setContentView(...).
On top of which your closing brackets look messed up. What's matching the ( before the new onClickListener?

Categories