数字格式异常: 无效 int: "null"



方法compareScores(int, int, int) 应该返回一个 int 值。还有其他错误。我已经研究过这个错误,但我似乎无法纠正这个错误。


这是日志猫:

01-06 09:14:22.838: E/AndroidRuntime(27362): FATAL EXCEPTION: main
01-06 09:14:22.838: E/AndroidRuntime(27362): java.lang.NumberFormatException: Invalid int: "null"
01-06 09:14:22.838: E/AndroidRuntime(27362):    at java.lang.Integer.invalidInt(Integer.java:138)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at java.lang.Integer.parseInt(Integer.java:355)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at java.lang.Integer.parseInt(Integer.java:332)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at com.example.plearnyforparent.DiagnosticFour$2.onClick(DiagnosticFour.java:104)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at android.view.View.performClick(View.java:4278)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at android.view.View$PerformClick.run(View.java:17429)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at android.os.Handler.handleCallback(Handler.java:725)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at android.os.Looper.loop(Looper.java:137)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at android.app.ActivityThread.main(ActivityThread.java:5099)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at java.lang.reflect.Method.invokeNative(Native Method)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at java.lang.reflect.Method.invoke(Method.java:511)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
01-06 09:14:22.838: E/AndroidRuntime(27362):    at dalvik.system.NativeStart.main(Native Method)

这是我的诊断四.java:

package com.example.plearnyforparent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class DiagnosticFour extends Activity{
    ProgressDialog mProgressDialog;
    ListView listview;
    Button next;
    int a4Score, level;
    String score, score2, score3, score4, childid;

    Functions function = new Functions();
    SessionManager session;
    Address add = new Address();
    String page = add.add+"throw/editchildlevel.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diagnostic_screen);
        session = new SessionManager(getApplicationContext());
        String[] questions = getResources().getStringArray(R.array.diag_3);
                listview = (ListView) findViewById(R.id.android_qlist);
                listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, questions));
                listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        // TODO Auto-generated method stub
                        a4Score=0;
                        int len = listview.getCount();
                        SparseBooleanArray checked = listview.getCheckedItemPositions();
                        for(int i=0 ; i<len ; i++){
                            if (checked.get(i)==true)
                                a4Score++;
                        }
                    }
                });


        next = (Button)findViewById(R.id.btnNext);
        next.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi") @Override
            public void onClick(View v) {
                HashMap<String, String> child = session.getLevel();
                level= Integer.parseInt(child.get(SessionManager.CLICKED_CHILDLEVEL));
                session.saveScore(Integer.toString(a4Score), level);
                HashMap<String, String> user = session.getScores();
                score2 = user.get(SessionManager.KEY_SCORE2);
                score3 = user.get(SessionManager.KEY_SCORE3);
                score4 = user.get(SessionManager.KEY_SCORE4);
                level = function.compareScores(Integer.parseInt(score2), Integer.parseInt(score3), Integer.parseInt(score4));
                mProgressDialog = new ProgressDialog(DiagnosticFour.this);
                mProgressDialog.setMessage("Getting data");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.show();
                HashMap<String, String> childData = session.getChild();
                childid = childData.get(SessionManager.CLICKED_CHILD);
                // TODO Auto-generated method stub
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(page);
                ThreadPolicy tp = ThreadPolicy.LAX;
                StrictMode.setThreadPolicy(tp);
                String result = "";
                InputStream isr = null;
                 try {
                   List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                   nameValuePairs.add(new BasicNameValuePair("child_id", childid));
                   nameValuePairs.add(new BasicNameValuePair("child_level", String.valueOf(level)));
                   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                   HttpResponse response = httpclient.execute(httppost);
                   HttpEntity entity = response.getEntity();
                   isr = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                            sb.append(line + "n");
                    }
                    isr.close();
                    result=sb.toString();
                    int mark;
                    JSONObject json = new JSONObject(result);
                    mark = json.getInt("success");
                    mProgressDialog.dismiss();
                    if (mark == 1){
                        Toast.makeText(getBaseContext(),"Child Level: "+level,Toast.LENGTH_SHORT).show();
                        //account = new Account();
                        //account.setID(json.getString("uID"));
                        //account.setfName(json.getString("uFname"));   
                        //account.setmName(json.getString("uMname"));
                        //account.setlName(json.getString("uLname"));
                        //accountSave.add(account);
                        /*child_id = json.getString("child_id");
                        child_name = json.getString("child_name");
                        child_parent = json.get("child_parent");*/
                        /*session.createLoginSession(ID, fName, mName,lName, bday, user, pass, pic,email,contact,address);*/

                      /*Intent i = new Intent(getApplicationContext(),Children.class);
                      startActivity(i);
                      finish();*/
                    }
                    if (mark == 0){
                        Toast.makeText(getBaseContext(),"Error in Saving Data",Toast.LENGTH_SHORT).show();
                    }

                 } catch (ClientProtocolException e) {
                     // TODO Auto-generated catch block
                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                 } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                /*Intent i = new Intent(getApplicationContext(), Result.class);
                startActivity(i);*/
            }
        });
    }

}

