2013-12-16 3 views
2

Это мой LogCatОшибка: java.lang.NumberFormatException:

12-16 23:29:07.309: W/dalvikvm(3821): threadid=1: thread exiting with uncaught exception (group=0x40018578) 
12-16 23:29:07.309: E/AndroidRuntime(3821): FATAL EXCEPTION: main 
12-16 23:29:07.309: E/AndroidRuntime(3821): java.lang.NumberFormatException: 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:267) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at java.lang.Double.parseDouble(Double.java:318) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at com.pmss.FulfillRequest$2.onClick(FulfillRequest.java:111) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at android.view.View.performClick(View.java:2485) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at android.view.View$PerformClick.run(View.java:9080) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at android.os.Handler.handleCallback(Handler.java:587) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at android.os.Handler.dispatchMessage(Handler.java:92) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at android.os.Looper.loop(Looper.java:130) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at android.app.ActivityThread.main(ActivityThread.java:3687) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at java.lang.reflect.Method.invokeNative(Native Method) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at java.lang.reflect.Method.invoke(Method.java:507) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 
12-16 23:29:07.309: E/AndroidRuntime(3821):  at dalvik.system.NativeStart.main(Native Method) 

Это мой FulfillRequest.java

public class FulfillRequest extends ActionBarActivity implements OnClickListener { 


    EditText parcelidtext, quantitytext, weighttext, typetext; 
    Button parcelexistbutton, calculatepaymentbutton; 

    JSONArray parcelconfirm = null; 
    JSONArray calculate = null; 
    private ProgressDialog messageDialog; 
    JSONParser jsonParser = new JSONParser(); 

    private static final String CONFIRM_URL = "http://XXX.XXX.X.XX:1234/PMSS/trackparcel.php"; 
    private static final String CALCULATE_URL = "http://XXX.XXX.X.XX:1234/PMSS/shipmentcalculate.php"; 

    // JSON element ids from repsonse of php script: 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_MESSAGE = "message"; 
    private static final String TAG_POSTS = "posts"; 
    private static final String TAG_PARCELID = "parcelid"; 
    private static final String TAG_PARCELSTATUS = "parcelstatus"; 
    private static final String TAG_PARCELPAYMENT = "parcelpayment"; 

