how to intent another class using json array [duplicate] - java

This question already has an answer here:
How to limit the display of questions in the quiz using json array in android?
(1 answer)
Closed 10 years ago.
im developing a quiz wherein i have 10 questions stored. and it is randomly displayed my problem is after that my 10th question i do not know how to intent it to my score class which score must be display of the player recently played the quiz.
this is where the questions is loaded:
public class Question1 extends Activity {
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
static int index = 50;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question10);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1 * 1000);
finish();
loadQuestions();
Intent intent = new Intent(Question1.this,
Question2.class);
Question1.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
//List<JSONObject> question = null;
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
/* question = new ArrayList<JSONObject>();
int n = Math.min(10, quesList.length());
for(int i = 0; i < n; i++) {
JSONObject questions1 = quesList.getJSONObject(i);
question.add(questions1);*/
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList()throws JSONException{
Random rnd = new Random();
for (int i = quesList.length() - 1; i >= 0; i--)
{
int j = rnd.nextInt(i + 1);
// Simple swap
Object object = quesList.get(j);
quesList.put(j, quesList.get(i));
quesList.put(i, object);
}
return quesList;
}
this is where the event of the questions:
public class Question2 extends Activity {
/** Called when the activity is first created. */
TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startquiz);
try {
score = getIntent().getIntExtra("score",0);
items = (TextView)findViewById(R.id.displayitems);
question = (TextView) findViewById(R.id.displayquestion);
answer1 = (RadioButton) findViewById(R.id.option1);
answer2 = (RadioButton) findViewById(R.id.option2);
answer3 = (RadioButton) findViewById(R.id.option3);
answers = (RadioGroup) findViewById(R.id.QueGroup1);
next = (Button) findViewById(R.id.selected);
next.setOnClickListener(nextListener);
selected = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0, review);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex, boolean review) {
try {
JSONObject aQues = Question1.getQuesList().getJSONObject(
qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.BLACK);
answer2.setTextColor(Color.BLACK);
answer3.setTextColor(Color.BLACK);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("", selected[qIndex] + "");
if (selected[qIndex] == 0)
answers.check(R.id.option1);
if (selected[qIndex] == 1)
answers.check(R.id.option2);
if (selected[qIndex] == 2)
answers.check(R.id.option3);
setText();
if (quesIndex == (Question1.getQuesList().length() - 1))
next.setEnabled(false);
if (quesIndex < (Question1.getQuesList().length() - 1))
next.setEnabled(true);
if (review) {
Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
Log.d("", Arrays.toString(selected));
Log.d("", Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
int i = correctAns.length;
if (v == next){
if (correctAns[i] == selected[i])
{
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(), "Your answer is wrong..." + correctAns, Toast.LENGTH_SHORT).show();
}
}
quesIndex++;
try {
if (quesIndex >= Question1.getQuesList().length())
quesIndex = Question1.getQuesList().length() - 1;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showQuestion(quesIndex, review);
}
};
private void setText() throws JSONException {
this.setTitle("Question " + (quesIndex + 1) + " out of "
+ Question1.getQuesList().length());
items.setGravity(250);
}
public void reload() {
setAnswer();
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}

I am unable to understand why you're trying to run a separate thread in Question1.onCreate(). If you want to load the questions in the background, use AsyncTask. Personally, I prefer to use an IntentService to do background tasks where you want to persist the results. An IntentService is particularly useful for decoding JSON.
You don't say what is happening now with your app, but my guess is that the Activity Question2 never starts. I'm not sure, but I suspect it's because you're trying to start the Activity from a background thread. You could use runOnUiThread() to fix this, but it would be much better to load the questions in an IntentService, send a local BroadcastMessage to your Activity when the loading is done, and then display the results. Also, I'd parse the JSON into a database or content provider.

Related

Cannot resolve showQueston argument in getActivity().showQuestion inside my Fragment

I'm using activity class code to create a fragment of each. I was able to successfully change the Mainactivity class to main fragment with replacing this with getActivity() and adding view before each findmyID.
But I'm not able to convert showquestion which highlights in red color although I added getActivity() before it replacing Mainactivity.this which was before.
Here is the screenshot
Here is the whole code
public class question extends Fragment {
EditText question = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioButton answer4 = null;
RadioGroup answers = null;
Button finish = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review =false;
Button prev, next = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question, container, false);
TableLayout quizLayout = (TableLayout) view.findViewById(R.id.quizLayout);
quizLayout.setVisibility(View.INVISIBLE);
try {
question = (EditText) view.findViewById(R.id.question);
answer1 = (RadioButton) view.findViewById(R.id.a0);
answer2 = (RadioButton) view.findViewById(R.id.a1);
answer3 = (RadioButton) view.findViewById(R.id.a2);
answer4 = (RadioButton) view.findViewById(R.id.a3);
answers = (RadioGroup) view.findViewById(R.id.answers);
RadioGroup questionLayout = (RadioGroup)view.findViewById(R.id.answers);
Button finish = (Button)view.findViewById(R.id.finish);
finish.setOnClickListener(finishListener);
prev = (Button)view.findViewById(R.id.Prev);
prev.setOnClickListener(prevListener);
next = (Button)view.findViewById(R.id.Next);
next.setOnClickListener(nextListener);
selected = new int[QuizFunActivity.getQuesList().length()];
Arrays.fill(selected, -1);
correctAns = new int[QuizFunActivity.getQuesList().length()];
Arrays.fill(correctAns, -1);
this.showQuestion(0,review);
quizLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
return view;
}
private void showQuestion(int qIndex,boolean review) {
try {
JSONObject aQues = QuizFunActivity.getQuesList().getJSONObject(qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.WHITE);
answer2.setTextColor(Color.WHITE);
answer3.setTextColor(Color.WHITE);
answer4.setTextColor(Color.WHITE);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(3).getString("Answer");
answer4.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("",selected[qIndex]+"");
if (selected[qIndex] == 0)
answers.check(R.id.a0);
if (selected[qIndex] == 1)
answers.check(R.id.a1);
if (selected[qIndex] == 2)
answers.check(R.id.a2);
if (selected[qIndex] == 3)
answers.check(R.id.a3);
setScoreTitle();
if (quesIndex == (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(false);
if (quesIndex == 0)
prev.setEnabled(false);
if (quesIndex > 0)
prev.setEnabled(true);
if (quesIndex < (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(true);
if (review) {
Log.d("review",selected[qIndex]+""+correctAns[qIndex]);;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
if (selected[qIndex] == 3)
answer4.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 3)
answer4.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private View.OnClickListener finishListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
//Calculate Score
int score = 0;
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
score++;
}
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("Score");
alertDialog.setMessage((score) +" out of " + (QuizFunActivity.getQuesList().length()));
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Retake", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
quesIndex=0;
getActivity().showQuestion(0, review);
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Review", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = true;
quesIndex=0;
getActivity().showQuestion(0, review);
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"Quit", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
getActivity().finish();
}
});
alertDialog.show();
}
};
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
if (answer4.isChecked())
selected[quesIndex] = 3;
Log.d("",Arrays.toString(selected));
Log.d("",Arrays.toString(correctAns));
}
private View.OnClickListener nextListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex++;
if (quesIndex >= QuizFunActivity.getQuesList().length())
quesIndex = QuizFunActivity.getQuesList().length() - 1;
showQuestion(quesIndex,review);
}
};
private View.OnClickListener prevListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex--;
if (quesIndex < 0)
quesIndex = 0;
showQuestion(quesIndex,review);
}
};
private void setScoreTitle() {
getActivity().setTitle("SciQuiz3 " + (quesIndex+1)+ "/" + QuizFunActivity.getQuesList().length());
}
}
Any help is well appreciated. Thanks in advance.
getActivity() returns Activity. So cast it before use.
((YourActivity) getActivity()).showQuestion(...);
Make sure showQuestion() method is public in YourActivity.

