2013-03-12 16 views
2

在我简单地创建了一个新的模拟器以在Google地图API上运行之后,之前工作的代码中出现了非常令人沮丧的错误。检查GPS状态时无法停止活动

背景的代码:

当用户点击该按钮时,我的代码检查设备以查看是否GPS我当前活动或没有。如果不是,则会提示用户进入设置页面。如果是,那么他们的经纬度值将被发送到一个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 

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调用意图对象启动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()覆盖之后,这也没有解决问题。

+0

'ShoppingList'如何涉及到这个?它是否是CheckGPS之前的活动? – 2013-03-12 21:50:25

+0

@ A - C感谢您的回复。 ShoppingList是我的类,它包含调用“CheckGPS”类的按钮。我将添加此代码。如果您需要查看更多代码,请让我知道。我已经添加了我的swtich语句以及该类是如何从意图中调用的。 – user1352057 2013-03-12 21:53:49

+0

发布全班。有些东西*应该*为空。 – 2013-03-12 21:58:19

回答

0

您没有关闭db的findPrice.open();。没有findPrice.close();

我建议你只需在onCreate()中打开db并在onDestroy()中关闭它。这样你就不必打开和关闭,然后忘记。

+0

再次感谢你的大力帮助,你和A__C都是正确的我确实离开了两个实例DB打开。我现在有另一个问题,我已经更新了我原来的问题。 – user1352057 2013-03-12 22:40:21

+0

发布您的onStop代码 – 2013-03-12 22:46:33

+0

我已添加logcat。我没有onStop()方法。 – user1352057 2013-03-12 22:49:52

0

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

+0

我正在将代码从一个项目转移到另一个项目。 – user1352057 2013-03-12 21:55:36

+0

那么你是说,支票返回为真或假,但你的程序无法启动一项新的活动? – nishantvodoo 2013-03-12 22:04:23

+0

据我所见,是的。我已经剥离了代码,只是简单地使用'onCreate',但它仍然崩溃,说它无法停止。# – user1352057 2013-03-12 22:11:28