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.
Related
actually I'm using this part of code but nothing shown in screen
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, elativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
And this is the activity codes
public class LaunchActivity extends Activity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationCenter.NotificationCenterDelegate, DialogsActivity.DialogsActivityDelegate {
private boolean finished;
private String videoPath;
private String sendingText;
private ArrayList<Uri> photoPathsArray;
private ArrayList<String> documentsPathsArray;
private ArrayList<Uri> documentsUrisArray;
private String documentsMimeType;
private ArrayList<String> documentsOriginalPathsArray;
private ArrayList<TLRPC.User> contactsToSend;
private int currentConnectionState;
private static ArrayList<BaseFragment> mainFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> layerFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> rightFragmentsStack = new ArrayList<>();
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;
private ActionBarLayout actionBarLayout;
private ActionBarLayout layersActionBarLayout;
private ActionBarLayout rightActionBarLayout;
private FrameLayout shadowTablet;
private FrameLayout shadowTabletSide;
private View backgroundTablet;
protected DrawerLayoutContainer drawerLayoutContainer;
private DrawerLayoutAdapter drawerLayoutAdapter;
private PasscodeView passcodeView;
private AlertDialog visibleDialog;
private RecyclerListView sideMenu;
private AlertDialog localeDialog;
private boolean loadingLocaleDialog;
private HashMap<String, String> systemLocaleStrings;
private HashMap<String, String> englishLocaleStrings;
private Intent passcodeSaveIntent;
private boolean passcodeSaveIntentIsNew;
private boolean passcodeSaveIntentIsRestore;
private boolean tabletFullSize;
private Runnable lockRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
ApplicationLoader.postInitApplication();
NativeCrashManager.handleDumpFiles(this);
AndroidUtilities.checkDisplaySize(this, getResources().getConfiguration());
Log.i(this.getClass().getName(), "onCreate: ");
if (!UserConfig.isClientActivated()) {
Intent intent = getIntent();
if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
super.onCreate(savedInstanceState);
finish();
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
long crashed_time = preferences.getLong("intro_crashed_time", 0);
boolean fromIntro = intent.getBooleanExtra("fromIntro", false);
if (fromIntro) {
preferences.edit().putLong("intro_crashed_time", 0).commit();
}
if (Math.abs(crashed_time - System.currentTimeMillis()) >= 60 * 2 * 1000 && intent != null && !fromIntro) {
preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", MODE_PRIVATE);
Map<String, ?> state = preferences.getAll();
if (state.isEmpty()) {
Intent intent2 = new Intent(this, IntroActivity.class);
intent2.setData(intent.getData());
startActivity(intent2);
super.onCreate(savedInstanceState);
finish();
return;
}
}
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(R.style.Theme_TMessages);
getWindow().setBackgroundDrawableResource(R.drawable.transparent);
if (UserConfig.passcodeHash.length() > 0 && !UserConfig.allowScreenCapture) {
try {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
FileLog.e(e);
}
}
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 24) {
AndroidUtilities.isInMultiwindow = isInMultiWindowMode();
}
Theme.createChatResources(this, false);
if (UserConfig.passcodeHash.length() != 0 && UserConfig.appLocked) {
UserConfig.lastPauseTime = ConnectionsManager.getInstance().getCurrentTime();
}
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
actionBarLayout = new ActionBarLayout(this);
drawerLayoutContainer = new DrawerLayoutContainer(this);
setContentView(drawerLayoutContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
if (AndroidUtilities.isTablet()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
RelativeLayout launchLayout = new RelativeLayout(this) {
private boolean inLayout;
#Override
public void requestLayout() {
if (inLayout) {
return;
}
super.requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
inLayout = true;
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
tabletFullSize = false;
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTabletSide.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
rightActionBarLayout.measure(MeasureSpec.makeMeasureSpec(width - leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
} else {
tabletFullSize = true;
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
backgroundTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
layersActionBarLayout.measure(MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(530), width), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(528), height), MeasureSpec.EXACTLY));
inLayout = false;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
shadowTabletSide.layout(leftWidth, 0, leftWidth + shadowTabletSide.getMeasuredWidth(), shadowTabletSide.getMeasuredHeight());
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
rightActionBarLayout.layout(leftWidth, 0, leftWidth + rightActionBarLayout.getMeasuredWidth(), rightActionBarLayout.getMeasuredHeight());
} else {
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
}
int x = (width - layersActionBarLayout.getMeasuredWidth()) / 2;
int y = (height - layersActionBarLayout.getMeasuredHeight()) / 2;
layersActionBarLayout.layout(x, y, x + layersActionBarLayout.getMeasuredWidth(), y + layersActionBarLayout.getMeasuredHeight());
backgroundTablet.layout(0, 0, backgroundTablet.getMeasuredWidth(), backgroundTablet.getMeasuredHeight());
shadowTablet.layout(0, 0, shadowTablet.getMeasuredWidth(), shadowTablet.getMeasuredHeight());
}
};
drawerLayoutContainer.addView(launchLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
backgroundTablet = new View(this);
//BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.catstile);
//drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
backgroundTablet.setBackgroundResource(R.drawable.catstile);
launchLayout.addView(backgroundTablet, LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
launchLayout.addView(actionBarLayout);
rightActionBarLayout = new ActionBarLayout(this);
rightActionBarLayout.init(rightFragmentsStack);
rightActionBarLayout.setDelegate(this);
launchLayout.addView(rightActionBarLayout);
shadowTabletSide = new FrameLayout(this);
shadowTabletSide.setBackgroundColor(0x40295274);
launchLayout.addView(shadowTabletSide);
shadowTablet = new FrameLayout(this);
shadowTablet.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
shadowTablet.setBackgroundColor(0x7f000000);
launchLayout.addView(shadowTablet);
shadowTablet.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!actionBarLayout.fragmentsStack.isEmpty() && event.getAction() == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
int location[] = new int[2];
layersActionBarLayout.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
if (layersActionBarLayout.checkTransitionAnimation() || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY && y < viewY + layersActionBarLayout.getHeight()) {
return false;
} else {
if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
a--;
}
layersActionBarLayout.closeLastFragment(true);
}
return true;
}
}
return false;
}
});
shadowTablet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layersActionBarLayout = new ActionBarLayout(this);
layersActionBarLayout.setRemoveActionBarExtraHeight(true);
layersActionBarLayout.setBackgroundView(shadowTablet);
layersActionBarLayout.setUseAlphaAnimations(true);
layersActionBarLayout.setBackgroundResource(R.drawable.boxshadow);
layersActionBarLayout.init(layerFragmentsStack);
layersActionBarLayout.setDelegate(this);
layersActionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
layersActionBarLayout.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
launchLayout.addView(layersActionBarLayout);
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
} else {
drawerLayoutContainer.addView(actionBarLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
sideMenu = new RecyclerListView(this);
sideMenu.setBackgroundColor(Theme.getColor(Theme.key_chats_menuBackground));
sideMenu.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
sideMenu.setAdapter(drawerLayoutAdapter = new DrawerLayoutAdapter(this));
drawerLayoutContainer.setDrawerLayout(sideMenu);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) sideMenu.getLayoutParams();
Point screenSize = AndroidUtilities.getRealScreenSize();
layoutParams.width = AndroidUtilities.isTablet() ? AndroidUtilities.dp(320) : Math.min(AndroidUtilities.dp(320), Math.min(screenSize.x, screenSize.y) - AndroidUtilities.dp(56));
layoutParams.height = LayoutHelper.MATCH_PARENT;
sideMenu.setLayoutParams(layoutParams);
sideMenu.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
#Override
public void onItemClick(final View view, int position) {
int id = drawerLayoutAdapter.getId(position);
if (position == 0) {
Bundle args = new Bundle();
args.putInt("user_id", UserConfig.getClientUserId());
presentFragment(new ChatActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 2) {
if (!MessagesController.isFeatureEnabled("chat_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
presentFragment(new GroupCreateActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 3) {
Bundle args = new Bundle();
args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true);
args.putBoolean("createSecretChat", true);
args.putBoolean("allowBots", false);
presentFragment(new ContactsActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 4) {
if (!MessagesController.isFeatureEnabled("broadcast_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (!BuildVars.DEBUG_VERSION && preferences.getBoolean("channel_intro", false)) {
Bundle args = new Bundle();
args.putInt("step", 0);
presentFragment(new ChannelCreateActivity(args));
} else {
presentFragment(new ChannelIntroActivity());
preferences.edit().putBoolean("channel_intro", true).commit();
}
drawerLayoutContainer.closeDrawer(false);
} else if (id == 6) {
presentFragment(new ContactsActivity(null));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 7) {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
/*AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTopImage(R.drawable.permissions_contacts, 0xff35a8e0);
builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("ContactsPermissionAlert", R.string.ContactsPermissionAlert)));
builder.setPositiveButton(LocaleController.getString("ContactsPermissionAlertContinue", R.string.ContactsPermissionAlertContinue), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(LocaleController.getString("ContactsPermissionAlertNotNow", R.string.ContactsPermissionAlertNotNow), null);
showAlertDialog(builder);*/
showLanguageAlert(true);
} else {
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText());
startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500);
} catch (Exception e) {
FileLog.e(e);
}
drawerLayoutContainer.closeDrawer(false);
}
} else if (id == 8) {
presentFragment(new SettingsActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 9) {
Browser.openUrl(LaunchActivity.this, LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 10) {
presentFragment(new CallLogActivity());
drawerLayoutContainer.closeDrawer(false);
}
}
});
drawerLayoutContainer.setParentActionBarLayout(actionBarLayout);
actionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
actionBarLayout.init(mainFragmentsStack);
actionBarLayout.setDelegate(this);
Theme.loadWallpaper();
passcodeView = new PasscodeView(this);
drawerLayoutContainer.addView(passcodeView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this);
currentConnectionState = ConnectionsManager.getInstance().getConnectionState();
NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.needShowAlert);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.wasUnableToFindCurrentLocation);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetNewWallpapper);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetPasscode);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadInterface);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.suggestedLangpack);
if (actionBarLayout.fragmentsStack.isEmpty()) {
if (!UserConfig.isClientActivated()) {
actionBarLayout.addFragmentToStack(new LoginActivity());
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
DialogsActivity dialogsActivity = new DialogsActivity(null);
dialogsActivity.setSideMenu(sideMenu);
actionBarLayout.addFragmentToStack(dialogsActivity);
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
try {
if (savedInstanceState != null) {
String fragmentName = savedInstanceState.getString("fragment");
if (fragmentName != null) {
Bundle args = savedInstanceState.getBundle("args");
switch (fragmentName) {
case "chat":
if (args != null) {
ChatActivity chat = new ChatActivity(args);
if (actionBarLayout.addFragmentToStack(chat)) {
chat.restoreSelfArgs(savedInstanceState);
}
}
break;
case "settings": {
SettingsActivity settings = new SettingsActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
case "group":
if (args != null) {
GroupCreateFinalActivity group = new GroupCreateFinalActivity(args);
if (actionBarLayout.addFragmentToStack(group)) {
group.restoreSelfArgs(savedInstanceState);
}
}
break;
case "channel":
if (args != null) {
ChannelCreateActivity channel = new ChannelCreateActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "edit":
if (args != null) {
ChannelEditActivity channel = new ChannelEditActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "chat_profile":
if (args != null) {
ProfileActivity profile = new ProfileActivity(args);
if (actionBarLayout.addFragmentToStack(profile)) {
profile.restoreSelfArgs(savedInstanceState);
}
}
break;
case "wallpapers": {
WallpapersActivity settings = new WallpapersActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
if (fragment instanceof DialogsActivity) {
((DialogsActivity) fragment).setSideMenu(sideMenu);
}
boolean allowOpen = true;
if (AndroidUtilities.isTablet()) {
allowOpen = actionBarLayout.fragmentsStack.size() <= 1 && layersActionBarLayout.fragmentsStack.isEmpty();
if (layersActionBarLayout.fragmentsStack.size() == 1 && layersActionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
}
if (actionBarLayout.fragmentsStack.size() == 1 && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false);
}
checkLayout();
handleIntent(getIntent(), false, savedInstanceState != null, false);
try {
String os1 = Build.DISPLAY;
String os2 = Build.USER;
if (os1 != null) {
os1 = os1.toLowerCase();
} else {
os1 = "";
}
if (os2 != null) {
os2 = os1.toLowerCase();
} else {
os2 = "";
}
if (os1.contains("flyme") || os2.contains("flyme")) {
AndroidUtilities.incorrectDisplaySizeFix = true;
final View view = getWindow().getDecorView().getRootView();
view.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if (Build.VERSION.SDK_INT >= 21) {
height -= AndroidUtilities.statusBarHeight;
}
if (height > AndroidUtilities.dp(100) && height < AndroidUtilities.displaySize.y && height + AndroidUtilities.dp(100) > AndroidUtilities.displaySize.y) {
AndroidUtilities.displaySize.y = height;
FileLog.e("fix display size y to " + AndroidUtilities.displaySize.y);
}
}
});
}
} catch (Exception e) {
FileLog.e(e);
}
MediaController.getInstance().setBaseActivity(this, true);
}
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]));
}
I have this code as a method:
String resultTimeString = ct.toString()
if(resultTimeString.length() == 2 ){
resultTime1ASCII = resultTimeString.charAt(0);
resultTime2ASCII = resultTimeString.charAt(1);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime2 = (int)resultTime2ASCII - 48;
resultTime = resultTime1 + resultTime2;
}
else{
resultTime1ASCII = resultTimeString.charAt(0);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime = resultTime1;
}
punkty = punkty * resultTime;
//Globals.setScore(punkty);
ct.cancel();
The problem is in counting. Final score ("punkty") isn't multiply punkty and resultTime and I don't know why. Variable punkty is define as a points from giving a good answer.
Timer count down from 60 to 0.
You have said that the final score always remains 0.
The only way this could be happening is when you have initialized punkty as 0.
Each time, it multiplies by 0, and remains 0.
You should initialize punkty as 1. Then your code will work.
#Hackerdarshi, maybe I will show You all code:
public class QuestionActivity extends Activity {
private static final String TAG = "suemar";
int position = 0;
Button buttonA;
Button buttonB;
Button buttonC;
Button buttonD;
TextView textView;
TextView count;
Retrofit retrofit;
QuestionService questionService;
Call<pytania> QACall;
pytania questionsAnswers;
int licz = 0, punkty = 0;
String id;
char resultTime1ASCII,resultTime2ASCII;
int resultTime=0, resultTime1=0, resultTime2=0;
CountDownTimer ct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
buttonA = (Button) findViewById(R.id.buttonA);
buttonB = (Button) findViewById(R.id.buttonB);
buttonC = (Button) findViewById(R.id.buttonC);
buttonD = (Button) findViewById(R.id.buttonD);
textView = (TextView) findViewById(R.id.textView_pytanie);
count = (TextView) findViewById(R.id.countText);
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
ct = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
String v = String.format("%02d", millisUntilFinished/60000);
int va = (int)( (millisUntilFinished%60000)/1000);
count.setText(String.format("%02d", va));
}
public void onFinish() {
count.setText("0");
koniec();
}
};
ct.start();
Intent intent = getIntent();
position = intent.getExtras().getInt("position");
position++;
id = Integer.toString(position);
//Retrofit magic part
retrofit = new Retrofit.Builder()
.baseUrl("http://46.101.128.24/")
.addConverterFactory(GsonConverterFactory.create())
.build();
questionService = retrofit.create(QuestionService.class);
QACall = questionService.getQuestionsAnswers(id);
QACall.enqueue(new Callback<pytania>() {
#Override
public void onResponse(Call<pytania> call, Response<pytania> response) {
if (response.isSuccessful()) {
questionsAnswers = response.body();
// textView.setText(Integer.toString(questionsAnswers.success));
giveQuestions();
for (Questions c : questionsAnswers.Questions) {
Log.i(TAG, String.format("%s: %s", c.question, c.answer1));
Log.i(TAG, "---------");
}
} else {
Toast.makeText(QuestionActivity.this, "LOL2", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<pytania> call, Throwable t) {
Log.d("Coś się zepsuło", t.getMessage());
Toast.makeText(QuestionActivity.this, "LOL", Toast.LENGTH_SHORT).show();
}
});
}
public void onAnswer(View view) {
licz++;
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
switch (view.getId()) {
case R.id.buttonA:
buttonA.setBackgroundResource(R.drawable.button_game_click);
if (buttonA.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonB:
buttonB.setBackgroundResource(R.drawable.button_game_click);
if (buttonB.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonC:
buttonC.setBackgroundResource(R.drawable.button_game_click);
if (buttonC.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonD:
buttonD.setBackgroundResource(R.drawable.button_game_click);
if (buttonD.getText() == questionsAnswers.Questions.get(licz - 1).answer1) {
Toast.makeText(QuestionActivity.this, "Pan to umie ale tego nie rozumie :D", Toast.LENGTH_SHORT).show();
punkty++;
} else {
Toast.makeText(QuestionActivity.this, "...Bania.", Toast.LENGTH_SHORT).show();
}
break;
}
if (licz == 5) {
koniec();
} else {
Runnable r = new Runnable() {
#Override
public void run() {
buttonA.setBackgroundResource(R.drawable.button_game);
buttonB.setBackgroundResource(R.drawable.button_game);
buttonC.setBackgroundResource(R.drawable.button_game);
buttonD.setBackgroundResource(R.drawable.button_game);
giveQuestions();
}
};
Handler h = new Handler();
h.postDelayed(r, 300);
}
}
private void koniec() {
String resultTimeString = ct.toString();
//resultTime1ASCII = resultTimeString.charAt(resultTimeString.length() - 2);
//resultTime2ASCII = resultTimeString.charAt(resultTimeString.length()-1);
if(resultTimeString.length() == 2 ){
resultTime1ASCII = resultTimeString.charAt(0);
resultTime2ASCII = resultTimeString.charAt(1);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime2 = (int)resultTime2ASCII - 48;
resultTime = (resultTime1*10) + resultTime2;
}
else{
resultTime1ASCII = resultTimeString.charAt(0);
resultTime1 = (int)resultTime1ASCII - 48;
resultTime = resultTime1;
}
punkty = punkty * resultTime;
//Globals.setScore(punkty);
ct.cancel();
Intent intent = new Intent(QuestionActivity.this, YourResultActivity.class);
startActivity(intent);
finish();
}
public void giveQuestions() {
questionsAnswers.Questions.get(licz).ShuffleAnswers();
textView.setText(questionsAnswers.Questions.get(licz).question);
buttonA.setText(questionsAnswers.Questions.get(licz).getAnswer(0));
buttonB.setText(questionsAnswers.Questions.get(licz).getAnswer(1));
buttonC.setText(questionsAnswers.Questions.get(licz).getAnswer(2));
buttonD.setText(questionsAnswers.Questions.get(licz).getAnswer(3));
}
}
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.
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