Android:无法在代码中找到错误?

时间:2014-04-28 19:16:04

标签: java android

我理解这是一个非常长篇大论的请求,希望任何人都能回答,但我已经尝试了一些我能想到的解决这个问题的方法。

在我的Android应用程序中,我首先进行此活动,该活动接受用户输入(数字)并将其传递给下一个活动:

public class Practice extends Activity implements View.OnClickListener {

    // Declaring Vars
    Button go2;
    EditText enterNumber2;
    TextView top2;
    TextView bottom2;
    private Integer convertedNumber2; // change back to private Integer?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // setting equal to text layout View
        setContentView(R.layout.practice);

        // calling method to intialise vars
        initialiseVars();

        // setting on click listeners for edit text and button
        go2.setOnClickListener(this);
        enterNumber2.setOnClickListener(this);

    }// on create end

    /**
     * method to initialise all of the buttons, textviews etc used to clean up
     * the onCreate.
     */
    private void initialiseVars() {
        // Setting up (initialising) all the buttons text views etc from the xml
        // (vid 25)
        go2 = (Button) findViewById(R.id.btnGoPractice);
        enterNumber2 = (EditText) findViewById(R.id.etEnterNumberPractce);
        top2 = (TextView) findViewById(R.id.tvTopPractice);
        bottom2 = (TextView) findViewById(R.id.tvBottomPractice);

    }

    /**
     * Method with on click listener that adds functionality for all of the
     * buttons, text views etc
     * 
     * @param v
     */
    public void onClick(View view) {

        // switch statement which determines what is clicked
        switch ((view).getId()) {
        case R.id.btnGoPractice:

            // sets text view equal to whats typed in in editText
            final String entry = enterNumber2.getText().toString().trim();// get your number
            entry.replaceAll("\\D+","");//possibly delete

            try {
                convertedNumber2 = Integer.parseInt(entry);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }

            Intent intent = new Intent(this, PracticeTest.class);
            if (convertedNumber2 >= 1 && convertedNumber2 <= 12) {
                intent.putExtra("convertedNumber2", convertedNumber2);
                System.out.println("Valid number");
            } else {
                System.out.println("Invalid number");
            }
            startActivity(intent);


            /**
             * UNCOMMENT THIS IF THE ABOVE DOESNT WORK
             // sets text view equal to whats typed in in editText final
             * String entry = enterNumber2.getText().toString();
             * 
             * // convert from string value to int convertedNumber2 =
             * Integer.parseInt(entry);
             * 
             * Intent intent = new Intent(this, PracticeTest.class); if
             * (convertedNumber2 >= 1 && convertedNumber2 <= 12) {
             * intent.putExtra("convertedNumber2", convertedNumber2);
             * startActivity(intent); } else {
             * System.out.println("Invalid number"); }
             * 
             * break; default: System.out.println("invalid entry"); break;
             * 
             * }
             */

        }
    }

}// c end

以下活动收到数字,并根据数字(乘法时间表)开始循环问题:

public class PracticeTest extends Activity implements View.OnClickListener {

    // declare vars
    int multiplier;
    int[] results = new int[12];
    int numberPassed;
    TextView question;
    EditText answer;
    int score;
    String[] questions = new String[12];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.practicetest);

        // This declares and int variable, assigns it an int value from the
        // calling Intent if its not there it is defaulted to 0
        numberPassed = getIntent().getIntExtra("convertedNumber2", 0);

        // setting up vars(possibly do this in different method?
        Button submit = (Button) findViewById(R.id.btnGoPractice2); 
        answer = (EditText) findViewById(R.id.etEnterNumberPractice2);
        question = (TextView) findViewById(R.id.tvTopPractice2);

        // setting listeners
        submit.setOnClickListener(this);

        updateQuestion();

    }

    public void onClick(View view) {

        // sets text view equal to whats typed in in editText
        final String entry = answer.getText().toString();

        // convert from string value to int
        int a = Integer.parseInt(entry); // note: maybe change name

        results[multiplier - 1] = a;
        score++;// Irrelevant?

        if (multiplier < 12) {

            // called after an answer is given
            updateQuestion();

        } else {
            // System.out.println(score);
            Intent intent = new Intent(this, Results.class);
            intent.putExtra("results", results);
            intent.putExtra("numberPassed", numberPassed);
            intent.putExtra("questions", questions);
            this.startActivity(intent);
        }

    }

    public void updateQuestion() {

        multiplier++;

        // string to hold quest
        String q = numberPassed + "x" + multiplier + "=";
        questions[multiplier - 1] = q;
        question.setText(questions[multiplier - 1]);
        answer.setText("");

    }

}

然后,此活动会获取用户的答案等,并将其传递给此活动:

public class Results extends Activity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.results);

        ListView itemList = (ListView) findViewById(R.id.lvresults);

        //gets arrays from prev act
        int[] results = getIntent().getIntArrayExtra("results");

        int numberPassed = getIntent().getIntExtra("numberPassed", 0);

        String[] questions= getIntent().getStringArrayExtra("questions");



        ArrayList < HashMap <String, String> > list = new ArrayList < HashMap <String, String> > ();


        // loop to give list view
        for (int i = 1; i <= 12; i++)
        {
            int userAnswer = results[i - 1];

            int expectedAnswer = numberPassed * i;

            String userString = numberPassed + " x " + i + " = " + userAnswer;


            String expectedString = " " + expectedAnswer;

            HashMap <String, String> map = new HashMap <String, String> ();

            map.put("user", userString);
            map.put("expected", expectedString);

            list.add(map);
        }

         // Instantiate custom array adapter
        MyArrayAdapterPractice adapter = new MyArrayAdapterPractice(this.getApplicationContext(), R.layout.list_row_practice, list, questions, results);

        // Here you set the custom adapter to your ListView.
        itemList.setAdapter(adapter);

    }
}

