获取空指针异常无法启动主活动

时间:2013-10-10 11:11:25

标签: android nullpointerexception

StockLedgerRpt类显示空指针异常。此类在微调器视图中显示一个列表以选择库存项目。

package com.manacle.umma.activity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.manacle.umma.java.Constants;
import com.manacle.umma.java.DatabaseHelper;
import com.manacle.umma.java.Header;
import com.manacle.umma.java.Validation;

public class StockLedgerRep extends ListActivity {

    Button srch_btn;
    TextView stckldgr_header, stckldgr_cntr, frm_date, to_date,
    stck_item;
    EditText to_dt_edit, frm_dt_edit;
    Spinner add_stcitm_spin;
    RelativeLayout stckldgr_relative;
    LinearLayout stckldgr_linearLayout;
    HeaderDb headerDb;
    ListAdapter adapter;
    Header headerClass;
    HashMap<String, String> map, categoryMap, unitMap;
    String value, stockId, voucherId, code;
    String stockItemsname[] = null;
    String batchId = null;
    DatabaseHelper databaseHelper;
    Map stockItemMap;

    SharedPreferences preferences;
    String itemname;
    String firstSelection;
    private TextToSpeech tts;

    String batchIDD;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stck_ldgr_rpt);

        final HeaderDb db = new HeaderDb(getApplicationContext());

        headerDb = new HeaderDb(getApplicationContext());

        stckldgr_relative = (RelativeLayout) findViewById(R.id.stckldgr_relative_layout);
        stckldgr_linearLayout = (LinearLayout) findViewById(R.id.stckldgr_linear_layout);
        stckldgr_header = (TextView) findViewById(R.id.stckldgr_header);
        stckldgr_cntr = (TextView) findViewById(R.id.stckldgr_txt);
        frm_date = (TextView) findViewById(R.id.stckldgr_frmdate_txt);
        to_date= (TextView) findViewById(R.id.stckldgr_todate_txt);
        stck_item=(TextView) findViewById(R.id.stckldgr_stockItem_txt);
        add_stcitm_spin=(Spinner) findViewById(R.id.stckldgr_stock_item_spinner);

        frm_dt_edit = (EditText) findViewById(R.id.stckldgr_frmdate_edit);
        to_dt_edit = (EditText) findViewById(R.id.stckldgr_todate_edit);
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date date = new Date();
        frm_dt_edit.setText(dateFormat.format(date));
        frm_dt_edit.setFocusable(false);
        to_dt_edit.setText(dateFormat.format(date));
        to_dt_edit.setFocusable(false);


        String dat = preferences.getString("STOCK_CODE", "");
        if (!dat.equalsIgnoreCase("")) {
            // Toast.makeText(getApplicationContext(), "Selected date="+dat,
            // Toast.LENGTH_LONG).show();
            stckldgr_cntr.setText(dat);

        }

        final OnDateSetListener odsl = new OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker arg0, int year, int month, int day) {
                String date_format = Validation.dateFormat(month, day, year);

                frm_dt_edit.setText(date_format);
                to_dt_edit.setText(date_format);
                }
        };

        frm_dt_edit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Calendar cal = Calendar.getInstance();
                DatePickerDialog datePickDiag = new DatePickerDialog(
                        StockLedgerRep.this, odsl, cal.get(Calendar.YEAR), cal
                        .get(Calendar.MONTH), cal
                        .get(Calendar.DAY_OF_MONTH));
                datePickDiag.show();

            }
        });

        to_dt_edit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Calendar cal = Calendar.getInstance();
                DatePickerDialog datePickDiag = new DatePickerDialog(
                        StockLedgerRep.this, odsl, cal.get(Calendar.YEAR), cal
                        .get(Calendar.MONTH), cal
                        .get(Calendar.DAY_OF_MONTH));
                datePickDiag.show();

            }
        });


        com.manacle.umma.java.SpinnerAdapter adapter1 = new com.manacle.umma.java.SpinnerAdapter(
                this, android.R.layout.simple_spinner_item, getStockItem());

        add_stcitm_spin.setAdapter(adapter1);

        add_stcitm_spin.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub

                Object item = arg0.getItemAtPosition(arg2);

                if (item.equals("")) {

                } else {
                    firstSelection = add_stcitm_spin.getSelectedItem()
                            .toString();
                    // tToast(""+firstSelection);

                    if (firstSelection.equals("All")) {
                        if (headerDb.getVouDateTransIdfromVouTableforAllItem(value, batchId).size() > 0) {
                            //showAllName_Id();
                        } else {
                            // tToast("No Record, Please add new Record.");
                            //showAllName_Id();
                        }
                    } else {
                        List stockItemList = headerDb
                                .getAllIRMStockItem(headerDb
                                        .getAllIRMStockcategoryID());
                        Map mapItem = (Map) stockItemList.get(arg2 - 1);
                        code = (String) mapItem.get(add_stcitm_spin
                                .getSelectedItem().toString());
                    }
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        }); }








    private void tToast(String s) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, s, duration);
        toast.show();
    }



    public String[] getStockItem() {

        String arr_name[] = null;
        List listCategoryId = headerDb.getAllIRMStockcategoryID();
        List stockList = headerDb.getAllIRMStockItem(listCategoryId);

        Iterator memberItemsItr = headerDb.getAllIRMStockItem(listCategoryId)
                .iterator();
        int i = 0;
        arr_name = new String[stockList.size() + 1];
        arr_name[0] = "All";
        i++;
        // tToast("ARRSIZE="+listCategoryId.size());
        while (memberItemsItr.hasNext()) {

            stockItemMap = (Map) memberItemsItr.next();

            Iterator<?> iter = stockItemMap.entrySet().iterator();

            // String arr_code[]=new String[memberItemsMap.size()+1];
            while (iter.hasNext()) {
                Map.Entry mEntry = (Map.Entry) iter.next();
                // tToast(mEntry.getKey() + " : " + mEntry.getValue());
                String stockName = (String) mEntry.getKey();
                String stockCode = (String) mEntry.getValue();

                arr_name[i] = stockName;
                i++;

            }

        }
        return arr_name;
    }
    public void showAllName_Id() {

        adapter = new SimpleAdapter(this, headerDb.getVouDateTransIdfromVouTableforAllItem(value, batchId),
                R.layout.stock_list_item, new String[] {
                        Constants.Bat_Acc_Voch_VOUCHER_DATE,
                        Constants.Bat_Acc_Voch_Trans_Id }, new int[] {
                        R.id.stock_list_code, R.id.stock_list_name });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
        // lv.setBackgroundColor(Integer.parseInt(headerDb.getBgColor("KD125"),
        // 16)+0xFF000000);
        // lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        try {
            // lv.setSelector(R.drawable.sel);
        } catch (Exception e) {
            // TODO: handle exception
            tToast("Error" + e);
        }
        // lv.setSelector(Color.RED);
    lv.setOnTouchListener(new ListView.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                case MotionEvent.ACTION_DOWN:
                    // Disallow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(true);

                    // v.setBackgroundResource(R.drawable.sel);

                    break;

                case MotionEvent.ACTION_UP:
                    // Allow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    // v.setBackgroundResource(R.drawable.sel);

                    break;
                }

                // Handle ListView touch events.
                v.onTouchEvent(event);
                return true;
            }
        });

    lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                String name = ((TextView) view
                        .findViewById(R.id.stock_list_code)).getText()
                        .toString();

                voucherId = ((TextView) view.findViewById(R.id.stock_list_name))
                        .getText().toString();
                String Vid[] = voucherId.split("-");
                String vid = Vid[1];
                String mobtrans = Vid[0];
                // tToast("Voucher Id="+vid);
                // tToast("Selected Value="+name+""+code);

                Intent in = new Intent(getApplicationContext(),
                        IRM_add_preview.class);
                in.putExtra("VOU_ID", vid);
                in.putExtra("VALUE", value);
                in.putExtra("MOBTRANS", mobtrans);
                startActivity(in);

            }
        });
    }
    }