会话管理器.java:

package com.example.plearnyforparent;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class SessionManager {
    // Shared Preferences
    SharedPreferences pref;
    // Editor for Shared preferences
    Editor editor;
    // Context
    Context _context;
    // Shared pref mode
    int PRIVATE_MODE = 0;
    // Sharedpref file name
    private static final String PREF_NAME = "PlearnyPref";
    // All Shared Preferences Keys
    private static final String IS_LOGIN = "IsLoggedIn";
    public static final String CLICKED_CHILD = "child";
    public static final String CLICKED_CHILDAGE = "child_age";
    public static final String CLICKED_CHILDLEVEL = "child_level";
    public static final String KEY_ID = "parent_id";
    public static final String KEY_NAME = "parent_name";
    public static final String KEY_USER = "parent_username";
    public static final String KEY_PASS = "parent_password";
    public static final String KEY_SCORE2 = "child_score2";
    public static final String KEY_SCORE3 = "child_score3";
    public static final String KEY_SCORE4 = "child_score4";
    public static final String KEY_SCORE = "child_score";
    // Constructor
    public SessionManager(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }
    /**
     * Create login session
     * */
    public void createLoginSession(String ID, String name, String username){
        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);
        editor.putString(KEY_ID, ID);
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_USER, username);
        // commit changes
        editor.commit();
    }
    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * Else won't do anything
     * */
    public void checkLogin(){
        // Check login status
        if(this.isLoggedIn()){
            Intent i = new Intent(_context, Children.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // Staring Login Activity
            _context.startActivity(i);
        }
    }
    public void saveScore(String score, int level){
        if (level==2)
            editor.putString(KEY_SCORE2, score);
        if (level==3)
            editor.putString(KEY_SCORE3, score);
        if (level==4)
            editor.putString(KEY_SCORE4, score);
        editor.commit();
    }
    /**
     * Get stored session data
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String, String> user = new HashMap<String, String>();
        user.put(KEY_ID, pref.getString(KEY_ID, null));
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));
        user.put(KEY_USER, pref.getString(KEY_USER, null));
        user.put(KEY_PASS, pref.getString(KEY_PASS, null));
        // return user
        return user;
    }
    public HashMap<String, String> getScores(){
        HashMap<String, String> score = new HashMap<String, String>();
        score.put(KEY_SCORE2, pref.getString(KEY_SCORE2, null));
        score.put(KEY_SCORE3, pref.getString(KEY_SCORE3, null));
        score.put(KEY_SCORE4, pref.getString(KEY_SCORE4, null));
        /*score.put(KEY_SCORE3, pref.getString(KEY_SCORE3, null));
        score.put(KEY_SCORE4, pref.getString(KEY_SCORE4, null));*/
        return score;
    }
    public HashMap<String, String> getChild(){
        HashMap<String, String> child = new HashMap<String, String>();
        child.put(CLICKED_CHILDAGE, pref.getString(CLICKED_CHILDAGE, null));
        child.put(CLICKED_CHILD, pref.getString(CLICKED_CHILD, null));
        return child;
    }
    /**
     * Clear session details
     * */
    public void logoutUser(){
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();
        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, MainActivity.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // Staring Login Activity
        _context.startActivity(i);
    }
    public void addedChild(String child_id, String child_age, int level){
        editor.putString(CLICKED_CHILD, child_id);
        editor.putString(CLICKED_CHILDAGE, child_age);
        editor.putString(CLICKED_CHILDLEVEL, String.valueOf(level));
        editor.commit();
    }
    public void changeLevel(int level){
        level ++;
        editor.putString(CLICKED_CHILDLEVEL, String.valueOf(level));
        editor.commit();
    }
    public HashMap<String, String> getLevel(){
        HashMap<String, String> child = new HashMap<String, String>();
        child.put(CLICKED_CHILDLEVEL, pref.getString(CLICKED_CHILDLEVEL, null));
        return child;
    }

    /**
     * Quick check for login
     * **/
    // Get Login State
    public boolean isLoggedIn(){
        return pref.getBoolean(IS_LOGIN, false);
    }
}

功能.java:

package com.example.plearnyforparent;
public class Functions {
    public int compareScores(int score2, int score3, int score4){
        int scores[]={score2, score3, score4};
        int level=0, maxscore= scores[0];
        for(int i =0 ; i<3; i++)
        {
            if(scores[i] > maxscore){
                   maxscore = scores[i];
                   level = i++;
            }
        }
        return level;
    }
}

compareScores函数中,您会收到int参数。但是当你调用这个函数时,你使用的是Integer。请注意,Integer可以null,但int不能。

我建议在使用它之前验证您的输入,如下所示:

if (myString != null && !myString.isEmpty()) {
    myNumber = Integer.parseInt(a);
} else {
    myNumber = 0;
}

相关内容

最新更新