在整个过程中,我使用以下适配器:

public class MyArrayAdapterPractice extends ArrayAdapter<ArrayList<HashMap<String, String>>>
{
    Context mContext;
    ArrayList<HashMap<String, String>> mQuestionArrayList;
    int mLayoutResourceId;
    String[] mQuestionsArray;
    int[] mUsersAnswers;

    public MyArrayAdapterPractice(Context context, int layoutResourceId, ArrayList<HashMap<String, String>> questionsArrayList, String[] questionsArray, int[] usersAnswers)
    {
        super(context, layoutResourceId);
        mContext = context;
        this.mQuestionArrayList = questionsArrayList;
        this.mLayoutResourceId = layoutResourceId;
        this.mQuestionsArray = questionsArray;
        this.mUsersAnswers = usersAnswers;
    }

    @Override
    public int getCount()
    {
        return mQuestionArrayList.size();
    }

    @Override
    public View getView(int position, View row, ViewGroup parent)
    {
        HashMap<String, String> question = mQuestionArrayList.get(position);

        LayoutInflater inflater = LayoutInflater.from(mContext);

        // Here you will initialize the row layout, by inflating the xml file list_row.
        row = inflater.inflate(this.mLayoutResourceId, parent, false);

        // Here we initialize those two TextViews defined in the list_row layout.
        TextView questionTxtView = (TextView) row.findViewById(R.id.tvPracticeQuestion);
        TextView answerTxtView = (TextView) row.findViewById(R.id.tvPracticeAnswer);
        TextView correctAnswerTxtView = (TextView) row.findViewById(R.id.tvPracticeCorrect);

        questionTxtView.setText(mQuestionsArray[position]);
        answerTxtView.setText(String.valueOf(mUsersAnswers[position]));
        correctAnswerTxtView.setText(question.get("expected").toString());

        // This is just a pseudo code to show you when and how to set the colors of
        // the TextView programatically.
        if(mUsersAnswers[position] != Integer.parseInt(question.get("expected").toString()))
            answerTxtView.setTextColor(Color.RED);
        else
            answerTxtView.setTextColor(Color.GREEN);

        return row;
    }
}

最后这是我尝试运行代码时得到的logcat错误跟踪(请注意,仿真器会在result.java活动即将打开的情况下切断):

04-28 19:03:54.792: E/AndroidRuntime(1059): FATAL EXCEPTION: main
04-28 19:03:54.792: E/AndroidRuntime(1059): Process: com.example.multapply, PID: 1059
04-28 19:03:54.792: E/AndroidRuntime(1059): java.lang.NumberFormatException: Invalid int: " 9"
04-28 19:03:54.792: E/AndroidRuntime(1059):     at java.lang.Integer.invalidInt(Integer.java:137)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at java.lang.Integer.parse(Integer.java:374)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at java.lang.Integer.parseInt(Integer.java:365)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at java.lang.Integer.parseInt(Integer.java:331)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at com.example.multapply.MyArrayAdapterPractice.getView(MyArrayAdapterPractice.java:59)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.widget.AbsListView.obtainView(AbsListView.java:2263)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.widget.ListView.onMeasure(ListView.java:1175)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.View.measure(View.java:16497)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.View.measure(View.java:16497)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.View.measure(View.java:16497)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.View.measure(View.java:16497)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.View.measure(View.java:16497)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.Choreographer.doFrame(Choreographer.java:544)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.os.Handler.handleCallback(Handler.java:733)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.os.Looper.loop(Looper.java:136)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at java.lang.reflect.Method.invokeNative(Native Method)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at java.lang.reflect.Method.invoke(Method.java:515)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-28 19:03:54.792: E/AndroidRuntime(1059):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

要找出错误所在,您必须读取堆栈跟踪。这是相关部分(强调我的):

  

04-28 19:03:54.792:E / AndroidRuntime(1059): java.lang.NumberFormatException:无效的int:&#34; 9&#34;

     

04-28 19:03:54.792:E / AndroidRuntime(1059):at java.lang.Integer.invalidInt(Integer.java:137)

     

04-28 19:03:54.792:E / AndroidRuntime(1059):at java.lang.Integer.parse(Integer.java:374)

     

04-28 19:03:54.792:E / AndroidRuntime(1059):at java.lang.Integer.parseInt(Integer.java:365)

     

04-28 19:03:54.792:E / AndroidRuntime(1059):at java.lang.Integer.parseInt(Integer.java:331)

     

04-28 19:03:54.792:E / AndroidRuntime(1059): at com.example.multapply.MyArrayAdapterPractice.getView(MyArrayAdapterPractice.java:59)

因此,这意味着在方法MyArrayAdapterPractice#getView内的文件 MyArrayAdapterPractice.java 的第59行引发了错误。您只需要转到当前代码的那一部分,检查问题并修复它。

从分析中,错误消息非常具体:

java.lang.NumberFormatException: Invalid int: " 9"

您正在发送" 9",但无法将其转换为Integer。修剪字符串,然后解析它。

这是有问题的一行:

if(mUsersAnswers[position] != Integer.parseInt(question.get("expected").toString()))

将其转换为

if(mUsersAnswers[position] != Integer.parseInt(question.get("expected").toString().trim()))