android.widget.TextView无法强制转换为android.widget.EditText

时间:2014-05-14 16:53:35

标签: android classcastexception

这是FulfillRequest.java

public class FulfillRequest extends ActionBarActivity implements
    OnClickListener, OnItemSelectedListener {

EditText parcelidtext, quantitytext, weighttext;
Button parcelexistbutton, calculatepaymentbutton;
Spinner typeSpinnerFulfillRequest;

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

 private static final String CONFIRM_URL = "http://xxx.xxx.xxx.x/PMSS/trackparcel.php";
 private static final String CALCULATE_URL = "http://xxx.xxx.xxx.x/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 static final String TAG_PARCELQUANTITY = "parcelquantity";
private static final String TAG_PARCELWEIGHT = "parcelweight";
private static final String TAG_PARCELTYPE = "parceltype";

private double payment = 0;
public String status;

private String ParcelIDCal;
private String Quantity;
private String Weight;
private String Payment;
private String Type;


@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);
    typeSpinnerFulfillRequest = (Spinner) findViewById(R.id.typeSpinnerFulfillRequest);
    parcelexistbutton = (Button) findViewById(R.id.parcelexistbutton);
    calculatepaymentbutton = (Button) findViewById(R.id.calculatepaymentbutton);

    // Create an ArrayAdapter using the string array and a default spinner
            // layout
            ArrayAdapter<CharSequence> adapter = ArrayAdapter
                    .createFromResource(this, R.array.state_array,
                            android.R.layout.simple_spinner_item);
            // Specify the layout to use when the list of choices appears
            adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
            // Apply the adapter to the spinner
            typeSpinnerFulfillRequest.setAdapter(adapter);
            typeSpinnerFulfillRequest.setOnItemSelectedListener(FulfillRequest.this);

    quantitytext.setEnabled(false);
    weighttext.setEnabled(false);
    //typeSpinnerFulfillRequest.setVisibility(View.GONE);
    typeSpinnerFulfillRequest.setVisibility(100);



    parcelexistbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            quantitytext.setText(null);
            weighttext.setText(null);
            quantitytext.setEnabled(false);
            weighttext.setEnabled(false);
            typeSpinnerFulfillRequest.setVisibility(0);
            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
            ParcelIDCal = parcelidtext.getText().toString();
            Quantity = quantitytext.getText().toString();
            Weight = weighttext.getText().toString();



            /*if (ParcelIDCal == null || ParcelIDCal.trim().equals("")
                    || Quantity == null || Quantity.trim().equals("")
                    || Weight == null || Weight.trim().equals("")
                    || Type == null || Type.trim().equals("")) {
                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 if( status.equals("paid") || status.equals("fulfilled")){

                new AlertDialog.Builder(FulfillRequest.this)
                .setTitle("Parcel Information")
                .setMessage(
                        " The parcel status is either fulfilled or paid!")
                .setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int which) {
                            }
                        }).show();
            }

            else if("document".equals(Type) || "parcel".equals(Type)){

                {
                    double weight = Double.parseDouble(Weight);

                    if (weight > 0 && weight < 0.50 && "document".equals(Type)) {
                        double baseamount = 4.50;
                        payment = ((baseamount * 1.25) * 1.06) + 5;
                    }

                    else if (weight > 0.50 && "document".equals(Type)) {
                        double baseamount = 5.50;
                        payment = ((baseamount * 1.25) * 1.06) + 5;
                    }

                    else if (weight > 0 && weight < 2.0 && "parcel".equals(Type)) {
                        double baseamount = 16.00;
                        payment = ((baseamount * 1.25) * 1.06) + 5;
                    }

                    else if (weight > 2.0 && "parcel".equals(Type)) {
                        double baseamount = 18.00;
                        payment = ((baseamount * 1.25) * 1.06) + 5;
                    }

                    else if (weight < 0){
                        new AlertDialog.Builder(FulfillRequest.this)
                        .setTitle("Parcel Information")
                        .setMessage(
                                " The weight value only valid in positive number. ")
                        .setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int which) {
                                    }
                                }).show();
                    }

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

            else{
                new AlertDialog.Builder(FulfillRequest.this)
                .setTitle("Parcel Information")
                .setMessage(
                        " The information key-in is incorrect. ")
                .setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int which) {
                            }
                        }).show();
            }*/
        }
    });
}

@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 onItemSelected(AdapterView<?> parent, View view, int position,
        long id) {
    // TODO Auto-generated method stub
    Type = (String) typeSpinnerFulfillRequest.getItemAtPosition(position);
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
    // TODO Auto-generated method stub

}