    private double payment = 0 ; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_fulfill_request); 
     parcelidtext = (EditText) findViewById(R.id.parcelidtext); 
     quantitytext = (EditText) findViewById(R.id.quantitytext); 
     weighttext = (EditText) findViewById(R.id.weighttext); 
     typetext = (EditText) findViewById(R.id.typetext); 
     parcelexistbutton = (Button) findViewById(R.id.parcelexistbutton); 
     calculatepaymentbutton = (Button) findViewById(R.id.calculatepaymentbutton); 

     quantitytext.setEnabled(false); 
     weighttext.setEnabled(false); 
     typetext.setEnabled(false); 

     parcelexistbutton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       String ParcelID = parcelidtext.getText().toString(); 
       new AttemptSearch(ParcelID).execute(); 
      } 
     }); 

     calculatepaymentbutton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       String ParcelIDCal = parcelidtext.getText().toString(); 
       String Quantity = quantitytext.getText().toString(); 
       String Weight = weighttext.getText().toString(); 
       String Type = typetext.getText().toString(); 

       if(ParcelIDCal == "" || Quantity == "" || Weight == "" || Type == ""){ 
        new AlertDialog.Builder(FulfillRequest.this).setTitle("Parcel Information") 
        .setMessage("Please fill in all the information first before calculate. ") 
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 

         } 
        }) 
        .show(); 
       } 

       else{ 
        double weight = Double.parseDouble(Weight); 


        if(weight > 0.45 || Type == "document"){ 
         double baseamount = 4.50; 
         payment = ((baseamount*1.25)*1.06);      
        } 
        else if(weight > 0.45 || Type == "parcel"){ 
         double baseamount = 5.00; 
         payment = ((baseamount*1.25)*1.06); 
        } 

        String Payment = Double.toString(payment); 
        new AttemptCalculate(ParcelIDCal,Quantity,Weight,Type,Payment).execute(); 
       } 
      } 
     }); 
    } 

    @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    private void setupActionBar() { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      getActionBar().setDisplayHomeAsUpEnabled(true); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.fulfill_request, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case android.R.id.home: 

      NavUtils.navigateUpFromSameTask(this); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 

    } 

    class AttemptSearch extends AsyncTask<String, String, Integer> { 

     private final String TAG = null; 
     boolean failure = false; 
     String message; 
     String ParcelID, parcelid; 
     int success; 

     public AttemptSearch(String ParcelID) { 
      this.ParcelID = ParcelID; 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      messageDialog = new ProgressDialog(FulfillRequest.this); 
      messageDialog.setMessage("Attempting checking..."); 
      messageDialog.setIndeterminate(false); 
      messageDialog.setCancelable(true); 
      messageDialog.show(); 

     } 

     protected Integer doInBackground(String... args) { 

      try { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("parcelid", ParcelID)); 

       Log.d("check!", "starting"); 
       // getting product details by making HTTP request 
       JSONObject json = jsonParser.makeHttpRequest(CONFIRM_URL, "POST", 
         params); 
       // check your log for json response 
       Log.d("Checking attempt", json.toString()); 

       // json success tag 
       success =json.getInt(TAG_SUCCESS); 
       message= json.getString(TAG_MESSAGE); 

       if(success == 1){ 
        Log.d("Retrieve Successful!", "message: " + message); 
        parcelconfirm = json.getJSONArray(TAG_POSTS); 
        JSONArray jr = parcelconfirm.getJSONArray(0); 
        JSONObject jb = jr.getJSONObject(0); 
        parcelid = jb.getString(TAG_PARCELID); 
       } 
       else if(success == 0){ 
        Log.d("Retrieve Failed!", "message: " + message); 
       } 

      } catch (JSONException e) { 
       Log.e(TAG, "JSON error", e); 
       success = Integer.valueOf(0); 
      } 
      return success; 

     } 

     protected void onPostExecute(Integer success) { 
      // dismiss the dialog once product deleted 
      messageDialog.dismiss(); 

      if (success != null && success == 1) { 
       quantitytext.setEnabled(true); 
       weighttext.setEnabled(true); 
       typetext.setEnabled(true); 
       Toast.makeText(
         FulfillRequest.this, 
         message == null ? "Please enter parcel ID (success)" 
           : message, Toast.LENGTH_LONG).show(); 
      } 
      else { 
       parcelidtext.setText(null); 
       Toast.makeText(
         FulfillRequest.this, 
         message == null ? "Please enter parcel ID (failed)" 
           : message, Toast.LENGTH_LONG).show(); 
      } 

     } 
    } 

    class AttemptCalculate extends AsyncTask<String, String, Integer> { 

     private final String TAG = null; 
     boolean failure = false; 
     String message; 
     String ParcelID, Quantity, Weight, Type, Status = "paid", Payment; 
     String parcelstatus,parcelpayment; 
     int success; 

     public AttemptCalculate(String ParcelID, String Quantity, String Weight, String Type, String Payment) { 
      this.ParcelID = ParcelID; 
      this.Quantity = Quantity; 
      this.Weight = Weight; 
      this.Type = Type; 
      this.Payment = Payment; 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      messageDialog = new ProgressDialog(FulfillRequest.this); 
      messageDialog.setMessage("Attempting calculating..."); 
      messageDialog.setIndeterminate(false); 
      messageDialog.setCancelable(true); 
      messageDialog.show(); 

     } 

     protected Integer doInBackground(String... args) { 

      try { 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("parcelid", ParcelID)); 
       params.add(new BasicNameValuePair("parcelquantity", Quantity)); 
       params.add(new BasicNameValuePair("parcelweight", Weight)); 
       params.add(new BasicNameValuePair("parceltype", Type)); 
       params.add(new BasicNameValuePair("parcelpayment", Payment)); 
       params.add(new BasicNameValuePair("parcelstatus", Status)); 

       Log.d("request!", "starting"); 
       // getting product details by making HTTP request 
       JSONObject json = jsonParser.makeHttpRequest(CALCULATE_URL, "POST", 
         params); 
       // check your log for json response 
       Log.d("Tracking attempt", json.toString()); 

       // json success tag 
       success =json.getInt(TAG_SUCCESS); 
       message= json.getString(TAG_MESSAGE); 

       if(success == 1){ 
        Log.d("Retrieve Successful!", "message: " + message); 
        calculate = json.getJSONArray(TAG_POSTS); 
        JSONArray jr = calculate.getJSONArray(0); 
        JSONObject jb = jr.getJSONObject(0); 
        parcelpayment = jb.getString(TAG_PARCELPAYMENT); 
        parcelstatus = jb.getString(TAG_PARCELSTATUS); 
       } 
       else if(success == 0){ 
        Log.d("Retrieve Failed!", "message: " + message); 
       } 

      } catch (JSONException e) { 
       Log.e(TAG, "JSON error", e); 
       success = Integer.valueOf(0); 
      } 
      return success; 

     } 

     protected void onPostExecute(Integer success) { 
      // dismiss the dialog once product deleted 
      messageDialog.dismiss(); 
      if (success != null && success == 1) {    
        new AlertDialog.Builder(FulfillRequest.this).setTitle("Parcel Information") 
        .setMessage(" Your Parcel Status is " + parcelstatus + ". Your Payment Amount is RM" + parcelpayment + ". ") 
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
          parcelidtext.setText(null); 
          quantitytext.setText(null); 
          quantitytext.setEnabled(false);       
          weighttext.setText(null); 
          weighttext.setEnabled(false); 
          typetext.setText(null);              
          typetext.setEnabled(false); 
         } 
        }) 
        .show(); 
       Toast.makeText(
         FulfillRequest.this, 
         message == null ? "Please enter parcel ID (success)" 
           : message, Toast.LENGTH_LONG).show(); 
      } else { 
       Toast.makeText(
         FulfillRequest.this, 
         message == null ? "Please enter parcel ID (failed)" 
           : message, Toast.LENGTH_LONG).show(); 
      } 

     } 
    } 
} 

Почему это сообщение об ошибке происходит со мной? Что мне делать? Я думаю, что это возможно из-за моей двойной переменной веса.

линии 111 в этом методе calculatepaymentbutton.setOnClickListener(new View.OnClickListener()

Интересно, есть ли способ устранить эту проблему double weight = Double.parseDouble(Weight);? Причина того, что я хочу сделать, это то, что когда я нажимаю кнопку calcpayment, я хочу, чтобы моя система проверила, что все заполнено или нет, но когда я нажимаю на эту ошибку, происходит ошибка logcat ~

+3

критическая ошибка: 'Тип ==" document "' –

+0

Таким образом, система не может интерпретировать любое значение в Вес как двойное. Это произойдет, если это значение, например, «sup dog» или «Мне нравится пицца». Самый простой подход - уловить NumberFormatException и обработать его, так как вы допустили бы недопустимый ввод. – Taylor

+0

Тип ввода для 'EditText weighttext' - _numberDecimal_ –

ответ

1

Эти сравнения являются частью проблемы:

if (ParcelIDCal == "" || Quantity == "" || Weight == "" || Type == "") 

Они должны быть:

if (ParcelIDCal == null || ParcelIDCal.trim().equals("") || 
    Quantity == null || Quantity.trim().equals("") || 
    Weight == null || Weight.trim().equals("") || 
    Type == null || Type.trim().equals("")) 

И все части, где вы сравниваете строки, как это неправильны:

Type == "document" 

Это не, как вы сравните String с для равенства в Java , вы must использование:

Type.equals("document") 

Или еще лучше, чтобы принять во внимание возможность того, что переменная null это лучше сделать это:

"document".equals(Type) 

И кстати - переменные и атрибуты в Java должны начинаться с буквы в нижнем регистре, это соглашение ,

+0

'ParcelIDCal.trim(). Equals (" ")' .trim() означает? –

+0

@Jiazzyuser это для удаления всех пробелов вокруг строки.Строка с пробелами должна считаться пустой, тоже –

+0

Так что, если я ошибочно нажимаю пробел в редакторе, то он принял пустой текст? –

0

Если вы хотите, чтобы в лагере Strings использовались :

"".equals(ParcelIDCal) 

или даже лучше, чтобы проверить, если строка пуста или пустым:

StringUtils.isNotBlank(ParcelIDCal) 
+0

'StringUtils' нужно что-то объявить? Я спросил об этом, потому что он сказал, что 'StringUtils не может быть разрешен' –

+0

Да. вам нужно импортировать его: 'import org.apache.commons.lang.StringUtils;' – BobTheBuilder

+0

Когда я импортирую библиотеку, он сказал: «Импорт org.apache.commons.lang не может быть разрешен» –

Смежные вопросы