在ArayAdapter中使用Spinner获取空指针异常

时间:2014-08-04 03:30:40

标签: android android-adapter

我在ArrayAdapter中显示我的Spinner时出现问题。它变空了我不知道为什么。错误是空指针异常。请帮我解决这个问题。这是我的代码。

package com.example.senditem;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.functions.ClientModel;
import com.functions.JSONParser;
import com.functions.Model;
import com.functions.MyAdapter;
import com.functions.SqliteHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class UserProductActivity extends Activity {
 ListView listView;
    Button btnSend;
    Button btnSave;
    Button btnSearch;
    Button btnUpload;
    Spinner inputUom;
    String items;
    JSONParser jsonParser = new JSONParser();
    ArrayAdapter<Model> adapter;
    List<String> uomlist;
    List<Model> list = new ArrayList<Model>();
    ArrayList<ClientModel> sales = new ArrayList<ClientModel>();
    private String search_product;
    private String phoneNo;
    ProgressDialog pDialog;

    private static String upload = "http://192.168.0.101/MyAndroidConnect/upload.php";
    private static String KEY_SUCCESS = "success";
    private static String KEY_ITEM = "items";
    private static String KEY_AGENT = "agent";
    private static String KEY_DAYS = "days";
    private static String KEY_BARCODE = "barcode";
    private static String KEY_CLIENT = "client";
    private static String KEY_QTY = "qty";
    private static String KEY_UOM = "uom";

    String acode;
    String days;
    String client;
    String bcode;
    String qty;
    String uom;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.userprodmain);
        Intent i=getIntent();
        final Bundle b = i.getExtras();
        final SqliteHelper db = new SqliteHelper(this);
        listView = (ListView) findViewById(R.id.my_list);
//      btnSend = (Button) findViewById(R.id.btnSend);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnUpload = (Button) findViewById(R.id.btnUpload);
        inputUom = (Spinner) findViewById(R.id.inputUom);


        adapter = new MyAdapter(this, getModel(), Integer.parseInt(b.get("id").toString()) );
//      Toast.makeText(getBaseContext(),b.get("id").toString(),       
               Toast.LENGTH_LONG).show();
        listView.setAdapter(adapter);

        final List<String> uomlist = new ArrayList<String>();
        for(int j=0;j<list.size();j++){
            String barcode = list.get(j).getBar();
            uomlist.add(db.selectUom(barcode));



   //Toast.makeText(getBaseContext(),db.selectUom(barcode),Toast.LENGTH_SHORT).show();

        }




 ArrayAdapter<String> uomadapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,uomlist);
        uomadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        inputUom.setAdapter(uomadapter);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        btnSave.setOnClickListener(new View.OnClickListener() {
                    public void onClick(final View v) {
                    listView.clearFocus();
                    AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
                    alert.setTitle("Save Details?");
                    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which){
                        for (int i = 0; i < list.size(); i++) {
                            if(list.get(i).getQuantity()!=null)
                            {
//  Toast.makeText(v.getContext(), String.valueOf(list.get(i).getprodId()), Toast.LENGTH_LONG).show();
                                    db.addItem(new Model(Integer.parseInt(b.get("id").toString()), list.get(i).getprodId(), list.get(i).getQuantity(),list.get(i).getAmt()));
                                }
                            }
                        }
                        });
                    alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             dialog.cancel();
                         }
                     });
                    alert.show();
            }
         });



        btnSearch.setOnClickListener(new View.OnClickListener(){

            public void onClick(final View v) {
                     AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
                     alert.setTitle("Search Item");
                     final EditText input = new EditText(v.getContext());
                     input.setInputType(InputType.TYPE_CLASS_TEXT);
                     alert.setView(input);
                     alert.setPositiveButton("Search", new DialogInterface.OnClickListener(){
                         @Override
                         public void onClick(DialogInterface dialog, int which){
                             search_product = input.getText().toString();
                             int z=0;
                             for (int i = 0; i < list.size(); i++) {
                                 if(search_product.toUpperCase().equals(list.get(i).getName().toUpperCase())){
                                     listView.setSelection(i);
                                     z=0;
                                 }
                                 else
                                     z++;
                             }
                             if(z==list.size())
                             {
                               AlertDialog alert = new AlertDialog.Builder(v.getContext()).create();
                               alert.setTitle("No Data Found!");
                               alert.show();
                             }
                         }
                     });
                     alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                         public void onClick(DialogInterface dialog, int which) {
                             dialog.cancel();
                         }
                     });


                 alert.setMessage("Input Message");
  //          alert.setCanceledOnTouchOutside(true);
  //          alert.setCancelMessage(null);
                     alert.show();
            }
        });



