2

这是我的代码

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener {

    RadioButton r1, r2;
    Button exit, submit, report,settings,about;
    EditText amount;
    double Liters = 0;
    double ppetrol;
    double pdiesel;
    double damount;
    String date, time, dbamt;
    String price_petrol;
    String price_diesel;
    DatabaseHandler db;

    // XML parsing data types

        // All static variables
        static final String URL = "http://pixelexis.host56.com/data.xml";
        // XML node keys
        static final String KEY_ITEM = "item"; // parent node(to check every nodes)
        static final String PETROL = "petrol";
        static final String DIESEL = "diesel";

        AlertDialog.Builder alert;

        TextView input1;

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

         alert = new AlertDialog.Builder(this);

         input1 = new TextView(this);


        r1 = (RadioButton)findViewById(R.id.radiopetrol);
        r2 = (RadioButton)findViewById(R.id.radiodiesel);
        exit = (Button)findViewById(R.id.exitbutton);
        submit = (Button)findViewById(R.id.submit);
        amount = (EditText)findViewById(R.id.amt);
        report = (Button)findViewById(R.id.repobutton);
        settings = (Button)findViewById(R.id.setbutton);
        about = (Button)findViewById(R.id.abtbutton);

        final DatabaseHandler db = new DatabaseHandler(this);


        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        int mHour = c.get(Calendar.HOUR_OF_DAY);
        int mMinute = c.get(Calendar.MINUTE);
        TextView t = (TextView)findViewById(R.id.time);
        TextView d = (TextView)findViewById(R.id.date);
        d.setText(" Date:" + mDay+" / "+mMonth+1 + " / "+mYear+" ");
        t.setText("Time:" + mHour+" : "+mMinute);

        date = d.getText().toString();
        time = t.getText().toString();



        // XML to HashMap

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

                XMLParser parser = new XMLParser();
                String xml = parser.getXmlFromUrl(URL); // getting XML
                Document doc = parser.getDomElement(xml); // getting DOM element

                NodeList nl = doc.getElementsByTagName(KEY_ITEM);
                // looping through all item nodes <item>
                for (int i = 0; i < nl.getLength(); i++) {
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element) nl.item(i);
                    // adding each child node to HashMap key => value
                    map.put(PETROL, parser.getValue(e, PETROL));
                    map.put(DIESEL, parser.getValue(e, DIESEL));

                    // adding HashList to ArrayList
                    menuItems.add(map);
                }

                menuItems.trimToSize();

                price_petrol = menuItems.get(0).values().toString();
                price_diesel = menuItems.get(1).values().toString();

                String regx = ",[] ";
                char[] ca = regx.toCharArray();
                for(char c1 : ca)
                {
                    price_petrol = price_petrol.replace(""+c1, "");
                    price_diesel = price_diesel.replace(""+c1, "");
                }


                System.out.println("Price of petrol = " + price_petrol);
                System.out.println("Price of diesel = " + price_diesel);

                ppetrol = Double.parseDouble(price_petrol);
                pdiesel = Double.parseDouble(price_diesel);

            //  int count = db.getValuesCount();
                /**
                 * DATABASE OPERATIONS
                 * */
                // Inserting values
                Log.d("Insert: ", "Inserting ..");
               // db.addValues(new Values(date, time, price_petrol,dbamt ));




        exit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                System.exit(0);
                // Force stopping all process and shutting down application


            }
        });

        about.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Toast.makeText(getApplicationContext(), "App by Junior Hacker...",
                        Toast.LENGTH_LONG).show();


            }
        });