@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, parcelquantity, parcelweight, parceltype ,parcelstatus;
    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);
                parcelquantity = jb.getString(TAG_PARCELQUANTITY);
                parcelweight = jb.getString(TAG_PARCELWEIGHT);
                parceltype = jb.getString(TAG_PARCELTYPE);
                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

        if (success != null && success == 1) {

            if("fulfilled".equals(parcelstatus)){
                quantitytext.setText(parcelquantity);
                weighttext.setText(parcelweight);
                if(parceltype.equals("document")){
                    typeSpinnerFulfillRequest.setSelection(0);
                    typeSpinnerFulfillRequest.getEmptyView();
                }
                else if(parceltype.equals("parcel")){
                    typeSpinnerFulfillRequest.setSelection(1);
                    typeSpinnerFulfillRequest.getEmptyView();
                }
            }
            else if("paid".equals(parcelstatus)){
                quantitytext.setText(parcelquantity);
                weighttext.setText(parcelweight);
                if(parceltype.equals("document")){
                    typeSpinnerFulfillRequest.setSelection(0);
                }
                else if(parceltype.equals("parcel")){
                    typeSpinnerFulfillRequest.setSelection(1);
                }

            }
            else if("requested".equals(parcelstatus)){
                quantitytext.setEnabled(true);
                weighttext.setEnabled(true);
                typeSpinnerFulfillRequest.setSelection(0);
            }

            status = parcelstatus;
            Toast.makeText(
                    FulfillRequest.this,
                    message == null ? "Please enter parcel ID  (success)"
                            : message, Toast.LENGTH_LONG).show();

            messageDialog.dismiss();

        } 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 = "fulfilled", Payment;
    private 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);
                                    typeSpinnerFulfillRequest.getEmptyView();
                                }
                            }).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();
        }

    }
}

我的logcat

05-15 00:39:38.728: E/AndroidRuntime(21078): FATAL EXCEPTION: main
05-15 00:39:38.728: E/AndroidRuntime(21078): Process: com.pmss, PID: 21078
05-15 00:39:38.728: E/AndroidRuntime(21078): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pmss/com.pmss.FulfillRequest}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.os.Looper.loop(Looper.java:136)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.ActivityThread.main(ActivityThread.java:5017)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at java.lang.reflect.Method.invokeNative(Native Method)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at java.lang.reflect.Method.invoke(Method.java:515)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at dalvik.system.NativeStart.main(Native Method)
05-15 00:39:38.728: E/AndroidRuntime(21078): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
05-15 00:39:38.728: E/AndroidRuntime(21078):    at com.pmss.FulfillRequest.onCreate(FulfillRequest.java:81)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.Activity.performCreate(Activity.java:5231)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-15 00:39:38.728: E/AndroidRuntime(21078):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-15 00:39:38.728: E/AndroidRuntime(21078):    ... 11 more

第81行是parcelidtext = (EditText) findViewById(R.id.parcelidtext);

这是我的activity_fulfill_request.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FulfillRequest" xmlns:android="http://schemas.android.com/apk/res/android">

<RelativeLayout
    android:id="@+id/RelativeLayout01"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/app_name"
    android:src="@drawable/pos_wing" />

    <TextView
        android:id="@+id/filldescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_marginTop="-10dp"
        android:layout_centerHorizontal="true"
        android:text="@string/filldescription"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/quantity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/parcelexistbutton"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="25dp"
        android:text="@string/quantity"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/weight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/quantitytext"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="26dp"
        android:text="@string/weight"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/weight"
        android:layout_below="@+id/weighttext"
        android:layout_marginTop="32dp"
        android:text="@string/type"
        android:textSize="20sp" />

    <Button
        android:id="@+id/calculatepaymentbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/typeSpinnerFulfillRequest"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp"
        android:text="@string/calculatepayment" />

    <TextView
        android:id="@+id/parcelid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/parcelidtext"
        android:layout_alignBottom="@+id/parcelidtext"
        android:layout_marginLeft="45dp"
        android:text="@string/parcelid"
        android:textSize="20sp" />

    <Button
        android:id="@+id/parcelexistbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/parcelidtext"
        android:layout_marginTop="17dp"
        android:layout_toRightOf="@+id/parcelid"
        android:text="@string/searchparcelexist" />

    <EditText
        android:id="@+id/parcelidtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/parcelexistbutton"
        android:layout_below="@+id/filldescription"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="29dp"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/quantitytext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/quantity"
        android:layout_alignBottom="@+id/quantity"
        android:layout_alignLeft="@+id/parcelidtext"
        android:ems="10"
        android:inputType="number" />

    <EditText
        android:id="@+id/weighttext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/weight"
        android:layout_alignBottom="@+id/weight"
        android:layout_alignLeft="@+id/quantitytext"
        android:ems="10"
        android:inputType="numberDecimal" />

    <Spinner
        android:id="@+id/typeSpinnerFulfillRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/weighttext"
        android:layout_alignRight="@+id/weighttext"
        android:layout_alignTop="@+id/type" />

</RelativeLayout>

我想知道问题是什么。我没有将TextView转换为EditText,因为我的parcelidtext已经是EditText。任何人都可以帮助我。

0 个答案:

没有答案