2017-08-08 186 views
-2

我正在开发一个应用程序,在这里,我想保存用户的个人详细信息按钮点击,但是当我点击提交按钮时,它显示错误,即由java.lang.ArrayIndexOutOfBoundsException引起:长度= 18;指数= 18。我该如何解决这个问题?请建议我。以下是我的代码,我该如何解决这个问题?如何解决导致:java.lang.ArrayIndexOutOfBoundsException:length = 18;索引= 18在Android?

//代码

public class MyPersonalDetailsActivity1 extends AppCompatActivity { 

     RadioGroup rgGender, rgDopinion, rgYca, rgPye; 
     Button btnSave, btnBdate; 
     EditText edFname, edLname, edEmail, edPass, edAddress, edCountry, edState, edBdate, edCity, edMob, edHeight, edWeight, edQualification, edOccupation; 
     RadioButton rbYes, rbNo, rbFit, rbUnfit, rbYesa, rbNota, rbMale, rbFemale; 
     RadioButton rbGender, rbPye, rbDopinion, rbYca; 
     Toolbar toolbar; 
     TextView user_id, responsetypes; 
     Calendar myCalendar; 

     private boolean isLoggedIn = false; 
     SessionManagement session; 

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

      toolbar = (Toolbar) findViewById(R.id.toolbar); 
      setSupportActionBar(toolbar); 

      TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); 
      setSupportActionBar(toolbar); 
      getSupportActionBar().setDisplayShowTitleEnabled(false); 
      toolbarTitle.setText("My Personal Details"); 
      toolbar.setTitleMarginBottom(50); 

      getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
      getSupportActionBar().setHomeButtonEnabled(true); 

      user_id=(TextView)findViewById(R.id.user_id); 
      edFname= (EditText)findViewById(R.id.ed_fname); 
      edEmail= (EditText)findViewById(R.id.ed_email); 
      edPass= (EditText)findViewById(R.id.ed_passowrd); 
      edMob= (EditText)findViewById(R.id.ed_mobile); 
      edBdate= (EditText)findViewById(R.id.ed_dob); 
      edAddress= (EditText)findViewById(R.id.ed_address); 
      edCountry= (EditText)findViewById(R.id.ed_country); 
      edState= (EditText)findViewById(R.id.ed_state); 
      edCity= (EditText)findViewById(R.id.ed_city); 
      edHeight= (EditText)findViewById(R.id.ed_height); 
      edWeight= (EditText)findViewById(R.id.ed_weight); 
      edQualification= (EditText)findViewById(R.id.ed_qaulification); 
      edOccupation= (EditText)findViewById(R.id.ed_occupation); 

      rgGender= (RadioGroup)findViewById(R.id.rg_gender); 
      rgDopinion= (RadioGroup)findViewById(R.id.rg_drop); 
      rgPye= (RadioGroup)findViewById(R.id.rg_pye); 
      rgYca= (RadioGroup)findViewById(R.id.rg_yca); 

      SharedPreferences sharedPreferences = getSharedPreferences(SessionManagement.PREF_NAME, Context.MODE_PRIVATE); 
      isLoggedIn = sharedPreferences.getBoolean(SessionManagement.IS_LOGIN, false); 
      String email = sharedPreferences.getString(SessionManagement.KEY_EMAIL, "Not Available"); 
      user_id.setText(email); 

      myCalendar = Calendar.getInstance(); 
      final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { 
       @Override 
       public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 
        // TODO Auto-generated method stub 
        myCalendar.set(Calendar.YEAR, year); 
        myCalendar.set(Calendar.MONTH, monthOfYear); 
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); 
        updateLabel(); 
       } 
      }; 
      edBdate.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 
        new DatePickerDialog(MyPersonalDetailsActivity1.this, date, myCalendar 
          .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show(); 
       } 
      }); 

      //btnBdate=(Button)findViewById(R.id.btn_bdate); 
      btnSave=(Button)findViewById(R.id.btn_save); 

      btnSave.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 

        if (v.getId() == R.id.btn_save) { 

         if (checkValidation()) { 

          int selectedIdGender = rgGender.getCheckedRadioButtonId(); 
          rbGender = (RadioButton) findViewById(selectedIdGender); 

          int selectedIdYca = rgYca.getCheckedRadioButtonId(); 
          rbYca = (RadioButton) findViewById(selectedIdYca); 

          int selectedIdPye = rgPye.getCheckedRadioButtonId(); 
          rbPye = (RadioButton) findViewById(selectedIdPye); 

          int selectedIdDrop = rgDopinion.getCheckedRadioButtonId(); 
          rbDopinion = (RadioButton) findViewById(selectedIdDrop); 

          String firstname1 = edFname.getText().toString(); 
          String lastname = null; 
          String emailid = edEmail.getText().toString(); 
          String password = edPass.getText().toString(); 
          String address1 = edAddress.getText().toString(); 
          String country = edCountry.getText().toString(); 
          String state = edState.getText().toString(); 
          String city = edCity.getText().toString(); 
          String contactno = edMob.getText().toString(); 
          String sex = rbGender.getText().toString(); 
          String height = edHeight.getText().toString(); 
          String weight = edWeight.getText().toString(); 
          String qualification1 = edQualification.getText().toString(); 
          String occupation1 = edOccupation.getText().toString(); 
          String pye = rbPye.getText().toString(); 
          String dopinion = rbDopinion.getText().toString(); 
          String attendcourse = rbYca.getText().toString(); 
          String birthdate = edBdate.getText().toString(); 
          int userID = 12973; 
          String zipcode = null; 

          try { 
           String firstname = URLEncoder.encode(firstname1, "utf-8"); 
           String address = URLEncoder.encode(address1, "utf-8"); 
           String qualification = URLEncoder.encode(qualification1, "utf-8"); 
           String occupation = URLEncoder.encode(occupation1, "utf-8"); 

           System.out.println("Givennames is :" + firstname + " Given password is :" + password + "Gender:" + sex); 

           connectWithHttpGet(firstname, lastname, emailid, password, birthdate, zipcode, 
             sex, address, country, state, city, contactno, 
             height, weight, qualification, occupation, pye, 
             dopinion, attendcourse, userID); 

           if (isLoggedIn) { 
            //We will start the Profile Activity 
            Intent intent = new Intent(MyPersonalDetailsActivity1.this, MenuActivity.class); 
            startActivity(intent); 
           } 

          } catch (UnsupportedEncodingException e) { 
           e.printStackTrace(); 
          } 
         } else { 
          // Toast.makeText(MyPersonalDetailsActivity.this, "Please Fill the fields", Toast.LENGTH_LONG).show(); 
         } 
        } 

       } 
      }); 
     } 


     private void connectWithHttpGet(String firstname, String lastname, String emailid, String password, String birthdate,String zipcode, 
             String sex, String address, String country, String state, String city, String contactno, 
             String height, String weight, String qualification, String occupation, String pye, 
             String dopinion, String attendcourse, int userID) { 

      class HttpGetAsyncTask extends AsyncTask<String, Void, String> { 

       @Override 
       protected String doInBackground(String... params) { 

        // As you can see, doInBackground has taken an Array of Strings as the argument 
        //We need to specifically get the givenUsername and givenPassword 

        String paramFname = params[0]; 
        String paramLname = params[1]; 
        String paramEmail = params[2]; 
        String paramPassword = params[3]; 
        String paramAddress = params[4]; 
        String paramCountry = params[5]; 
        String paramBirthdate = params[6]; 
        String paramZip = params[7]; 
        String paramState = params[8]; 
        String paramCity = params[9]; 
        String paramPhone = params[10]; 
        String paramSex = params[11]; 
        String paramHeight = params[12]; 
        String paramWeight = params[13]; 
        String paramQualifn = params[14]; 
        String paramDopenion = params[15]; 
        String paramPye = params[16]; 
        String paramOccupatn = params[17]; 
        String paramYca = params[18]; 
        String paramUserid = params[19]; //HERE GIVES AN ERROR 


        System.out.println("userID" + paramFname + " email is :" + paramEmail+" gender is :" + paramSex); 

        // Create an intermediate to connect with the Internet 
        HttpClient httpClient = new DefaultHttpClient(); 

        // Sending a GET request to the web page that we want 
        // Because of we are sending a GET request, we have to pass the values through the URL 
        HttpGet httpGet = new HttpGet("http://www.example.com/ypAndroid/api/SavePersonalDetails?firstname="+paramFname+"&lastname="+null+ 
          "&emailid="+paramEmail+"&password="+paramPassword+ 
          "&address1="+paramAddress+"&Country="+paramCountry+"&birthdate="+paramBirthdate+"&zipcode="+null+"&state="+paramState+ 
          "&city="+paramCity+"&phonenumber="+paramPhone+"&sex="+paramSex+"&heightincms="+paramHeight+"&weightinkgs="+paramWeight+ 
          "&qualification="+paramQualifn+"&doctorsopinion="+paramDopenion+"&PreviousYogaExperience="+paramPye+"&business="+paramOccupatn+ 
          "&attendcourse="+paramYca+"&userid="+12973); 

        try { 
         // execute(); executes a request using the default context. 
         // Then we assign the execution result to HttpResponse 
         HttpResponse httpResponse = httpClient.execute(httpGet); 
         System.out.println("httpResponse// getEntity() ; obtains the message entity of this response"); 
         // getContent() ; creates a new InputStream object of the entity. 
         // Now we need a readable source to read the byte stream that comes as the httpResponse 
         InputStream inputStream = httpResponse.getEntity().getContent(); 

         // We have a byte stream. Next step is to convert it to a Character stream 
         InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 

         // Then we have to wraps the existing reader (InputStreamReader) and buffer the input 
         BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 

         // InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed. 
         //The buffer size is 8K 
         //Therefore we need a mechanism to append the separately coming chunks in to one String element 
         // We have to use a class that can handle modifiable sequence of characters for use in creating String 
         StringBuilder stringBuilder = new StringBuilder(); 

         String bufferedStrChunk = null; 

         // There may be so many buffered chunks. We have to go through each and every chunk of characters 
         //and assign a each chunk to bufferedStrChunk String variable 
         //and append that value one by one to the stringBuilder 
         while((bufferedStrChunk = bufferedReader.readLine()) != null){ 
          stringBuilder.append(bufferedStrChunk); 
         } 

         // Now we have the whole response as a String value. 
         //We return that value then the onPostExecute() can handle the content 
         System.out.println("Returninge of doInBackground :" + stringBuilder.toString()); 

         // If the Username and Password match, it will return "working" as response 
         // If the Username or Password wrong, it will return "invalid" as response 
         return stringBuilder.toString(); 

        } catch (ClientProtocolException cpe) { 
         System.out.println("Exceptionrates caz of httpResponse :" + cpe); 
         cpe.printStackTrace(); 
        } catch (IOException ioe) { 
         System.out.println("Secondption generates caz of httpResponse :" + ioe); 
         ioe.printStackTrace(); 
        } 

        return null; 
       } 

       @Override 
       protected void onPostExecute(String result) { 
        super.onPostExecute(result); 
        System.out.println("httpResponse :" + result); 

        try { 
         JSONObject jsonObject = new JSONObject(result); 
         JSONArray login = jsonObject.getJSONArray("savepersonaldetails"); 
         JSONObject jsonObject1 = login.getJSONObject(0); 
         // edited second, you response was responsetype, but I parsed was responsetypes,so you can have a look. 
         String responsetypes = jsonObject1.optString("responsetype"); 
         String message = jsonObject1.getString("message"); 

         if (TextUtils.equals(responsetypes, "success")) { 
          Toast.makeText(getApplicationContext(), message , Toast.LENGTH_LONG).show(); 
         } else if (TextUtils.equals(responsetypes, "failure")) { 
          Toast.makeText(getApplicationContext(), message , Toast.LENGTH_LONG).show(); 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 

      // Initialize the AsyncTask class 
      HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask(); 
    // Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask 
    // We are passing the connectWithHttpGet() method arguments to that 
      httpGetAsyncTask.execute(firstname,lastname,emailid,password,birthdate,zipcode,sex,address,country,city,contactno, 
        height,weight,qualification,occupation,pye,dopinion,attendcourse, String.valueOf(userID)); 
     } 

     @Override 
     public boolean onOptionsItemSelected(MenuItem item) { 
      switch (item.getItemId()) { 
       // action with ID action_refresh was selected 
       case android.R.id.home: 
        Intent i8= new Intent(this, MenuActivity.class); 
        i8.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); 
        startActivity(i8); 
        finish(); 
        return true; 
       default: 
        break; 
      } 

      return true; 
     } 

     private boolean checkValidation() { 
      boolean ret = true; 

      if (!Validation.hasText(edFname)) ret = false; 
      if (!Validation.hasText(edPass)) ret = false; 
      if (!Validation.isEmailAddress(edEmail, true)) ret = false; 
      if (!Validation.isBirthDate(edBdate, true)) ret = false; 
      if (!Validation.hasText(edAddress)) ret = false; 
      if (!Validation.hasText(edCountry)) ret = false; 
      if (!Validation.hasText(edState)) ret = false; 
      if (!Validation.hasText(edCity)) ret = false; 
      if (!Validation.isPhoneNumber(edMob, true)) ret = false; 
      if (!Validation.hasText(edHeight)) ret = false; 
      if (!Validation.hasText(edWeight)) ret = false; 
      if (!Validation.hasText(edQualification)) ret = false; 
      if (!Validation.hasText(edOccupation)) ret = false; 

      return ret; 
     } 

     private void updateLabel() { 
      String myFormat = "yyyy/MM/dd"; //In which you need put here 
      SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US); 
      edBdate.setText(sdf.format(myCalendar.getTime())); 
     } 
    } 

回答

1

,而你正在试图获得19参数String paramUserid = params[19];httpGetAsyncTask.execute电话只传递18个参数。因此错误。检查你的执行呼叫,并通过更多的参数。

PS:这不是一个传递数据的理想方法。没有方法调用应该有19个参数。创建一个包含这19个字段的User类型的模型类,然后在该模型类中设置值,然后传递它。