btnUpload.setOnClickListener(new View.OnClickListener(){

            public void onClick(final View v) {

                new UploadSales().execute();
            }





  });

    }
     private List<Model> getModel() {
        Intent i=getIntent();
        final Bundle b = i.getExtras();
        SqliteHelper db = new SqliteHelper(this);
        list = db.getAllProduct(b.get("clientCode").toString(),b.get("day").toString());
        return list;
    }

  class UploadSales extends AsyncTask <String,String,String>{

      @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UserProductActivity.this);
            pDialog.setMessage("Uploading Sales. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }


      protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {

                        Intent i=getIntent();
                        final Bundle b = i.getExtras();
                        SqliteHelper db = new SqliteHelper(getApplicationContext()); 


                        for(int j=0; j<list.size(); j++){

                            acode = db.getAgent(1);
                            days = b.get("day").toString();
                            client = b.get("clientCode").toString();
                            bcode = list.get(j).getBar();
                            qty = list.get(j).getQuantity();
                            uom = list.get(j).getUom();         



                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("agent", acode));
                        params.add(new BasicNameValuePair("days", days));
                        params.add(new BasicNameValuePair("barcode", bcode));
                        params.add(new BasicNameValuePair("client", client));
                        params.add(new BasicNameValuePair("uom", uom));
                        params.add(new BasicNameValuePair("qty", qty));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                upload, "POST", params);

                        // check your log for json response
                        Log.d("Single Product Details", json.toString());

                        // json success tag
                        success = json.getInt(KEY_SUCCESS);

                        if (success == 1) {
                           //


                        }else{
                            // product with pid not found
                        }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }








  }

}

这里的问题是什么?

logcat的

08-04 11:44:12.812: E/AndroidRuntime(28977): FATAL EXCEPTION: main
08-04 11:44:12.812: E/AndroidRuntime(28977): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.senditem/com.example.senditem.UserProductActivity}: java.lang.NullPointerException
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.ActivityThread.access$600(ActivityThread.java:162)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.os.Handler.dispatchMessage(Handler.java:107)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.os.Looper.loop(Looper.java:194)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.ActivityThread.main(ActivityThread.java:5400)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at java.lang.reflect.Method.invokeNative(Native Method)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at java.lang.reflect.Method.invoke(Method.java:525)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:837)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at dalvik.system.NativeStart.main(Native Method)
08-04 11:44:12.812: E/AndroidRuntime(28977): Caused by: java.lang.NullPointerException
08-04 11:44:12.812: E/AndroidRuntime(28977):    at com.example.senditem.UserProductActivity.onCreate(UserProductActivity.java:104)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.Activity.performCreate(Activity.java:5122)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
08-04 11:44:12.812: E/AndroidRuntime(28977):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
08-04 11:44:12.812: E/AndroidRuntime(28977):    ... 11 more

XML

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<TextView
android:id="@+id/label"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="@+id/label"
android:textSize="15sp"/>

<TextView
    android:id="@+id/inputAmt"
    android:layout_width="50dp"
    android:layout_height="35dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginRight="22dp"
    android:ems="10"
    android:gravity="right"
    android:inputType="number"
    android:textSize="12sp" />

<EditText
    android:id="@+id/inputQty"
    android:layout_width="40dp"
    android:layout_height="35dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:ems="10"
    android:gravity="right"
    android:inputType="number"
    android:textSize="12sp" >



 <requestFocus />
</EditText>

<Spinner
    android:id="@+id/inputUom"
    android:layout_width="40dp"
    android:layout_height="35dp"
   />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

看到这是你的错误:

替换

 adapter = new MyAdapter(this, getModel(), Integer.parseInt(b.get("id").toString()) );
//      Toast.makeText(getBaseContext(),b.get("id").toString(),       
               Toast.LENGTH_LONG).show();
        listView.setAdapter(adapter);

adapter = new MyAdapter(this, getModel(), Integer.parseInt(b.get("id").toString()) );
//      Toast.makeText(getBaseContext(),b.get("id").toString(),       
//               Toast.LENGTH_LONG).show();
        listView.setAdapter(adapter);

还有一个错误,我发现检查你是否在你的代码中声明了两次全局,第二次在本地声明,所以只需删除本地声明 替换

final List<String> uomlist=new ArrayList<String>()

uomlist=new ArrayList<String>()

多数民众赞成......