settings.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {



                 alert.setTitle("Current fuel price");

                 alert.setView(input1);

                 input1.setTextColor(Color.parseColor("#FFFFFF"));

                 input1.setText("Petrol : "+price_petrol+ " Diesel : "+price_diesel);

                 alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
                 {
                  public void onClick(DialogInterface dialog, int whichButton) 
                  {

                      dialog.dismiss();
                  }
                 });
                alert.show();


            }
        });

        report.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
                startActivity(i);


            }
        });

        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                dbamt = amount.getText().toString();            

                if(amount.getText().toString() != null && ! amount.getText().toString().equalsIgnoreCase(""))
                {

                    if(r1.isChecked())
                    {
                        damount = Double.parseDouble(amount.getText().toString());
                        Liters = damount/ppetrol;
                        db.addValues(new Values(date, time, price_petrol,dbamt ));
                        Toast.makeText(getApplicationContext(), "Data Submitted Successfully",
                        Toast.LENGTH_LONG).show();
                        amount.setText("");

                        // Reading all values
                        Log.d("Reading: ", "Reading all contacts..");
                        List<Values> value = db.getAllValues();       

                        for (Values val : value) {
                            String log = "Id: "+val.getID()+" ,Date: " + val.getDate() + " ,Time: " + val.getTime() + ",Price: " + val.getPrice() + ",Amount: " + val.getAmount();
                                // Writing values to log
                        Log.d("The Log-> ", log);

                        }
                    }
                    else if(r2.isChecked())
                    {
                        damount = Double.parseDouble(amount.getText().toString());
                        Liters = damount/pdiesel;
                        Toast.makeText(getApplicationContext(), "Data Submitted Successfully",
                        Toast.LENGTH_LONG).show();
                        db.addValues(new Values(date, time, price_diesel,dbamt ));
                         // Reading all values
                        Log.d("Reading: ", "Reading all contacts..");
                        List<Values> value = db.getAllValues();       

                        for (Values val : value) {
                            String log = "Id: "+val.getID()+" ,Date: " + val.getDate() + " ,Time: " + val.getTime() + ",Price: " + val.getPrice() + ",Amount: " + val.getAmount();
                                // Writing values to log
                        Log.d("The Log-> ", log);

                        }

                    }
                    System.out.println(Liters);
                }
                else 
                {
                    Toast.makeText(getApplicationContext(), "Invalid amount!",
                    Toast.LENGTH_LONG).show();
                }

            }
        });



    }

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

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub

    }



}

对话框出现在第一次单击时,下一次单击以FatalException

这是我的日志猫

01-31 15:57:55.692: D/AndroidRuntime(272): Shutting down VM
01-31 15:57:55.692: W/dalvikvm(272): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-31 15:57:55.762: D/dalvikvm(272): GC_FOR_MALLOC freed 2922 objects / 185432 bytes in 61ms
01-31 15:57:55.772: E/AndroidRuntime(272): FATAL EXCEPTION: main
01-31 15:57:55.772: E/AndroidRuntime(272): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.view.ViewGroup.addViewInner(ViewGroup.java:1970)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.view.ViewGroup.addView(ViewGroup.java:1865)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.view.ViewGroup.addView(ViewGroup.java:1845)
01-31 15:57:55.772: E/AndroidRuntime(272):  at com.android.internal.app.AlertController.setupView(AlertController.java:364)
01-31 15:57:55.772: E/AndroidRuntime(272):  at com.android.internal.app.AlertController.installContent(AlertController.java:205)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.app.AlertDialog.onCreate(AlertDialog.java:251)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.app.Dialog.show(Dialog.java:225)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.app.AlertDialog$Builder.show(AlertDialog.java:802)
01-31 15:57:55.772: E/AndroidRuntime(272):  at com.aabasoft.fuelcalc.MainActivity$3.onClick(MainActivity.java:195)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.view.View.performClick(View.java:2408)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.view.View$PerformClick.run(View.java:8816)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.os.Handler.handleCallback(Handler.java:587)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.os.Looper.loop(Looper.java:123)
01-31 15:57:55.772: E/AndroidRuntime(272):  at android.app.ActivityThread.main(ActivityThread.java:4627)
01-31 15:57:55.772: E/AndroidRuntime(272):  at java.lang.reflect.Method.invokeNative(Native Method)
01-31 15:57:55.772: E/AndroidRuntime(272):  at java.lang.reflect.Method.invoke(Method.java:521)
01-31 15:57:55.772: E/AndroidRuntime(272):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-31 15:57:55.772: E/AndroidRuntime(272):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-31 15:57:55.772: E/AndroidRuntime(272):  at dalvik.system.NativeStart.main(Native Method)

这里有什么问题?我有其他项目也有同样的问题,我需要使用 EditTexts 接受用户的字符串,应用程序也停止了。

4

4 回答 4

2

您应该在 onClick 本身中初始化警报对话框。

 settings.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
             alert = new AlertDialog.Builder(this);
             alert.setTitle("Current fuel price");
             alert.setView(input1);
于 2013-01-31T10:27:58.133 回答
2

创建一个新类,其唯一目的是重复显示对话框,然后在必要时调用它......

这是代码

public class AlertDialogManager {

    public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        alert.setTitle("Current fuel price");
        alert.setView(input1);
        input1.setTextColor(Color.parseColor("#FFFFFF"));
        input1.setText("Petrol : "+price_petrol+ " Diesel : "+price_diesel);

        if(status != null)

        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        alertDialog.show();
    }
}
于 2013-01-31T11:24:51.783 回答
1

您必须在每次关闭它后重新初始化它。在 onClickListener 一侧初始化您的警报对话框。

于 2013-01-31T10:32:36.597 回答
1

我认为您的变量: alert 和 input1 未初始化。你能复制错误信息吗?你可以读取行号来查找错误,ok。

于 2013-01-31T10:20:14.170 回答