2013-03-12 62 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