fill my button from right to left when I change my language to persian

In my project , I want to play the sound and user must guess the sound.
every thing works well.
I have grid that show some letters and user must selected correct letters to make the right word.
when user selected letters my button fill from left to right
my language is persian and filling my button must be from right to left.
here is my code but don't know where I do this change.
public class TheGame extends Activity {
// Variables
// InterstitialAd interstitial;
private Button[] word_btn;
private String lvl = "0";
private String coins = "0";
private String[] chars = { "الف", "ب", "پ", "ت", "ث", "ج", "چ", "ح", "خ",
"د", "ذ", "ر", "ز", "ژ", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ",
"ف", "ق", "ک", "گ" ,"ل","م","ن","و","ه","ی"};
private String[] word_array;
private String theWord = "999";
private String resultWord = "";
public Button[] randBtn;
SoundPool soundPool;
Context mContext;
String SoundFile,Ribbon;
TextView txt_ribon;
Button btn_first,btn_bomb,btn_skip,btn_back,btn_ask;
boolean loaded = false,isLast=false;
private int soundID,Count=0;
StringBuilder sb;
public TheGame() {
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 9) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} catch (Exception e) {
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
mContext=TheGame.this;
sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(getString(R.string.app_name));
txt_ribon=(TextView)findViewById(R.id.txt_ribon);
btn_first=(Button)findViewById(R.id.button5);
btn_bomb=(Button)findViewById(R.id.button4);
btn_skip=(Button)findViewById(R.id.button3);
btn_back=(Button)findViewById(R.id.button1);
btn_ask=(Button)findViewById(R.id.button6);
Button button = (Button)findViewById(R.id.button8);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.rippleanimset);
animation.setFillAfter(false);
animation.setRepeatCount(0x186a0);
button.startAnimation(animation);
// 12 orange buttons where appear letters of the word, and other letters
randBtn = new Button[] { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
Intent intent = getIntent();
lvl = readData().split("\\|")[0];
coins = readData().split("\\|")[1];
if (Integer.parseInt(coins) < 0) {
coins = "0";
}
parseXML(Integer.parseInt(lvl)-1);
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
if(!isLast)
{
int sound_id = mContext.getResources().getIdentifier(SoundFile, "raw",
mContext.getPackageName());
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
loaded = true;
}
});
soundID = soundPool.load(this, sound_id, 1);
txt_ribon.setText(Ribbon);
word_array = getWord(theWord);
createWord(word_array.length);
randomChars();
TextView lvl_txt = (TextView) findViewById(R.id.textView2);
lvl_txt.setText(" " + lvl + " ");
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.reset_msg_1));
builder.setMessage(getString(R.string.reset_msg_2));
builder.setIcon(R.drawable.ic_launcher);
builder.setPositiveButton(getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
TheGame.this.finish();
}
});
builder.setNegativeButton(getString(R.string.reset_title),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeData(getString(R.string.point_give));
dialog.dismiss();
TheGame.this.finish();
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
((Button)findViewById(R.id.button7)).setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View view)
{
Count+=1;
if (Count %2==1) {
if(loaded)
{
soundPool.play(soundID, 1.0F, 1.0F, 0, 0, 1.0F);
}
else
{
Toast.makeText(getApplicationContext(), "Wait Sound is Loaded", Toast.LENGTH_SHORT).show();
}
}
if (Count % 2==0) {
soundPool.stop(soundID);
soundPool.play(soundID, 1.0F, 1.0F, 0, 0, 1.0F);
}
}
});
btn_first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
btn_first.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_first_letter)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
word_btn[0].setText(word_array[0].toUpperCase());
word_btn[0].setOnClickListener(null);
for (int i = 0; i < 12; i++) {
if (randBtn[i].getText().equals(
word_array[0].toUpperCase())) {
randBtn[i]
.setVisibility(View.INVISIBLE);
i = 12;
}
}
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.first_letter_msg_3)).setIcon(
R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_first_letter))) {
builder.setMessage(getString(R.string.first_letter_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.first_letter_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
btn_bomb.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_bomb)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins)));
remove3Chars();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.bomb_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_bomb))) {
builder.setMessage(getString(R.string.bomb_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.bomb_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
btn_skip.setVisibility(View.INVISIBLE);
coins = "" + (Integer.parseInt(coins) - Integer.parseInt(getString(R.string.how_much_for_skip)));
TextView coins_txt = (TextView) findViewById(R.id.textView1);
coins_txt.setText(coins);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins)));
finish();
startActivity(getIntent());
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
// Check if sufficient coins
AlertDialog.Builder builder = new AlertDialog.Builder(
TheGame.this);
builder.setTitle(getString(R.string.skip_msg_3)).setIcon(R.drawable.help);
if (Integer.parseInt(coins) >= Integer.parseInt(getString(R.string.how_much_for_skip))) {
builder.setMessage(getString(R.string.skip_msg_1));
builder.setNegativeButton(getString(R.string.no), dialogClickListener)
.setPositiveButton(getString(R.string.yes), dialogClickListener)
.show();
} else {
builder.setMessage(getString(R.string.skip_msg_2));
builder.setNegativeButton(getString(R.string.ok), dialogClickListener)
.show();
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onBackPressed();
}
});
btn_ask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path=SaveBackground();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
startActivity(Intent.createChooser(share, "Share Image"));
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onDestroy() {
super.onDestroy();
soundPool.release();
}
// Function that generate black squares, depending on the number of letters
// in the word
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
// Function that generate random letters + word's leter on orange buttons
private void randomChars() {
for (int i = 0; i < 12; i++) {
randBtn[i].setOnClickListener(randCharClick(randBtn[i]));
Random r = new Random();
int i1 = r.nextInt(25 - 0) + 0;
randBtn[i].setText(chars[i1]);
}
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
for (int x = 0; x < word_array.length; x++) {
int value = list.remove(0);
randBtn[value].setText(word_array[x]);
}
}
// Fuction that clear wrong letter from black squares
private OnClickListener charOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < 12; i++) {
if (randBtn[i].getVisibility() == View.INVISIBLE
&& randBtn[i].getText() == button.getText())
randBtn[i].setVisibility(View.VISIBLE);
}
button.setText("");
}
};
}
// Function for orange buttons
private OnClickListener randCharClick(final Button btn) {
return new View.OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.INVISIBLE);
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() == "") {
word_btn[i].setText(btn.getText());
i = word_array.length;
}
}
createResult();
}
};
}
// Function that check if the word is correct and showing correct/wrong
// dialog
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord +=word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
// Function that transform the word to array
private String[] getWord(String str) {
String[] chars = str.split("");
List<String> selected_chars = new ArrayList<String>();
for (int i = 0; i < chars.length; i++) {
selected_chars.add(chars[i]);
}
selected_chars.remove(0);
return selected_chars.toArray(new String[selected_chars.size()]);
}
// //Function that showing dialogs: correct, wrong or zooming image
private void showMyDialog(final int type, String bmp) {
final Dialog dialog = new Dialog(TheGame.this, R.style.dialogStyle);
dialog.setContentView(R.layout.dialog);
dialog.getWindow().getDecorView()
.setBackgroundResource(R.drawable.dialog_bg);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
String points = ""
+ ((new Random().nextInt(10 - 3) + 3) + word_array.length);
SmartImageView image = (SmartImageView) dialog
.findViewById(R.id.imageDialog);
Button dialogBtn = (Button) dialog.findViewById(R.id.dialogBtn);
TextView score = (TextView) dialog.findViewById(R.id.points);
if (type == 1) {
image.setImageResource(R.drawable.corect);
dialogBtn.setText(" Continue "); // Next level button
score.setText("+" + points);
writeData("" + (Integer.parseInt(lvl) + 1) + "|"
+ (Integer.parseInt(coins) + Integer.parseInt(points)));
} else if (type == 2) {
image.setImageResource(R.drawable.gresit);
dialogBtn.setText(" Try Again "); // Try again button, restart
// current level
score.setText("-5");
if (Integer.parseInt(coins) > 0 && Integer.parseInt(coins) <= 5) {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt("0")));
} else {
writeData("" + (Integer.parseInt(lvl)) + "|"
+ (Integer.parseInt(coins) - 5));
}
} else {
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
score.setVisibility(View.GONE);
dialogBtn.setVisibility(View.GONE);
ImageView coinicon = (ImageView) dialog
.findViewById(R.id.dialogIcon);
coinicon.setVisibility(View.GONE);
image.setImageUrl(bmp);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
dialog.show();
dialogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (type > 0) {
finish();
startActivity(getIntent());
}
dialog.dismiss();
}
});
}
// // Button that open "Share on Facebook" dialog
// fb.setOnClickListener(new OnClickListener() {
// #Override
// public void onClick(View v) {
// ByteArrayOutputStream stream = new ByteArrayOutputStream();
// getBitmapFromView().compress(Bitmap.CompressFormat.PNG, 100,
// stream);
// byte[] byteArray = stream.toByteArray();
//// Intent i = new Intent(TheGame.this, LoginFragment.class);
//// i.putExtra("image", byteArray);
//// i.putExtra("lvl", lvl);
//// startActivity(i);
// dialog.dismiss();
// }
// });
// Function that save all user data. Current level, coins
private void writeData(String dataStr) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
openFileOutput("thewords.dat", Context.MODE_PRIVATE));
outputStreamWriter.write(dataStr);
outputStreamWriter.close();
} catch (IOException e) {
}
}
// Function that read user data
private String readData() {
String ret = "";
try {
InputStream inputStream = openFileInput("thewords.dat");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return ret;
}
// Function that hide 3 orange buttons (letters)
public void remove3Chars() {
Button[] removeBtn = { (Button) findViewById(R.id.char1),
(Button) findViewById(R.id.char2),
(Button) findViewById(R.id.char3),
(Button) findViewById(R.id.char4),
(Button) findViewById(R.id.char5),
(Button) findViewById(R.id.char6),
(Button) findViewById(R.id.char7),
(Button) findViewById(R.id.char8),
(Button) findViewById(R.id.char9),
(Button) findViewById(R.id.char10),
(Button) findViewById(R.id.char11),
(Button) findViewById(R.id.char12) };
int x = 0;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < 12; i++) {
list.add(i);
}
Collections.shuffle(list);
while (x != 3) {
int value = list.remove(0);
if (!Arrays.asList(word_array).contains(
removeBtn[value].getText().toString().toUpperCase())) {
removeBtn[value].setVisibility(View.INVISIBLE);
x += 1;
}
}
}
private void parseXML(int i) {
AssetManager assetManager = getBaseContext().getAssets();
try {
InputStream is = assetManager.open("LevelData.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LevelSAXParserHandler myXMLHandler = new LevelSAXParserHandler();
xr.setContentHandler(myXMLHandler);
InputSource inStream = new InputSource(is);
xr.parse(inStream);
ArrayList<Level> cartList = myXMLHandler.getCartList();
if(i>=cartList.size())
{
isLast=true;
}
else
{
Level level=cartList.get(i);
theWord=level.getAnswer();
SoundFile=level.getMusicId();
Ribbon=level.getRibbon();
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String SaveBackground()
{
Bitmap bitmap;
RelativeLayout panelResult = (RelativeLayout) findViewById(R.id.root);
panelResult.invalidate();
panelResult.setDrawingCacheEnabled(true);
panelResult.buildDrawingCache();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int i = displaymetrics.heightPixels;
int j = displaymetrics.widthPixels;
bitmap = Bitmap.createScaledBitmap(Bitmap.createBitmap(panelResult.getDrawingCache()), j, i, true);
panelResult.setDrawingCacheEnabled(false);
String s = null;
File file;
boolean flag;
file = new File(sb.toString());
flag = file.isDirectory();
s = null;
if (flag)
{
}
file.mkdir();
FileOutputStream fileoutputstream1 = null;
s = (new StringBuilder(String.valueOf("guess"))).append("_sound_").append(System.currentTimeMillis()).append(".png").toString();
try {
fileoutputstream1 = new FileOutputStream(new File(file, s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fileoutputstream = fileoutputstream1;
StringBuilder stringbuilder1;
bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, fileoutputstream);
stringbuilder1 = new StringBuilder();
stringbuilder1.append(sb.toString()).append(File.separator).append(s);
try {
fileoutputstream.flush();
fileoutputstream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""+stringbuilder1;
}
here I CREATE place to fill by selected letter by user:
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
for (int i = 0; i < length; i++) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
}
and here i check the letters to fill:
private void createResult() {
resultWord = "";
for (int i = 0; i < word_array.length; i++) {
if (word_btn[i].getText() != "") {
resultWord +=word_btn[i].getText();
}
}
if (resultWord.length() == word_array.length) {
if (resultWord.equalsIgnoreCase(theWord)) {
showMyDialog(1, null);
} else {
showMyDialog(2, null);
}
}
}
now it works but my button fill from left to right
I want to fill right to left
Try adding android:supportsRtl="true" in <application> in your AndroidManifest.xml, and then android:layoutDirection="rtl" in your root layout.
Using a check if the language is right to left from this answer, I would structure your code like this:
private static boolean isRTL() {
final int directionality = Character.getDirectionality(Locale.getDefault().getDisplayName().charAt(0));
return directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT ||
directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
}
private void populateButtons(int i, Button word_btn) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}
private void createWord(int length) {
LinearLayout world_layout = (LinearLayout) findViewById(R.id.world_layout);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, length);
word_btn = new Button[length];
if(isRTL()) {
for(int j = length - 1; j >= 0; j--) {
populateButtons(j, word_btn);
}
} else {}
for (int k = 0; k < length; k++) {
populateButtons(k, word_btn)
}
}
After 2 days, I found the solution. It was easy as a piece of cake.
I dont know why I make it so compilacated.
I just change the my if clause like this:
for (int i = length -1; i >= 0; i--) {
word_btn[i] = new Button(getApplicationContext());
word_btn[i].setText("");
word_btn[i].setId(i);
word_btn[i].setTextColor(Color.parseColor("#ffffff"));
word_btn[i].setTextSize(24);
word_btn[i].setTypeface(Typeface.DEFAULT_BOLD);
word_btn[i].setLayoutParams(param);
word_btn[i].setBackgroundResource(R.drawable.matchbox);
world_layout.addView(word_btn[i]);
word_btn[i].setOnClickListener(charOnClick(word_btn[i]));
}

Sharing Intent Not working Properly

I have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks

Android CountDown Timer won't stop [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Ok so here is my problem. I am working on a trivia game that uses a question counter to display 10 questions and once that happens it calls the finalscore class. I have implemented a timer that resets for every question and if time runs up it proceeds to the next question. However if nothing is clicked on the final question it will keep looping back to the finalscore class even after starting a new game.
public class game extends Activity implements OnClickListener {
// int[] anArray;
int[] anArray2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int numberOfQuestionsDisplayedCounter = 0;
int nextOrFinishValue = 0;
int randomValueZeroToThree = 0;
int randomValue0to29 = 0;
boolean alreadyDisplayQuestion = false;
boolean validQuestionNumber = false;
boolean rightButton1 = false;
boolean rightButton2 = false;
boolean rightButton3 = false;
boolean rightButton4 = false;
String questionFromDatabase;
String answer1FromDatabase;
String answer2FromDatabase;
String answer3FromDatabase;
String answer4FromDatabase;
String displayedQuestionFromDatabase = "question ";
String displayedAnswer1FromDatabase = "answer1a ";
String displayedAnswer2FromDatabase = "answer2a ";
String displayedAnswer3FromDatabase = "answer3a ";
String displayedAnswer4FromDatabase = "answer4a ";
int categoryId = 0;
int questionId = 0;
int currentScore = 0;
private CountDownTimer mCountDown;
public void onCreate(Bundle savedInstanceState) {
int randomInt = 1;
super.onCreate(savedInstanceState);
categoryId = com.triviagame.Trivia_Game.categoryIdInMainMenu;
// System.out.println("categoryID =" + categoryId);
setContentView(R.layout.displayquestion);
// gathers question and answers from database
gatherInfoBeforePopulating(); // includes generating random number
// between getting info from database 1
// to 30
// displays question, answers, score
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
// Sets buttons and listers for the buttons with the 4 possible answers
View answer1button = findViewById(R.id.answer1button);
answer1button.setOnClickListener(this);
View answer2button = findViewById(R.id.answer2button);
answer2button.setOnClickListener(this);
View answer3button = findViewById(R.id.answer3button);
answer3button.setOnClickListener(this);
View answer4button = findViewById(R.id.answer4button);
answer4button.setOnClickListener(this);
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
// Displays question, answers, score
public void populateWithQuestionInfo(String question, String answer1,
String answer2, String answer3, String answer4,
int nextQuestionOrFinish) {
// populate the question label
TextView questionLabel = (TextView) findViewById(R.id.question);
questionLabel.setText(question);
// populate answer1
Button buttonAnswer1 = (Button) findViewById(R.id.answer1button);
buttonAnswer1.setText(answer1);
// populate answer2
Button buttonAnswer2 = (Button) findViewById(R.id.answer2button);
buttonAnswer2.setText(answer2);
// populate answer3
Button buttonAnswer3 = (Button) findViewById(R.id.answer3button);
buttonAnswer3.setText(answer3);
// populate answer4
Button buttonAnswer4 = (Button) findViewById(R.id.answer4button);
buttonAnswer4.setText(answer4);
numberOfQuestionsDisplayedCounter++;
}
// Generates a random number between 0 and 3 to be used to display the
// possible answers randomly
int RandomGeneratorZeroToThree() {
int randomInt = 0;
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx) {
randomInt = randomGenerator.nextInt(4);
}
return randomInt;
}
// Generates a random number between 0 and 29 to be used to select the
// question to be displayed
int RandomGenerator0To29() {
int randomInt2 = 0;
Random randomGenerator2 = new Random();
for (int idx2 = 1; idx2 <= 10; ++idx2) {
randomInt2 = randomGenerator2.nextInt(30);
}
return randomInt2;
}
// returns true if the question has already been displayed
// returns false if the question has not been already displayed
boolean questionsAlreadyDisplayed(int randomValue0to29) {
for (int i = 0; i < 10; i++) {
if (anArray2[i] == randomValue0to29) {
return true; // question already displayed
}
}
anArray2[numberOfQuestionsDisplayedCounter] = randomValue0to29; // questionId
// added
// to
// array
// of
// displayed
// questions
return false; // random number can be used as it has been used already
}
// Connects to the database to gather the question and 4 possible answers.
// Uses DataBaseHelper class
void getInfoFromDatabase(int categoryId, int questionId) {
DataBaseHelper myDbHelper = new DataBaseHelper(
this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
questionFromDatabase = myDbHelper.getQuestion(categoryId,
questionId);
displayedQuestionFromDatabase = questionFromDatabase;
System.out
.println("questionFromDatabase = " + questionFromDatabase);
answer1FromDatabase = myDbHelper.getCorrectAnswer(categoryId,
questionId); // correct answer from database
System.out.println("correct answer from db = "
+ answer1FromDatabase);
answer2FromDatabase = myDbHelper.getWrongAnswer1(categoryId,
questionId);
answer3FromDatabase = myDbHelper.getWrongAnswer2(categoryId,
questionId);
answer4FromDatabase = myDbHelper.getWrongAnswer3(categoryId,
questionId);
myDbHelper.close();
} catch (SQLException sqle) {
System.out.println("Errored out");
try {
throw sqle;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// If the player selects the right answer this method is called to increase
// the score by 10 points
void increaseScore() {
currentScore = currentScore + 10;
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// If the player selects the wrong answer this method is called to decrease
// the score by 10 points
void decreaseScore() {
currentScore = currentScore - 10;
// score can't go below 0
if (currentScore < 0) {
currentScore = 0;
}
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// Displays the current scores on the activity
void displayScore() {
TextView yourScore = (TextView) findViewById(R.id.yourscore);
String currentScoreText;
currentScoreText = Integer.toString(currentScore);
yourScore.setText(currentScoreText);
}
void resetTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
void questionCheck() {
if (nextOrFinishValue == 1) {
Intent e = new Intent(this, finalscore.class);
startActivity(e);
cancelTimer();
}
if (nextOrFinishValue == 0) { // If 10 questions have not been displayed
// yet, display the next question
gatherInfoBeforePopulating();
displayScore();
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
}
}
// gathers question and answers from database
void gatherInfoBeforePopulating() {
categoryId = Trivia_Game.getCategoryIdInMainMenu();
// Loop until a valid questionId that hasn't been used is obtained
while (validQuestionNumber == false) {
randomValue0to29 = RandomGenerator0To29();
System.out.println("random30 in onClick = " + randomValue0to29);
alreadyDisplayQuestion = questionsAlreadyDisplayed(randomValue0to29);
if (alreadyDisplayQuestion == true) {
System.out
.println("question number already displayed looking for a non displayed question");
}
if (alreadyDisplayQuestion == false) {
System.out.println("question not displayed yet");
validQuestionNumber = true;
}
}
validQuestionNumber = false;
alreadyDisplayQuestion = false;
questionId = randomValue0to29; // sets the valid random generated number
// to the questionID
// connect to database to gather the question and answers
getInfoFromDatabase(categoryId, questionId);
// Calls random number from 0 to 3 to determine which button will
// display the correct answer
randomValueZeroToThree = RandomGeneratorZeroToThree();
System.out.println("random4 in onClick = " + randomValueZeroToThree);
// Sets the order according to the button that is to display the correct
// answer
switch (randomValueZeroToThree) {
case 0:
displayedAnswer1FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = true;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
break;
case 1:
displayedAnswer2FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = true;
rightButton3 = false;
rightButton4 = false;
break;
case 2:
displayedAnswer3FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer2FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = true;
rightButton4 = false;
break;
case 3:
displayedAnswer4FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer2FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = true;
break;
default:
displayedAnswer1FromDatabase = answer4FromDatabase; // no correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer1FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
}
// After the 9th question is displayed, the nextOfFinishValue should be
// set to 1 so the button displayes Finish instead of Next
if (numberOfQuestionsDisplayedCounter < 9) {
nextOrFinishValue = 0;
} else {
nextOrFinishValue = 1;
}
}
// Listeners for the 4 buttons with answers and the Next or Finish buttons
public void onClick(View v) {
switch (v.getId()) {
case R.id.answer1button:
if (rightButton1 == true) {
increaseScore();
resetTimer();
// put here to change color of button
} else {
decreaseScore();
resetTimer();
// change button to red
}
questionCheck();
break;
case R.id.answer2button:
if (rightButton2 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer3button:
if (rightButton3 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer4button:
if (rightButton4 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
}
}
#Override
protected void onResume() {
super.onResume();
music.play(this, R.raw.musicbackground); // play background music
}
#Override
protected void onPause() {
super.onPause();
music.stop(this); // stop playing background music
}
}
mCountdown is never null so change your code
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
To
void cancelTimer() {
mCountDown.cancel();
}

how to random questions in the quiz using JSON array in android?

i developing a quiz wherein i have 50 questions stored and i want it to display random in the quiz everytime the user will play..how can i do that? is it possible to randomize question using json?please help me.. i really appreciate ur help..thanks.
public class Question1 extends Activity {
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question10);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1 * 1000);
finish();
loadQuestions();
Intent intent = new Intent(Question1.this,
Question2.class);
Question1.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList(){
return quesList;
}
}
public class Question2 extends Activity {
/** Called when the activity is first created. */
TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startquiz);
try {
items = (TextView)findViewById(R.id.displayitems);
question = (TextView) findViewById(R.id.displayquestion);
answer1 = (RadioButton) findViewById(R.id.option1);
answer2 = (RadioButton) findViewById(R.id.option2);
answer3 = (RadioButton) findViewById(R.id.option3);
answers = (RadioGroup) findViewById(R.id.QueGroup1);
next = (Button) findViewById(R.id.selected);
next.setOnClickListener(nextListener);
selected = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0, review);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex, boolean review) {
try {
JSONObject aQues = Question1.getQuesList().getJSONObject(
qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.BLACK);
answer2.setTextColor(Color.BLACK);
answer3.setTextColor(Color.BLACK);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("", selected[qIndex] + "");
if (selected[qIndex] == 0)
answers.check(R.id.option1);
if (selected[qIndex] == 1)
answers.check(R.id.option2);
if (selected[qIndex] == 2)
answers.check(R.id.option3);
setText();
if (quesIndex == (Question1.getQuesList().length() - 1))
next.setEnabled(false);
if (quesIndex < (Question1.getQuesList().length() - 1))
next.setEnabled(true);
if (review) {
Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
Log.d("", Arrays.toString(selected));
Log.d("", Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) || (correctAns[i] == selected[i]))
{
if (correctAns[i] == selected[i])
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
quesIndex++;
if (quesIndex >= Question1.getQuesList().length())
//quesIndex = Question1.getQuesList().length() - 1;
showQuestion(quesIndex, review);
}
}
};
private void setText() {
this.setTitle("Question " + (quesIndex + 1) + "out of "
+ Question1.getQuesList().length());
items.setGravity(250);
}
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
Use ((int) Math.random() * <size of your array>) to generate a random index for your array of questions

Categories

Resources