简体   繁体   English

检查GPS状态时无法停止活动

[英]Unable to stop activity when checking for GPS status

Very frustrating error that has appeared on previously working code after I simply created a new emulator to run on Google maps API. 在我简单地创建了一个新的模拟器以在Google Maps API上运行之后,以前的工作代码中出现了非常令人沮丧的错误。

Background of the code: 代码背景:

When the user taps the button, my code checks the device to see if the GPS i currently active or not. 当用户点击按钮时,我的代码将检查设备以查看GPS i当前是否处于活动状态。 If it isnt, the users is prompted to the settings page. 如果不是,则提示用户进入设置页面。 If it is, then their Lat ang Long values are sent to a AsyncTask. 如果是,则将其经度Long值发送到AsyncTask。

From what I can see my GPS is returning a value (be it true or false) but im getting the following error: 从我可以看到,我的GPS返回一个值(是true还是false),但是我收到了以下错误消息:

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

Passlat: Passlat:

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 calls the intent object to start the CheckGPS class: ShoppingList.Java调用intent对象以启动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();

    }
    }

Heres the class that calls the check: 这是调用检查的类:

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();
    }

    }

And the GPSYesOrNo class: 和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;

           }

}

Async class: 异步类:

 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;

public class GoogleAsync extends AsyncTask> { 公共类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);

}

}

Full LogCat: 完整的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)

Currently my emulator is set to GoogleApi 2.2. 目前,我的模拟器设置为GoogleApi 2.2。 Im really confused on this error as it was previously working. 我确实对此错误感到困惑,因为它以前一直在起作用。 After trying to implement a onStop() override, this did not fix the issue either. 尝试实现onStop()覆盖后,这也无法解决问题。

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

You did not close the db for findPrice.open(); 您没有为findPrice.open();关闭数据库findPrice.open(); . No findPrice.close(); 没有findPrice.close(); .

I suggest you just open the db in onCreate() and close it in onDestroy() . 我建议您只是在onCreate()打开数据库,然后在onDestroy()关闭它。 That way you do not have to keep opening and closing and then forget. 这样,您不必保持打开和关闭然后忘记的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM