2

在我简单地创建了一个新的模拟器以在 Google 地图 API 上运行之后,以前工作的代码上出现了非常令人沮丧的错误。

代码背景:

当用户点击按钮时,我的代码会检查设备以查看我当前是否激活了 GPS。如果不是,则提示用户进入设置页面。如果是,则将它们的 Lat ang Long 值发送到 AsyncTask。

从我可以看到我的 GPS 正在返回一个值(无论是真还是假),但我收到以下错误:

03-12 21:33:18.317: E/AndroidRuntime(364): java.lang.RuntimeException: Unable to stop activity {com.example.flybaseapp/com.example.flybaseapp.ShoppingList}: java.lang.NullPointerException

通行证:

package com.example.flybaseapp;



import android.R.string;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;


public class PassLatLong extends Activity{

double latt;
double longg;
String conLatt = "";
String conLongg = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras(); 
    if (extras != null) {
        latt = extras.getDouble("passedLat"); 
        longg = extras.getDouble("passedLong"); 
    }

    conLatt = Double.toString(latt);
    conLongg = Double.toString(longg);
    GoogleAsync task = new GoogleAsync(this);
    task.execute(conLatt, conLongg);


    }

 }

ShoppingList.Java 调用意图对象来启动 CheckGPS 类:

package com.example.flybaseapp;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class ShoppingList extends ListActivity implements OnClickListener {

    Button AddItem;
    Button showShop;
    ListView showItems;
    SimpleCursorAdapter cursorAdapter;
    Long itemId;
    EditText totalPrice;
    String itemDescription;
    int itemAmount;
    int itemPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.shoppinglistlayout);

        AddItem = (Button) findViewById(R.id.btnAddItem);
        showShop = (Button) findViewById(R.id.btnSearchShops);

        showItems = (ListView) findViewById(android.R.id.list);

        totalPrice = (EditText) findViewById(R.id.totalListPrice);

        AddItem.setOnClickListener(this);
        showShop.setOnClickListener(this);

        setList();

        int setPrice = updateTotal();
        totalPrice.setText(Integer.toString(setPrice));

    }

    @Override
    public void onClick(View clickedAdd) {

        switch (clickedAdd.getId()) {

        case (R.id.btnAddItem):

            show();

            break;

        case (R.id.btnSearchShops):

            Intent checkGPS = new Intent("com.example.flybaseapp.CheckGPS");
            startActivity(checkGPS);

            break;

        }

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long idd) {
        super.onListItemClick(l, v, position, idd);

        itemId = idd;

        final CharSequence[] items = { "Edit Item", "Delete Item",
                "Show Most Purchased Item" };

        Builder alertDialogBuilder = new AlertDialog.Builder(ShoppingList.this);

        alertDialogBuilder.setTitle("Item Options:");

        alertDialogBuilder.setItems(items,
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int item) {

                        if (items[item].equals("Edit Item")) {

                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                    ShoppingList.this);

                            builder.setTitle("Edit Item");

                            DBHandlerShop setEdit = new DBHandlerShop(
                                    ShoppingList.this, null, null);

                            setEdit.open();
                            String itemName = setEdit.getItem(itemId);
                            int itemAmount = setEdit.getItemQuan(itemId);
                            int itemPrice = setEdit.getItemCost(itemId);
                            setEdit.close();
                            LinearLayout layout = new LinearLayout(
                                    ShoppingList.this);
                            layout.setOrientation(LinearLayout.VERTICAL);

                            final EditText titleBox = new EditText(
                                    ShoppingList.this);
                            titleBox.setText(itemName);
                            titleBox.setHint("Item Name:");
                            layout.addView(titleBox);

                            final EditText quantityBox = new EditText(
                                    ShoppingList.this);
                            quantityBox.setText(Integer.toString(itemAmount));
                            quantityBox.setHint("Item Quantity");
                            layout.addView(quantityBox);

                            final EditText priceBox = new EditText(
                                    ShoppingList.this);
                            priceBox.setText(Integer.toString(itemPrice));
                            priceBox.setHint("Item Price.");
                            layout.addView(priceBox);

                            builder.setView(layout);

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

                                            Editable valueItem = titleBox
                                                    .getText();
                                            Editable valueAmount = quantityBox
                                                    .getText();
                                            Editable valuePrice = priceBox
                                                    .getText();

                                            String itemDescription = valueItem
                                                    .toString();
                                            String s = valueAmount.toString();
                                            int itemAmount = Integer
                                                    .parseInt(s);
                                                String a = valuePrice.toString();
                                            int itemPrice = Integer.parseInt(a);

                                            try {
                                                DBHandlerShop update = new DBHandlerShop(
                                                        ShoppingList.this,
                                                        null, null);
                                                update.open();
                                                update.updateItem(itemId,
                                                        itemDescription,
                                                        itemAmount, itemPrice);
                                                update.close();
                                            } catch (Exception e) {
                                                Dialog e1 = new Dialog(
                                                        ShoppingList.this);
                                                e1.setTitle("Item unsuccesfully updated");
                                                TextView txt = new TextView(
                                                        ShoppingList.this);
                                                txt.setText("Success");
                                                e1.setContentView(txt);
                                                e1.show();
                                            }    finally {
                                                Dialog e1 = new Dialog(
                                                        ShoppingList.this);
                                                e1.setTitle("Item succesfully updated");
                                                TextView txt = new TextView(
                                                        ShoppingList.this);
                                                txt.setText("Success");
                                                e1.setContentView(txt);
                                                e1.show();

                                                setList();

                                                int cost = updateTotal();
                                                totalPrice.setText(Integer
                                                        .toString(cost));
                                            }

                                        }

                                    });

                            builder.setNegativeButton("Cancel",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog,
                                                int whichButton) {

                                        }
                                    });

                            builder.show();

                        }

                        else if (items[item].equals("Delete Item")) {

                            DBHandlerShop delete = new DBHandlerShop(
                                    ShoppingList.this, null, null);

                            delete.open();
                            delete.deleteItem(itemId);
                            delete.close();

                            DBHandlerShop findPrice = new DBHandlerShop(
                                    ShoppingList.this, null, null);

                            findPrice.open();
                            int returnedCost = findPrice.getItemCost(itemId);

                            int cost = updateTotal();

                            int newTotal = cost - returnedCost;
                            totalPrice.setText(Integer.toString(newTotal));

                            setList();

                        }

                        else if (items[item].equals("Show Most Purchased Item")) {

                            Dialog e1 = new Dialog(ShoppingList.this);
                            e1.setTitle("Item unsuccesfully updated");
                            TextView txt = new  TextView(ShoppingList.this);
                            txt.setText("Success");
                            e1.setContentView(txt);
                            e1.show();

                        }

                    }

                });

        alertDialogBuilder.show();

    }

    private void setList() {

        DBHandlerShop DBShop = new DBHandlerShop(this, null, null);

        DBHandlerShop searchItems = new DBHandlerShop(this, null, null);

        searchItems.open();

        Cursor cursor = searchItems.getItems();

        startManagingCursor(cursor);

        String[] from = new String[] { DBShop.KEY_ITEMSHOP, DBShop.KEY_ITEMNUM,
                DBShop.KEY_ITEMPRICE };
        int[] to = new int[] { R.id.txtSetItem, R.id.txtSetAmount,
                R.id.txtSetPrice };

        cursorAdapter = new SimpleCursorAdapter(this, R.layout.setshoppinglist,
                cursor, from, to);
        showItems.setAdapter(cursorAdapter);

    }

    private int updateTotal() {

        DBHandlerShop total = new DBHandlerShop(this, null, null);

        int totalPrice = 0;
        total.open();
        Cursor totalPrices = total.getTotals();
        total.close();

        if (totalPrices != null) {

            startManagingCursor(totalPrices);
            if (totalPrices.moveToFirst()) {

                do {
                    int cost = totalPrices.getInt(3);
                    totalPrice += cost;

                } while (totalPrices.moveToNext());

                return totalPrice;
            }

        }

        else {

            return totalPrice;

        }

        return 0;

    }

    private void show() {

        AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingList.this);

        builder.setTitle("Enter Item Details:");

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        final EditText titleBox = new EditText(this);

        titleBox.setHint("Item Name:");
        layout.addView(titleBox);

        final EditText quantityBox = new EditText(this);

        quantityBox.setHint("Item Quantity");
        layout.addView(quantityBox);

        final EditText priceBox = new EditText(this);

        priceBox.setHint("Item Price.");
        layout.addView(priceBox);

        builder.setView(layout);

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

                    Editable valueItem = titleBox.getText();
                    Editable valueAmount = quantityBox.getText();
                    Editable valuePrice = priceBox.getText();

                    itemDescription = valueItem.toString();
                    String s = valueAmount.toString();
                    itemAmount = Integer.parseInt(s);
                    String a = valuePrice.toString();
                    itemPrice = Integer.parseInt(a);

                    int totalCombined = itemAmount * itemPrice;

                    DBHandlerShop addItem = new DBHandlerShop(
                            ShoppingList.this, null, null);
                    addItem.open();
                    addItem.insertItems(itemDescription, itemAmount,
                            totalCombined);
                    addItem.close();

                } catch (Exception e) {
                    Dialog e1 = new Dialog(ShoppingList.this);
                    e1.setTitle("Item unsuccesfully added");
                    TextView txt = new TextView(ShoppingList.this);
                    txt.setText("Success");
                    e1.setContentView(txt);
                    e1.show();

                } finally {
                    Dialog e = new Dialog(ShoppingList.this);
                    e.setTitle("Item succesfully added.");
                    TextView txt = new TextView(ShoppingList.this);
                    txt.setText("Success");
                    e.setContentView(txt);
                    e.show();

                    int cost = updateTotal();
                    totalPrice.setText(Integer.toString(cost));

                    setList();

                }

            }

        });

        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }
                });

        builder.show();

    }
    }