stck_ldgr Xml这个xml显示三个东西,一个是微调器库存项目列,另外两个是选择日期。我无法得到错误。请帮助。甚至在androidmanifest.xml中添加

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true"
        android:id="@+id/stckldgr_relative_layout"

     >

    <TextView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="10dp"
         />

    <TextView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/imageView1"
        android:orientation="vertical" 
        android:id="@+id/stckldgr_linear_layout"

        >

        <!--  --> 
        <ScrollView 
                android:id="@+id/scroller"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:fillViewport="true" >



    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"

        >
        <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:paddingLeft="6dip"
            android:paddingRight="6dip"
            android:paddingTop="6dip" 
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Stock Ledger Report"
            android:textStyle="bold"
            android:gravity="center"
        android:id="@+id/stckldgr_header"
            />

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dip"
            android:background="#ff106510"
            android:layout_marginLeft="6dip"
            android:layout_marginRight="6dip"
            android:layout_marginTop="6dip"
            android:layout_marginBottom="12dip" />

        <LinearLayout
        android:id="@+id/linearLayout_login_4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       android:orientation="vertical"

      >

             <TableLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent" >


             <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:paddingLeft="6dip"
            android:paddingRight="6dip"
           android:id="@+id/stckldgr_txt"
           android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Stock Center Code-Name"
            android:gravity="center"
            />


             <TableRow
                    android:id="@+id/tableRow1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                     >
                     <TextView

            android:text="Stock Item"
            android:height="40dp"
            android:width="150dp"
             android:layout_marginTop="10dip"
            android:textStyle="bold"
                    android:id="@+id/stckldgr_stockItem_txt"

             android:layout_gravity="center_horizontal|bottom"

            ></TextView>

                      <Spinner
