I am developing a quiz app and my activity looks like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//click this button to go to the next question
mButton = (Button)findViewById(R.id.nextButton);
//open the DB
openDB();
//Check if the table has data
if(!(myDb.checkDataExists())) {
insertRows();
}
//display a random question
displayQuestion();
}
private void displayQuestion() {
randomNumber = getRandomNumber();
//check if number used or not
if (isNumberNew(String.valueOf(randomNumber))) {
Cursor cursor = myDb.getRow(randomNumber);
displayRecordSet(cursor, optionAnswer);
mOptionButton1.setBackgroundColor(color);
mOptionButton2.setBackgroundColor(color);
mOptionButton3.setBackgroundColor(color);
mOptionButton4.setBackgroundColor(color);
flag = true;
}
}
private void displayRecordSet(Cursor cursor, Map<String, String> optionAnswer) {
int id = 0;
String question = "", option = "", rightAnswer = "";
ArrayList<String> optionList = new ArrayList<String>();
mImageView = (ImageView)findViewById(R.id.storyImageView);
mQuestionTextView = (TextView)findViewById(R.id.questionTextView);
mOptionButton1 = (Button)findViewById(R.id.button);
mOptionButton2 = (Button)findViewById(R.id.button2);
mOptionButton3 = (Button)findViewById(R.id.button3);
mOptionButton4 = (Button)findViewById(R.id.button4);
}
if (cursor.moveToFirst()) {
do {
id = cursor.getInt(0);
question = cursor.getString(1);
option = cursor.getString(3);
rightAnswer = cursor.getString(5);
optionList.add(option);
optionAnswer.put(option,rightAnswer);
} while (cursor.moveToNext());
mQuestionTextView.setText(question);
mOptionButton1.setText(optionList.get(0));
mOptionButton2.setText(optionList.get(1));
mOptionButton3.setText(optionList.get(2));
mOptionButton4.setText(optionList.get(3));
}
cursor.close();
}
The displayQuestion method is supposed to get a random question from the db and then override the values of the option buttons and the question text view. However, when the app starts, the first question is still the one that I hardcoded in my view. In other words, when I call the setContentView(R.layout.activity_quiz); ... I am putting default values in for the option buttons and the question text view. But, I don't want to display those values because they are just place holders. I want to display the question from the database, which I get through dipslayQuestion method.
Does anyone know how to fix this?
There doesn't seem to be enough info to help you. What does displayRecordSet do and how are mOptionButtonX defined? Maybe you intended to change the text of buttons, not the background color?
Also, 2 things. Try to use more descriptive variable names instead of "flag" and such. Secondly, you shouldn't hardcode text into layout files you never want to use. Just set the text to "", you'll overwrite it anyway.
Related
I'm really strugling to figure this out and had not found an answer or a way to do it.
What I'm trying to do is having questions that are saved in a SQLite colum to be displayed in a TextView one after another until they finish.
What I have done so far on the main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseHelper = new DatabaseHelper(this);
btn1star = (Button) findViewById(R.id.btn1star);
btn2star = (Button) findViewById(R.id.btn2star);
btn3star = (Button) findViewById(R.id.btn3star);
mListview = (ListView) findViewById(R.id.qlistview);
qTextView = (TextView) findViewById(R.id.qTextView);
questionsListView();
}
private void questionsListView() {
Cursor data = mDatabaseHelper.getData();
data.moveToFirst();
qTextView.setText(data.getString(1));
}
public void VoteClick(View view){
mDatabaseHelper.getReadableDatabase();
Cursor data = mDatabaseHelper.getData();
if (data.getCount() >=1){
for (int i = 0; i< data.getCount(); i++) {
data.moveToNext();
Log.i("Counted Questions are: ", String.valueOf(data.getCount()));
qTextView.setText(data.getString(1));
}
}
}
private void toastmessage (String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
I'm able to display the first and when i click the button the last question
I'm unable to display the questions between.
Any tip or suggestion?
In your VoteClick method you do your getReadableDatabase, this is too late, move this line into onCreate method. You must open the database before reading from it (in questionsListView).
mDatabaseHelper.getReadableDatabase();//move to onCreate
add this:
startManagingCursor(data);
data.moveToFirst();
BEFORE the line:
if (data.getCount() >=1){
Hello found a solution to my problem
It turns out that i have to make a new int variable
Get its value from the first id
and incrise this by one at the end of each button press until i reach the last cursor place whhere i move the cursor to the first position
public void VoteClick(View view) {
Cursor data = mDatabaseHelper.getData();
data.moveToPosition(q);
data.moveToNext();
qTextView.setText(data.getString(1));
while (data.isLast()) {
data.moveToFirst();
q = data.getPosition();
}
q = q+1;
}
My question is:
How I can check if the checkboxes are checked and how can I get its id or text in a onclick event?
I have done it whit RadioGroup, but RadioGroup only let me check 1 RadioButton, and in this case I need to check more than one, but if Im wrong and there is a way to do it with RadioGroup it should work for me.
Thanks for the help
Here is the code where I create the checkboxes programmatically:
protected void onCreate(Bundle savedInstanceState) {
LinearLayout lg = (LinearLayout) findViewById(R.id.lg);
Button botonenv = (Button) findViewById(R.id.botonenv);
try{
myJson = new JSONObject(data);
JSONArray Solutions = myJson.getJSONArray("solutions");
for (int i = 0; i < Solutions.length(); i++) {
JSONObject JSonSol = Solutions.getJSONObject(i);
final String idSt = JSonSol.getString("id");
final String name = JSonSol.getString("name");
String resp = name.toUpperCase();
CheckBox cb1 = new CheckBox(this);
cb1.setText(resp);
LinearLayout.LayoutParams llg = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llg.setMargins(0, 30, 0, 0);
cb1.setTextSize(15);
cb1.setTextColor(Color.parseColor("#FF000000"));
lg.addView(cb1);
int id =Integer.parseInt(idSt);
cb1.setId(id);
}
}catch(JSONException e){
e.printStackTrace();
}
botonenv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//HERE I MUST NOW WHAT CHECKBOXES ARE CHECKED AND THEIR IDS
..............
}
});
}
Add their references to list , then you can reuse those reference again in any where outside after creation .
like
List<CheckBox> checkBoxes = new ArrayList<>();
add checkbox to your list wherever your create a new one checkBoxes.add(cb1);
inside your onClick you can check all of them .
The title is a little confusing so let me explain further. An application I am trying to make has multiple buttons opening a new activity that look the same, but the text is different depending on the button clicked (Like a dictionary). So instead of recreating the activity 50+ times, I made a new method for onClick() in the first activity with a new Intent, and added a getIntent() to the second activity.
//first activity method
public final static String TRANSFER_SYMBOL = "com.engineering.dictionary.MESSAGE";
public void openView(View view)
{
Intent open = new Intent(this,displayCharHB.class);
Button setBtn = (Button) findViewById(view.getId());
String grabText = setBtn.getText().toString();
String thisChar = "sym_hira_" + grabText;
open.putExtra(TRANSFER_SYMBOL,thisChar);
startActivity(open);
}
//second Activity method
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent grabChar = getIntent();
String thisChar = grabChar.getStringExtra(hira_basic.TRANSFER_SYMBOL);
//String strValue = "R.string." + thisChar;
TextView displaySym = (TextView) findViewById(R.id.charDisplay);
displaySym.setText(thisChar);
}
sym_hira_ + whatever is stored in grabText is the name of a String in strings.xml (For example, grabText = "ro", sym_hira_ro is a String name). Is it possible to get it to reference that string name with setText() and not actually set the text to "sym_hira_..."?
Is it possible to get it to reference that string name with setText()
Use getIdentifier to get value from strings.xml using name:
int resId = getResources().getIdentifier(thisChar, "string",getPackageName());
displaySym.setText(getResources().getString(resId));
you can using BeanShell execute the "R.string.xxxx" command to get the string resource id.
this is my code example;
String str = "";
Interpreter i = new Interpreter();
i.set("context", MainActivity.this);
Object res = i.eval("com.example.testucmbilebase.R.string.hello_world");
if(res != null) {
Integer resI = (Integer)res;
str = MainActivity.this.getResources().getString(resI);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I posted this question before, however i didnt explain myself good. I will have the other question removed. Here is my current situation:
I have a regular xml page with a textView which when clicked opens a popup dialog. This dialog contains 2 editText. Currently my code (OnClick – Done button) gets the value of both edit texts and puts them into the single TextView. However when i open the pop-up again, instead of the two strings being listed in its own editText (Where each string was originally inputted) the combined string which was stored in the text view appears in one edit text. The issue is that although i’m getting the strings from 2 different editText’s and storing them into one textView. I cannot get each string back individually. I understand that i may have to store the string from each editText into variables and then i can use the variables to show the strings combined in the textView (and the editText – when i open the popup dialog again) How would i go about this? Thank for your help
The code:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView showPopUpButton;
EditText getInput;
EditText getInput2;
String myvalue = "";
String myvalue2 = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showPopUpButton = (TextView) findViewById(R.id.buttonShowPopUp);
showPopUpButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showPopUp3(); }
});
}
private void showPopUp3() {
AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
helpBuilder.setTitle("Enter PU Builder");
LayoutInflater inflater = getLayoutInflater();
View checkboxLayout = inflater.inflate(R.layout.popuplayout, null);
helpBuilder.setView(checkboxLayout);
getInput = (EditText) checkboxLayout.findViewById(R.id.editText1);
getInput2 = (EditText) checkboxLayout.findViewById(R.id.editText2);
getInput.setText(myvalue);
getInput2.setText(myvalue2);
helpBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
myvalue = getInput.getText().toString();
showPopUpButton.setText(myvalue + ", " + myvalue2);
}
});
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
}
First of all you need string to save your EditText value in it declare it like this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView showPopUpButton; //NEW
EditText getInput; //NEW
EditText getInput2; //NEW
// declare string to save the dialog edittext
String myValue = "" ;
then you need to show the last value of dialog in the EditText so try this :
private void showPopUp3() {
AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
helpBuilder.setTitle("Enter PU Builder");
LayoutInflater inflater = getLayoutInflater();
View checkboxLayout = inflater.inflate(R.layout.popuplayout, null);
getInput = (EditText) checkboxLayout.findViewById(R.id.editText1); //MISTAKE
getInput2 = (EditText) checkboxLayout.findViewById(R.id.editText2); //MISTAKE
getInput.setText(showPopUpButton.getText()); //New to keep the text in the editText when done is pressed
getInput2.setText(getInput2.getText()); //New test
// here set the my value to edit text , note firs time will be empty
getInput.setText(myValue)
and last thing when you click in done button in dialog you need to save the EditText value like that :
#Override
public void onClick(DialogInterface dialog, int which){
//showPopUpButton.setText(getInput.getText() + ", " + getInput2.getText());//NEW
//showPopUpButton.setText(value) ;
// save the edit text value into myvalue string
myvalue = getInput.getText().toString();
}
});
feed me back
This is fairly straightforward.
Create the variables to placehold your strings.
String inputText;
Where applicable, get and set.
inputText = editText.getText().toString();
textView.setText(inputText);
Did I understand this correctly? Is this what you are trying to accomplish?
I have a database with team names and team numbers(both stored as strings - the numbers sometimes have letters in them)
I want it so when you click the "Open" button, it'll bring up a popup that will have all of the teams' names and numbers, and if you click one, it will close the popup and set both editText's to the name & number.
Dialog d = new Dialog(this);
ScoutingFormData info = new ScoutingFormData(this);
info.open();
ScrollView scr = info.getData();
info.close();
d.addContentView(scr, null);
d.show();
That's from the main program, when you click "Open", this happens. ScoutingFormData is my SQLite database, and here's getData:
public ScrollView getData() {
String[] columns=new String[]{KEY_ROWID,KEY_NAME,KEY_NUM};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
ScrollView result=new ScrollView(null);
int iID = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iNum = c.getColumnIndex(KEY_NUM);
LinearLayout vertlay = new LinearLayout(null);
vertlay.setOrientation(LinearLayout.VERTICAL);
for (c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
TextView tv=new TextView(null);
tv.setText(c.getString(iNum)+" "+c.getString(iName));
vertlay.addView(tv);
}
result.addView(vertlay);
return result;
}
So this builds the dialog, but how do I make it so the main program(the top code) will know when one of these TextViews have been clicked?
Side question: when making a View(like LinearLayout vertlay = new LinearLayout(null);), what context am I supposed to be using? I don't fully understand what a 'context' is, so I'm really at a loss of what to replace "null" with.
How do I make it so the main program(the top code) will know when one of these TextViews have been clicked?
Simply make tv clickable and add an OnClickListener.
Side question: what context am I supposed to be using?
You hinted that getData() is in your database adapter class ScoutingFormData, save a reference to the Context passed to the Constructor and reuse it later:
private Context mContext;
public ScoutingFormData(Context context) {
mContext = context;
}
All together:
TextView tv=new TextView(mContext);
tv.setClickable(true);
tv.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// Do something
}
});