Android Class cast exception with radio group widget? - java

Building a small quiz application and have some issues with the code, it worked on a previous version but that got delete during a fresh install of windows, when i try open up the a activity for a quiz i keep getting an unexpected error and the log says after a few lines
Java.lang.classexception : android.widget.Radio Group
the code for the activity looks like this
package com.example.quizzards;
import java.io.FileNotFoundException;
import java.util.Arrays;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class GamesActivity extends Activity {
boolean rightWrong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_games);
try {
#SuppressWarnings("unused")
Questions questions = new Questions(getApplicationContext());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
update();
Button answer = (Button) findViewById(R.id.AnswerButton);
answer.setOnClickListener(new OnClickListener()
{
public void onClick(View V)
{
RadioGroup allOptions = (RadioGroup) findViewById(R.id.questions);
int toCheck = allOptions.getCheckedRadioButtonId();
if (toCheck == -1) {
Toast.makeText(GamesActivity.this, "Please select an option.",
Toast.LENGTH_SHORT).show();
} else {
RadioButton selected = (RadioButton) findViewById(allOptions
.getCheckedRadioButtonId());
rightWrong = Questions.checkAnswer(selected.getText()
.toString());
if (rightWrong == true) {
Toast.makeText(GamesActivity.this, "Right!!!",
Toast.LENGTH_SHORT).show();
Questions.addPoint();
update();
} else {
Questions.incorrectTry();
int remainingTries = Questions.getRemainingTries();
if (remainingTries == 0) {
// Toast.makeText(MainActivity.this,
// "Your final score is " + Questions.getScore() + ".",
// Toast.LENGTH_SHORT).show();
Intent i = new Intent(GamesActivity.this,
ResultsActivity.class);
startActivity(i);
} else {
Toast.makeText(
GamesActivity.this,
"Wrong!!! " + remainingTries
+ " tries left.",
Toast.LENGTH_SHORT).show();
}
}
allOptions.clearCheck();
}
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(GamesActivity.this, PlayActivity.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.games, menu);
return true;
}
public void update()
{
if (Questions.finished()) {
Intent i = new Intent(GamesActivity.this,
ResultsActivity.class);
startActivity(i);
} else {
String[] aQuestion = Questions.getNextQuestion();
String[] temp = Arrays.copyOfRange(aQuestion, 1, aQuestion.length);
for (int i = 0; i < temp.length; i++) {
int r = (int) (Math.random() * (i + 1));
String swap = temp[r];
temp[r] = temp[i];
temp[i] = swap;
}
TextView textViewQuestion = (TextView) findViewById(R.id.questions);
textViewQuestion.setText(aQuestion[0]);
TextView textViewOption1 = (TextView) findViewById(R.id.option1);
textViewOption1.setText(temp[0]);
TextView textViewOption2 = (TextView) findViewById(R.id.option2);
textViewOption2.setText(temp[1]);
TextView textViewOption3 = (TextView) findViewById(R.id.option3);
textViewOption3.setText(temp[2]);
TextView textViewOption4 = (TextView) findViewById(R.id.option4);
textViewOption4.setText(temp[3]);
TextView runningTotal = (TextView) findViewById(R.id.runningTotal);
runningTotal.setText("Total: " + Questions.getScore());
}
}
}
The XML file contains a radio group and few radio buttons, when i try to run the code without any sort of radio buttons and comment out the code, works perfectly

Make sure all your RadioButtons and RadioGroup have different id's in the layout file.
Another small optimization would be to look for the RadioButtons inside RadioGroup as following.
RadioButton selected = (RadioButton) allOptions.findViewById(
allOptions.getCheckedRadioButtonId());

Related

How to Show Different Strings With The Same Position When Clicking Random Button?

How to Show Different Strings With The Same Position When Clicking Random Button, So when the string is randomized the word and word2 display the same position data and in different textview. I have been looking for information for a few days and have not found an answer yet. I am confused to do so can you help me? Here's the Java file I have.
Adapter.java
package com.word.game;
import java.util.Random;
public class Adapter {
public static final Random RANDOM = new Random();
public static final String[] WORDS = {"RUN",
"WALK",
"CRY",
"SUGAR",
"SALT",
"RAIN",
"NOVEMBER"};
public static final String[] WORDS2 = {"FAST",
"RELAX",
"TEARS",
"DRINK",
"RECIPERS",
"WATER",
"CALENDAR"};
public static String randomWord2() {
return WORDS2[RANDOM.nextInt(WORDS2.length)];
}
public static String randomWord() {
return WORDS[RANDOM.nextInt(WORDS.length)];
}
public static String shuffleWord(String word) {
if (word != null && !"".equals(word)) {
char a[] = word.toCharArray();
for (int i = 0; i < a.length; i++) {
int j = RANDOM.nextInt(a.length);
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return new String(a);
}
return word;
}
}
MainActivity.java
package com.papaozi.pilgub;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MediaPlayer mediaPlayerbg, mediaPlayerwin, mediaPlayerSalah;
private TextView suffletext, quest;
private EditText answer;
private Button validate, newGame;
private String wordToFind, wordToFind2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
quest = (TextView) findViewById(R.id.quest);
suffletext = (TextView) findViewById(R.id.suffletext);
answer = (EditText) findViewById(R.id.wordEnteredEt);
validate = (Button) findViewById(R.id.validate);
validate.setOnClickListener(this);
newGame = (Button) findViewById(R.id.newGame);
newGame.setOnClickListener(this);
answer.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
newGame();
initViews();
}
private void initViews() {
mediaPlayerbg = MediaPlayer.create(this, R.raw.spooky);
mediaPlayerbg.start();
mediaPlayerbg.setLooping(true);
}
#Override
public void onClick(View view) {
if (view == validate) {
validate();
} else if (view == newGame) {
newGame();
}
}
private void validate() {
String w = answer.getText().toString();
Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(R.layout.custom_toast_benar, null);
final Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
customtoast.setDuration(Toast.LENGTH_LONG);
Context context2 = getApplicationContext();
LayoutInflater inflater2 = getLayoutInflater();
View customToastroot2 = inflater2.inflate(R.layout.custom_toast_salah, null);
final Toast customtoast2 = new Toast(context2);
customtoast2.setView(customToastroot2);
customtoast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
customtoast2.setDuration(Toast.LENGTH_LONG);
if (wordToFind.equals(w)) {
customtoast.show();
newGame();
mediaPlayerwin = MediaPlayer.create(this, R.raw.winner);
mediaPlayerwin.start();
} else {
customtoast2.show();
mediaPlayerSalah = MediaPlayer.create(this, R.raw.draw);
mediaPlayerSalah.start();
}
}
private void newGame() {
wordToFind = Adapter.randomWord();
String wordShuffled = Adapter.shuffleWord(wordToFind);
suffletext.setText(wordShuffled);
answer.setText("");;
}
protected void onDestroy() {
super.onDestroy();
if (mediaPlayerbg != null) {
mediaPlayerbg.release();
mediaPlayerbg = null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(MainActivity.this, SecondActivity.class));
mediaPlayerbg.stop();
finish();
}
}
If you want to return same position in different arrays with same size,
Try this
public static String randomWord2(int pos) {
return WORDS2[pos];
}
public static String randomWord(int pos) {
return WORDS[pos];
}
public static int randomNum() {
return RANDOM.nextInt(WORDS.length);
}
When You are invoking randomWord() and randomWord2() , get the random position first and the pass it to the methods
int pos= randomNum();
word1=randomWord(pos);
word2=randomWord2(pos);

Refresh the android activity and show the updated details in the same activity .When i pressed the update button

I updated the table in sqlite database,
but i don't know how to get the updated details
in the same activity with refresh when pressing update a buttton.
i tried below code
finish();
startActivity(getintent());
It loading the same Activity again and showing nothing .
I know this is not the right way.I need your help.
Thanks in advance.
this is my code.
package com.example.eightyeight.monthmaths;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class secondactivity extends AppCompatActivity {
String selected = "", yy = "", mm = "";
FloatingActionButton search;
Spinner sid;
List<String> li;
TableLayout tbid;
EditText year;
Cursor cur;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
sid = (Spinner) findViewById(R.id.monthspinid);
year = (EditText) findViewById(R.id.yearid);
search = (FloatingActionButton) findViewById(R.id.goid);
tbid = (TableLayout) findViewById(R.id.tbid);
li = new ArrayList<String>();
li.add("Month...");
li.add("Jan");
li.add("Feb");
li.add("Mar");
li.add("Apr");
li.add("May");
li.add("Jun");
li.add("Jul");
li.add("Aug");
li.add("Sep");
li.add("Oct");
li.add("Nov");
li.add("Dec");
ArrayAdapter<String> ad;
ad = new ArrayAdapter<String>(secondactivity.this, android.R.layout.simple_spinner_item, li);
ad.setDropDownViewResource(android.R.layout.simple_spinner_item);
sid.setAdapter(ad);
sid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected = (String) sid.getSelectedItem();
Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yy = year.getText().toString();
mm = (String) sid.getSelectedItem();
SQLiteDatabase db;
db = openOrCreateDatabase("monthapp", MODE_PRIVATE, null);
cur = db.rawQuery("SELECT * FROM monthvaluesOrgin WHERE curmonth='" + mm + "' AND curyear='" + yy + "'", null);
while (cur.moveToNext()) {
TableRow tr = new TableRow(secondactivity.this);
TextView tv1 = new TextView(secondactivity.this);
tv1.setWidth(100);
tv1.setText(cur.getString(1));
tr.addView(tv1);
final TextView tv2 = new TextView(secondactivity.this);
tv2.setText(cur.getString(2));
tv2.setWidth(100);
tr.addView(tv2);
final EditText et = new EditText(secondactivity.this);
tr.addView(et);
final TextView t21 = new TextView(secondactivity.this);
t21.setText(cur.getString(0));
tr.addView(t21);
final TextView tv3 = new TextView(secondactivity.this);
tv3.setText(cur.getString(3));
tv3.setWidth(100);
tr.addView(tv3);
Button b = new Button(secondactivity.this);
b.setText("update");
tr.addView(b);
tbid.addView(tr);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String a = (String) tv2.getText();
String totl = (String) tv3.getText();
int totv = Integer.parseInt(totl);
int b = Integer.parseInt(a);
Editable edi = et.getText();
int c = Integer.parseInt(String.valueOf(edi));
String id = (String) t21.getText();
int add = b + c;
if (add >= totv) {
Toast.makeText(getApplicationContext(), "large", Toast.LENGTH_SHORT).show();
} else {
SQLiteDatabase dbup;
dbup = openOrCreateDatabase("monthapp", MODE_PRIVATE, null);
dbup.execSQL("UPDATE monthvaluesOrgin SET currentpaid='" + add + "' WHERE id='" + id + "'");
Toast.makeText(getApplicationContext(), "added" + add + "\n" + id, Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
}
// Toast.makeText(getApplicationContext(),"add="+add,Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
Why you calling startActivity Again & again ?
Good Approach
Use notifyDataSetChanged()
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.
ad.notifyDataSetChanged();
Code
dbup = openOrCreateDatabase("monthapp", MODE_PRIVATE, null);
dbup.execSQL("UPDATE monthvaluesOrgin SET currentpaid='" + add + "' WHERE id='" + id + "'");
Toast.makeText(getApplicationContext(), "added" + add + "\n" + id, Toast.LENGTH_LONG).show();
ad.notifyDataSetChanged(); // This
create method to update list in Adapter, and after updating DB call it
public void refresh(Cursor newCursor) {
if (mCursor != null) mCursor.close();
mCursor = newCursor;
if (newCursor != null)
this.notifyDataSetChanged();
}

Error java.lang.NumberFormatException: Invalid double: "86,24" [duplicate]

This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Android NumberFormatException: Invalid Double - except the value is a valid Double
(2 answers)
Closed 6 years ago.
Android studio noti this error.This code by a main screen of quiz game
How to fix it??? i was try some guide but nothing
This is My error
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid double: "86,24"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
at java.lang.Double.parseDouble(Double.java:295)
at gt.scratchgame.MainActivity.checkAns(MainActivity.java:345)
at gt.scratchgame.MainActivity.onClick(MainActivity.java:318)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
My activity
package gt.scratchgame;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import gt.scratchgame.base.Session;
import gt.scratchgame.bean.AnsOptionBean;
import gt.scratchgame.bean.BeanEachQuetionScore;
import gt.scratchgame.bean.QuestionAnsbean;
import gt.scratchgame.constants.AppConstants;
import gt.scratchgame.database.DBhelper;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private WScratchView scratchView;
private TextView percentageView, scorelabel, textViewNo, textViewcounter, textViewTotalScore, textView3;
private float mPercentage;
public DBhelper dbhelper;
AQuery aQuery;
private static QuestionAnsbean questionAnsbean1;
private static String trueAns = null;
private static int quetionNumber = 0;
protected Button gameActivityButton1, gameActivityButton2, gameActivityButton3, gameActivityButton4;
ImageView imageView;
Session session;
Bitmap bitmap;
Typeface typeface;
private static float totalScore = 0;
public List<QuestionAnsbean> questionAnsList;
private List<BeanEachQuetionScore> scoreList;
ProgressDialog dialog;
private StartAppAd startAppAd;
AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
protected void onResume() {
super.onResume();
questionAnsList = new ArrayList<QuestionAnsbean>();
startAppAd = new StartAppAd(this);
aQuery = new AQuery(this);
session = Session.getInstance();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.scratchview1);
scoreList = new ArrayList<BeanEachQuetionScore>();
scratchView = (WScratchView) findViewById(R.id.scratch_view);
scratchView.setScratchBitmap(bitmap);
typeface = Typeface.createFromAsset(getAssets(),"customestyle.TTF");
totalScore = 0;
quetionNumber = 0;
dialog = new ProgressDialog(this);
initDialogProperty();
asyncJson();
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
StartAppSDK.init(this, AppConstants.DEVELOPER_ID, AppConstants.APP_ID, true);
// StartAppAd.showSlider(this);
startAppAd.showAd();
}
private void initDialogProperty() {
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.setMessage("Loading...");
}
private void initUI() {
percentageView = (TextView) findViewById(R.id.percentage);
percentageView.setTypeface(typeface);
scorelabel = (TextView) findViewById(R.id.scorelabel);
scorelabel.setTypeface(typeface);
textViewNo = (TextView) findViewById(R.id.textViewNo);
textViewNo.setTypeface(typeface);
textViewcounter = (TextView) findViewById(R.id.textViewcounter);
textViewcounter.setTypeface(typeface);
textViewTotalScore = (TextView) findViewById(R.id.textViewTotalScore);
textViewTotalScore.setTypeface(typeface);
textViewTotalScore.setText(totalScore + "");
textView3 = (TextView) findViewById(R.id.textView3);
textView3.setTypeface(typeface);
dbhelper = DBhelper.getInstance(getApplicationContext());
dbhelper.open();
initDb();
Collections.shuffle(questionAnsList);
/*Game Activity 4 option button*/
gameActivityButton1 = (Button) findViewById(R.id.gameActivityButton1);
gameActivityButton2 = (Button) findViewById(R.id.gameActivityButton2);
gameActivityButton3 = (Button) findViewById(R.id.gameActivityButton3);
gameActivityButton4 = (Button) findViewById(R.id.gameActivityButton4);
gameActivityButton1.setTypeface(typeface);
gameActivityButton2.setTypeface(typeface);
gameActivityButton3.setTypeface(typeface);
gameActivityButton4.setTypeface(typeface);
gameActivityButton1.setOnClickListener(this);
gameActivityButton2.setOnClickListener(this);
gameActivityButton3.setOnClickListener(this);
gameActivityButton4.setOnClickListener(this);
quetionInitialize();
// customize attribute programmatically
scratchView.setScratchable(true);
scratchView.setRevealSize(50);
scratchView.setAntiAlias(true);
// scratchView.setOverlayColor(Color.RED);
scratchView.setBackgroundClickable(true);
// add callback for update scratch percentage
scratchView.setOnScratchCallback(new WScratchView.OnScratchCallback() {
#Override
public void onScratch(float percentage) {
updatePercentage(percentage);
}
#Override
public void onDetach(boolean fingerDetach) {
/* if(mPercentage > 1){
scratchView.setScratchAll(true);
updatePercentage(100);
}*/
}
});
updatePercentage(0f);
}
private void updatePercentage(float percentage) {
mPercentage = percentage;
String percentage2decimal = String.format("%.2f", (100 - percentage));
percentageView.setText(percentage2decimal);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/* #Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
private void initDb() {
// Toast.makeText(getApplicationContext()," DB size-- "+dbhelper.getUserData().size(),Toast.LENGTH_LONG).show();
// dbhelper.addData(session.getSelectedCategory().id,"guru",123.36f);
}
public void asyncJson() {
// String url = "http://gurutechnolabs.com/demo/kids/demo.php?category=+""&level=level";
// Toast.makeText(getApplicationContext(),"aaaaaa",Toast.LENGTH_LONG).show();
int id = session.getSelectedCategory().id;
dialog.show();
String url = "http://8chan.biz/app/demo.php?category="+id;
Log.d("*************",url);
aQuery.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if (json != null) {
try {
JSONObject mainJsonObject = new JSONObject(json.toString());
if(mainJsonObject != null)
{
JSONArray list = mainJsonObject.getJSONArray("data");
if(list != null)
{
for(int i = 0 ; i < list.length() ; i++)
{
JSONObject subObject = list.getJSONObject(i);
// aQuery.id(R.id.result).visible().text(subObject.toString());
QuestionAnsbean questionAnsbean = new QuestionAnsbean();
questionAnsbean.id = subObject.getInt("id");
questionAnsbean.cat_id = subObject.getInt("cat_id");
questionAnsbean.url = subObject.getString("url");
JSONArray questionAnsOptionArrary = subObject.getJSONArray("answers");
for (int j = 0; j < questionAnsOptionArrary.length(); j++)
{
JSONObject suObject1 = questionAnsOptionArrary.getJSONObject(j);
AnsOptionBean ansOptionBean = new AnsOptionBean();
ansOptionBean.answer = suObject1.getString("answer");
ansOptionBean.result = suObject1.getInt("result");
questionAnsbean.ansOptionList.add(ansOptionBean);
}
questionAnsList.add(questionAnsbean);
// session.setOperationLists1(questionAnsbean);
// Toast.makeText(getApplicationContext(),levelLists.size()+"",Toast.LENGTH_LONG).show();
//gameLevelGridAdapter.notifyDataSetChanged();
}
// Collections.shuffle(ansOptionList);
}
// Toast.makeText(getApplicationContext(),questionAnsList.size()+" This is list size in asin aquery ",Toast.LENGTH_LONG).show();
initUI();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), listItem.size()+"", Toast.LENGTH_LONG).show();
//showResult(json, status);
} else {
// ajax error, show error code
/* Toast.makeText(aQuery.getContext(),
"Error:" + status.getMessage(), Toast.LENGTH_LONG)
.show();*/
}
}
});
}
private void quetionInitialize() {
scratchView.resetView();
scratchView.setScratchAll(false);
textViewcounter.setText(quetionNumber+"");
questionAnsbean1 = new QuestionAnsbean();
questionAnsbean1 = questionAnsList.get(quetionNumber);
dialog.dismiss();
aQuery.id(R.id.extra).progress(dialog).image(questionAnsList.get(quetionNumber).url, true, true);
ansOptionInitialize();
}
/*Quation ans intialize and set*/
private void ansOptionInitialize() {
try {
Collections.shuffle(questionAnsbean1.ansOptionList);
gameActivityButton1.setText(questionAnsbean1.ansOptionList.get(0).answer);
gameActivityButton2.setText(questionAnsbean1.ansOptionList.get(1).answer);
gameActivityButton3.setText(questionAnsbean1.ansOptionList.get(2).answer);
gameActivityButton4.setText(questionAnsbean1.ansOptionList.get(3).answer);
if(questionAnsbean1.ansOptionList.get(0).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(0).answer;
}
else if(questionAnsbean1.ansOptionList.get(1).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(1).answer;
}
else if(questionAnsbean1.ansOptionList.get(2).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(2).answer;
}
else if(questionAnsbean1.ansOptionList.get(3).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(3).answer;
}
}
catch (Exception e)
{
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.gameActivityButton1:
checkAns(gameActivityButton1.getText().toString());
break;
case R.id.gameActivityButton2:
checkAns(gameActivityButton2.getText().toString());
break;
case R.id.gameActivityButton3:
checkAns(gameActivityButton3.getText().toString());
break;
case R.id.gameActivityButton4:
checkAns(gameActivityButton4.getText().toString());
break;
default:
break;
}
}
private void checkAns(String text) {
BeanEachQuetionScore beanEachQuetionScore = new BeanEachQuetionScore();
beanEachQuetionScore.quetionNo = quetionNumber;
beanEachQuetionScore.url = questionAnsList.get(quetionNumber).url;
beanEachQuetionScore.playerAns = text;
beanEachQuetionScore.trueAns = trueAns;
beanEachQuetionScore.quetionScore = Double.parseDouble(percentageView.getText().toString());
scoreList.add(beanEachQuetionScore);
if (text.equals(trueAns)) {
totalScore = totalScore + Float.parseFloat(percentageView.getText().toString());
textViewTotalScore.setText(String.format("%.2f", totalScore));
quetionNumber++;
if(quetionNumber < questionAnsList.size()) {
quetionInitialize();
}
else {
gameOver();
}
}
else {
totalScore = totalScore - Float.parseFloat(percentageView.getText().toString());
textViewTotalScore.setText(String.format("%.2f", totalScore));
quetionNumber++;
if(quetionNumber < questionAnsList.size()) {
quetionInitialize();
}
else {
gameOver();
}
}
}
private void gameOver() {
session.setScoreBeen(scoreList);
session.setTotalScoreInSession(Float.parseFloat(textViewTotalScore.getText().toString()));
Intent intent = new Intent(getApplicationContext(),ScoreBord.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(),SelectCategoryActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
Your issue actually brings up a larger issue that is especially relevant when developing a mobile app: Locale. Rather than use Double.parse(), which does not take Locale into account, consider using NumberFormat instead.
NumberFormat nf = NumberFormat.getInstance(); //gets an instance with the default Locale
Number parsed = nf.parse(percentageView.getText().toString());
beanEachQuetionScore.quetionScore = parsed.doubleValue();
For your float values, you can use the same concept:
Number parsedFloat = nf.parse(someFloatString);
float floatVal = parsedFloat.floatValue();
This of course assumes that OP is in a Locale that uses ',' instead of '.' as a separator.

POST not occuring on Android?

Hey so I am not getting an error, but all my logs get initiated except for the one after HttpResponse not sure why, and on the server end I do not see any activity of a POST coming in...
here is my code:
package com.sfsfdsfds;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class wardrobe extends Activity{
//set variable for the fields
private EditText nameField;
private Spinner typeField;
private EditText colorField;
private Spinner seasonField;
private EditText sizeField;
private EditText quantityField;
private ImageView imageField;
private ProgressBar progressBarField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
//button for upload image
Button uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
//button for posting details
Button postWardrobe = (Button) findViewById(R.id.postButton);
//Value of fields
nameField = (EditText) findViewById(R.id.nameFieldWardrobeScreen);
typeField = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
colorField = (EditText) findViewById(R.id.colorFieldWardrobeScreen);
seasonField = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
sizeField = (EditText) findViewById(R.id.sizeFieldWardrobeScreen);
quantityField = (EditText) findViewById(R.id.quantityFieldWardrobeScreen);
imageField = (ImageView) findViewById(R.id.user_photo);
progressBarField = (ProgressBar) findViewById(R.id.progressBarWardrobe);
progressBarField.setVisibility(View.GONE);
//Creating spinner for select/options for type field
Spinner spinnerType = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterTypeArray = ArrayAdapter.createFromResource(this, R.array.type_array, android.R.layout.simple_spinner_item);
adapterTypeArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterTypeArray);
//Creating spinner for select/options for season field
Spinner spinnerSeason = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterSeasonArray = ArrayAdapter.createFromResource(this, R.array.season_array, android.R.layout.simple_spinner_item);
adapterSeasonArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSeason.setAdapter(adapterSeasonArray);
uploadImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//below allows you to open the phones gallery
Image_Picker_Dialog();
}
});
postWardrobe.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//validate input and that something was entered
if(nameField.getText().toString().length()<1 || colorField.getText().toString().length()<1 || sizeField.getText().toString().length()<1 || quantityField.getText().toString().length()<1) {
//missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(), "Please complete all sections!", Toast.LENGTH_LONG).show();
} else {
JSONObject dataWardrobe = new JSONObject();
try {
dataWardrobe.put("type", typeField.getSelectedItem().toString());
dataWardrobe.put("color", colorField.getText().toString());
dataWardrobe.put("season", seasonField.getSelectedItem().toString());
dataWardrobe.put("size", sizeField.getText().toString());
dataWardrobe.put("quantity", quantityField.getText().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//make progress bar visible
progressBarField.setVisibility(View.VISIBLE);
//execute the post request
new dataSend().postData(dataWardrobe);
}
//below should send data over
}
});
}
// After the selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
{
// data contains result
// Do some task
Image_Selecting_Task(data);
} else if (requestCode == Utility.CAMERA_PICTURE)
{
// Do some task
Image_Selecting_Task(data);
}
}
public void Image_Picker_Dialog()
{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.setType("image/*");
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
public void Image_Selecting_Task(Intent data)
{
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
try
{
Utility.uri = data.getData();
if (Utility.uri != null)
{
// User had pick an image.
Cursor cursor = getContentResolver().query(Utility.uri, new String[]
{ android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
//Assign string path to File
Utility.Default_DIR = new File(imageFilePath);
// Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
Utility.Create_MY_IMAGES_DIR();
// Copy your image
Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);
// Get new image path and decode it
Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);
// use new copied path and use anywhere
String valid_photo = Utility.Paste_Target_Location.toString();
b = Bitmap.createScaledBitmap(b, 150, 150, true);
//set your selected image in image view
user_photo.setImageBitmap(b);
cursor.close();
} else
{
Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
toast.show();
}
} catch (Exception e)
{
// you get this when you will not select any single image
Log.e("onActivityResult", "" + e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Calling code for different selected menu options
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
//show settings activity screen (main preference activity file)
case R.id.wardrobe:
Intent intent = new Intent(wardrobe.this, wardrobe.class);
startActivity(intent);
//if index button clicked in menu sub-menu options
case R.id.matches:
Toast.makeText(this, "matches was clicked!", 5).show();
//if index button clicked in menu sub-menu options
case R.id.worn:
Toast.makeText(this, "worn was clicked!", 5).show();
default:
}
return super.onOptionsItemSelected(item);
}
private class dataSend extends AsyncTask<JSONObject, Integer, Double> {
protected Double doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
progressBarField.setVisibility(View.GONE);
Toast.makeText(wardrobe.this, "info sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress) {
progressBarField.setProgress(progress[0]);
}
public void postData(JSONObject dataWardrobe) {
Log.v("posting data", "poooooost");
// Create a new HttpClient and Post Header
//int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
//HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
Log.v("posteed", "posteed url");
try {
Log.v("trying data", "prep");
//add data
StringEntity se = new StringEntity( dataWardrobe.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
Log.v("posteed", "posteed 11");
// execute http post request
HttpResponse response = httpclient.execute(httppost);
Log.v("posteed", "posteed 22");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Not sure what I am doing wrong, I tried various things and trying to look up different ways to go about doing this and none of them have worked... maybe it is something more simple than I see... the problem I think lies in the private class within this class.
I haven't read your code in great detail, but I suspect a strong contributor is this:
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
If you're using the emulator it's probably more likely you want to connect to "10.0.2.2". which is:
Special alias to your host loopback interface (i.e., 127.0.0.1 on your
development machine)
See here for more details on the emulator networking:
http://developer.android.com/tools/devices/emulator.html#emulatornetworking

ArrayList to charsequence conversion issue when selecting an option

I populate an alerttdialog from a database. I store these values in an arrayList, convert them to an charsequence list then set them to my alertdialog builder. As shown:
This is a screenshot of my populated 'text template' options from my database:
At the moment when I click one of my options for example Call me. it displays as it should within a specified edittext. If I click on one of the other options such as 'Email me' this is ignored, only my first 'if' option Call me. will work as shown:
This leads me to believe for some reason only Call me has been added to my charsequence array but I'm not sure why. Here is my complete class. I am getting this issue at the longOnClick method. I have marked this issue area on the code below:
package com.example.flybase2;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ContactsEmail extends Activity implements OnClickListener, OnLongClickListener{
String emailPassed;
String emailAdd;
String emailSub;
String emailMess;
EditText setEmailAddress;
EditText setEmailSubject;
EditText setEmailMessage;
Button btnSendEmail;
int i;
CharSequence[] items;
DBHandlerTempComms addTemp = new DBHandlerTempComms(this, null, null);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emaillayout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
emailPassed = extras.getString("passedEmailAdd");
}
setEmailAddress = (EditText) findViewById (R.id.inputEmailAddress);
setEmailAddress.setText(emailPassed);
setEmailSubject = (EditText) findViewById (R.id.inputEmailSubject);
setEmailMessage = (EditText) findViewById (R.id.inputEmailMessage);
btnSendEmail = (Button)findViewById(R.id.btnSendEmail);
btnSendEmail.setOnClickListener(this);
setEmailMessage.setOnLongClickListener(this);
}
#Override
public void onClick(View sendEmailClick) {
emailAdd = setEmailAddress.getText().toString();
emailSub = setEmailSubject.getText().toString();
emailMess = setEmailMessage.getText().toString();
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL,new String[] {emailAdd});
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSub);
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, emailMess);
startActivity(Intent.createChooser(sendEmailIntent, "Send mail..."));
finish();
}
*********************ISSUE AREA********************
#Override
public boolean onLongClick(View v) {
addTemp.open();
Cursor getTemps = addTemp.setList();
addTemp.close();
if (getTemps != null) {
String[] from = new String[getTemps.getCount()];
startManagingCursor(getTemps);
if (getTemps.moveToFirst()) {
int count = 0;
do {
String userName = getTemps.getString(1);
from[count] = userName;
count++;
} while (getTemps.moveToNext());
}
ArrayList<String> content = new ArrayList<String>();
for (int a = 0; a < from.length; a ++)
{
content.add(from[a]);
}
items = content.toArray(new CharSequence[content.size()]);
}
Builder alertDialogBuilder = new AlertDialog.Builder(ContactsEmail.this);
alertDialogBuilder.setTitle("Message Templates:");
alertDialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Call me.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Text me.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Leaving the house now.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Leaving work now.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Create New Template +")) {
AlertDialog.Builder builder = new AlertDialog.Builder(ContactsEmail.this);
builder.setTitle("Type New Template:");
final EditText input = new EditText(ContactsEmail.this);
builder.setView(input);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
setEmailMessage.setText(value);
String templateValue = (String)value.toString();
addTemp.open();
addTemp.insertTemplate(templateValue);
addTemp.close();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
builder.show();
}
}
});
alertDialogBuilder.show();
return true;
}
}
Slightly embarrassing but I've just realized I have different strings comparing my IFs to the strings stored in the charsequence, so it is now working!

Categories

Resources