android:id="@+id/stckldgr_stock_item_spinner"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginRight="6dip"

android:saveEnabled="true" >

</Spinner>



                        </TableRow>


             <TableRow
                    android:id="@+id/tableRow1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                     android:layout_marginTop="5dip"
                     >

                        <TextView
                            android:layout_width="150dp"
                            android:layout_height="40dp"
                            android:layout_marginTop="10dip"
                            android:text="From Date"
                             android:textStyle="bold"
                             android:id="@+id/stckldgr_frmdate_txt"

                            />

                        <EditText
                            android:id="@+id/stckldgr_frmdate_edit"
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_marginLeft="0dip"
                            android:layout_marginRight="10dip"

                            android:editable="false"
                            >

                            <requestFocus />
                        </EditText>

                        </TableRow>

             <TableRow
                    android:id="@+id/tableRow1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                     android:layout_marginTop="5dip"
                     >

                        <TextView
                            android:layout_width="150dp"
                            android:layout_height="40dp"
                            android:layout_marginTop="10dip"
                            android:text="To Date"
                             android:textStyle="bold"
                             android:id="@+id/stckldgr_todate_txt"

                            />

                        <EditText
                            android:id="@+id/stckldgr_todate_edit"
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:layout_marginLeft="0dip"
                            android:layout_marginRight="10dip"

                            android:editable="false"
                            >

                            <requestFocus />
                        </EditText>

                        </TableRow>




             </TableLayout>

              <ListView
             android:id="@android:id/list"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:layout_marginBottom="15dp"
             android:layout_marginTop="15dp"
             android:layout_weight="1"
             android:divider="@color/divider"
              android:listSelector="#369659"
                 android:cacheColorHint="#369659"
             android:dividerHeight="2px"
             android:choiceMode="singleChoice"
             android:gravity="center" >
         </ListView>

       </LinearLayout> 
    </LinearLayout>
    </ScrollView>
     </LinearLayout>

    </RelativeLayout>

logcat的

10-10 10:44:55.832: D/AndroidRuntime(2639): Shutting down VM
10-10 10:44:55.865: W/dalvikvm(2639): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-10 10:44:56.023: E/AndroidRuntime(2639): FATAL EXCEPTION: main
10-10 10:44:56.023: E/AndroidRuntime(2639): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.manacle.umma.activity/com.manacle.umma.activity.StockLedgerRep}: java.lang.NullPointerException
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.os.Looper.loop(Looper.java:137)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.ActivityThread.main(ActivityThread.java:5041)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at java.lang.reflect.Method.invokeNative(Native Method)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at java.lang.reflect.Method.invoke(Method.java:511)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at dalvik.system.NativeStart.main(Native Method)
10-10 10:44:56.023: E/AndroidRuntime(2639): Caused by: java.lang.NullPointerException
10-10 10:44:56.023: E/AndroidRuntime(2639):     at com.manacle.umma.activity.StockLedgerRep.onCreate(StockLedgerRep.java:96)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.Activity.performCreate(Activity.java:5104)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-10 10:44:56.023: E/AndroidRuntime(2639):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
10-10 10:44:56.023: E/AndroidRuntime(2639):     ... 11 more

4 个答案:

答案 0 :(得分:4)

您的preferences对象为空。

您需要在使用之前对其进行初始化。像这样:

preferences = PreferenceManager.getDefaultSharedPreferences(this);
String dat = preferences.getString("STOCK_CODE", "");

答案 1 :(得分:1)

因为您没有初始化首选项。这是问题所在:

String dat = preferences.getString(“STOCK_CODE”,“”);

答案 2 :(得分:0)

如果你使用Eclipse或任何其他IDE,你应该双击错误行,这样就可以直接找到异常来源...

10-10 10:44:56.023: E/AndroidRuntime(2639):     at com.manacle.umma.activity.StockLedgerRep.onCreate(StockLedgerRep.java:96)

应该像其他用户一样建议偏好...

答案 3 :(得分:0)

您可以在第96行之前编写此代码。

preferences= getApplicationContext.getSharedPreferences("blablabla", Context.MODE_PRIVATE);