这是调用检查的类:

package com.example.flybaseapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;

public class CheckGPS extends Activity {

    boolean check;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        GPSYesOrNo g = new GPSYesOrNo(this);

        check = g.checkStatus();

        if (check == true) {

            Intent Appoint = new Intent("com.example.flybaseapp.CurrentLatLong");
            startActivity(Appoint);

        }

        else {

            alert();
        }
    }

    private void alert() {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // Setting Icon to Dialog
        // alertDialog.setIcon(R.drawable.delete);

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }

    }

和 GPSYesOrNo 类:

public class GPSYesOrNo{

Context cc;
private LocationManager locationManager;
boolean enable;

public GPSYesOrNo(Context c)
{
this.cc = c;
checkStatus();

}

public boolean checkStatus()
{


locationManager = (LocationManager) cc.getSystemService(Context.LOCATION_SERVICE);
  boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

           if(enabled){
               return true;
           }else{

               return false;

           }

}

异步类:

 package com.example.flybaseapp;

import java.util.List;

import com.google.android.maps.MapActivity;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;

公共类 GoogleAsync 扩展 AsyncTask> {

private Context context = null;

public GoogleAsync(Context ctx) {
    context = ctx;
}

@Override
protected List<JSON> doInBackground(String... arg0) {
    return new JSONResponse().searchPostalCode(arg0[0], arg0[1]);
}

@Override
protected void onPostExecute(List<JSON> result) {
    this.populateActivity(result);
}

void populateActivity(List<JSON> result) {

    // Associate Adapter to ListView for matching locations
    MapActivity mapAct = (MapActivity) context;
    ListView list = (ListView) mapAct.findViewById(R.id.list);

    ShopMapDisplay adapter = new ShopMapDisplay(context, result);
    list.setAdapter(adapter);

}

}

完整的 LogCat:

03-12 22:38:56.994: E/AndroidRuntime(372): FATAL EXCEPTION: main
03-12 22:38:56.994: E/AndroidRuntime(372): java.lang.ClassCastException: com.example.flybaseapp.PassLatLong
03-12 22:38:56.994: E/AndroidRuntime(372):  at com.example.flybaseapp.GoogleAsync.populateActivity(GoogleAsync.java:32)
03-12 22:38:56.994: E/AndroidRuntime(372):  at com.example.flybaseapp.GoogleAsync.onPostExecute(GoogleAsync.java:26)
03-12 22:38:56.994: E/AndroidRuntime(372):  at com.example.flybaseapp.GoogleAsync.onPostExecute(GoogleAsync.java:1)
03-12 22:38:56.994: E/AndroidRuntime(372):  at android.os.AsyncTask.finish(AsyncTask.java:417)
03-12 22:38:56.994: E/AndroidRuntime(372):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-12 22:38:56.994: E/AndroidRuntime(372):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-12 22:38:56.994: E/AndroidRuntime(372):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-12 22:38:56.994: E/AndroidRuntime(372):  at android.os.Looper.loop(Looper.java:123)
03-12 22:38:56.994: E/AndroidRuntime(372):  at android.app.ActivityThread.main(ActivityThread.java:4627)
03-12 22:38:56.994: E/AndroidRuntime(372):  at java.lang.reflect.Method.invokeNative(Native Method)
03-12 22:38:56.994: E/AndroidRuntime(372):  at java.lang.reflect.Method.invoke(Method.java:521)
03-12 22:38:56.994: E/AndroidRuntime(372):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-12 22:38:56.994: E/AndroidRuntime(372):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-12 22:38:56.994: E/AndroidRuntime(372):  at dalvik.system.NativeStart.main(Native Method)

目前我的模拟器设置为 GoogleApi 2.2。我真的很困惑这个错误,因为它以前工作过。在尝试实现 onStop() 覆盖后,这也没有解决问题。

4

2 回答 2

0

您的错误是com.example.flybaseapp.ShoppingList 您是否使用其他项目的代码片段?

于 2013-03-12T21:54:02.650 回答
0

您没有关闭数据库findPrice.open();。没有findPrice.close();

我建议你只打开 dbonCreate()并在onDestroy(). 这样你就不必一直打开和关闭然后忘记。

于 2013-03-12T22:25:56.350 回答