显示java.lang.NullPointerException(安卓)

时间:2014-04-17 05:51:00

标签: java android android-asynctask

我将AsyncTask类的值传递给addValue方法,并从getValue方法获取值。这里addValue运行良好,但getValue以某种方式无法获取值并在我点击图片时在我的应用中返回Java.lang.nullPointerException

package com.example.mobile_e_commerce;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.example.mobile_e_commerce.dummy.ProductInfo.ProductItem;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
//include soap passing here

public class ProductCollection extends Activity {

public final static String EXTRA_MESSAGE = "com.example.mobile_e_commerce.product_name";
private static final ResourceBundle rb = ResourceBundle.getBundle("com.example.mobile_e_commerce.webserviceurl");
public static Map<String, ProductItem> ITEM_MAP = new HashMap<String, ProductItem>();


//Class involve asynctask(background running)//
public class objectTransfer extends AsyncTask<Void,Void,Void>{

这里列出了web服务网址和soap操作,但我已经测试过,并且还返回了值。

    private final String NAMESPACE = rb.getString("WSDLTargetNamespace");
    private  final String SoapURL = rb.getString("SoapAddress");
    private final String SOAP_ACTION = rb.getString("SoapAction");
    private final String METHOD_NAME = rb.getString("OperationName");
    private final String SOAP_ACTION2 = rb.getString("SoapAction2");
    private final String METHOD_NAME2 = rb.getString("OperationName2");
    private final String SOAP_ACTION3 = rb.getString("SoapAction3");
    private final String METHOD_NAME3 = rb.getString("OperationName3");
    private final String SOAP_ACTION4 = rb.getString("SoapAction4");
    private final String METHOD_NAME4 = rb.getString("OperationName4");
    private final String SOAP_ACTION5 = rb.getString("SoapAction5");
    private final String METHOD_NAME5 = rb.getString("OperationName5");
    private final String SOAP_ACTION6 = rb.getString("SoapAction6");//image location
    private final String METHOD_NAME6 = rb.getString("OperationName6");//image location
    private final String SOAP_ACTION7 = rb.getString("SoapAction7");
    private final String METHOD_NAME7 = rb.getString("OperationName7");

    //private Activity activity = new Activity();
  //  ImageView imageView = (ImageView)getActivity().findViewById(R.id.productImgDisplay);


    /**
     * A map of sample (dummy) items, by ID.
     */


    //  private File file = new File(Integer.toString(R.drawable.search));

         private String[] valuePass = new String[100];

         private int i;
         PropertyInfo pi = new PropertyInfo();


         private int n =0;
         PropertyInfo getInfo = new PropertyInfo();
         //  private int number = 0;



     @Override
      protected Void doInBackground(Void... arg0) {
         try
            {
            //get the no of the product
                Object response2 = null;
                    SoapObject request2 = new SoapObject(NAMESPACE,METHOD_NAME5);
                    SoapSerializationEnvelope envelope2 = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                    envelope2.dotNet = true;

                envelope2.setOutputSoapObject(request2);

                HttpTransportSE httpTransport2 = new HttpTransportSE(SoapURL);

                httpTransport2.call(SOAP_ACTION5, envelope2);
                response2 = envelope2.getResponse();
                i = Integer.parseInt(response2.toString());

                    try
                    {
                        //get the name of the product
                        Object response = null;

                        while(n < i)
                        {
                            SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
                            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

                                    envelope.dotNet = true;
                                    request.addProperty("number", n);


                        envelope.setOutputSoapObject(request);

                        HttpTransportSE httpTransport = new HttpTransportSE(SoapURL);

                    httpTransport.call(SOAP_ACTION, envelope);
                    response = envelope.getResponse();

                    //imageurl equal to byte type image data,will add to WS later



                         valuePass[n] = response.toString();
                        // Log.e("Value", valuePass[n]);
                         n++;

                         addValue(new ProductItem(Integer.toString(n) ,valuePass[n]));

                        }
                    }
                    catch (Exception exception)
                    {
                        exception.printStackTrace();
                        Log.e("Apps Error", exception.toString());
                    }
            }
            catch (Exception exception)
            {
                exception.printStackTrace();
                Log.e("Apps Error", exception.toString());
            }
                    return null;

     }

}

addValue方法应该可以正常工作,可以包含在上面的onBackground方法中。我将在稍后尝试查看。

public void addValue(ProductItem Item)
{
    ITEM_MAP.put(Item.id, Item);
}

getValue方法基于我稍后将在onCreate方法中输入的String值

public String getValue(String id)
{   ProductItem value;
try{
    value = ITEM_MAP.get(id);//check here later

    Log.e("Value: ", value.toString());
    return "";  
}
catch(Exception ee)
{
    ee.printStackTrace();
}
    return "";
}

这是初始化变量的类,将在我的保存和检索值中使用,就像刚才提到的那样:名称和id。

public static class ProductItem {//Instantiation of variable
    public String name;
    public String id;

    public ProductItem(String id,String name) {
        this.id = id;
        this.name = name;
    }
}

    /////*****////////

可以忽略MOBILE_OS,因为它仅用于检测图像的测试目的

    static final String[] MOBILE_OS = new String[] { 
        "Samsung Galaxy S III 16GB", "Samsung Galaxy S IV Zoom","Samsung Galaxy Note 8.0 16GB", "Blackberry" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          final Intent intent = new Intent(this,ProductCollectionDetails.class);
          setContentView(R.layout.activity_product_collection);

          GridView gridview = (GridView) findViewById(R.id.productGridView);

          gridview.setAdapter(new ImageAdapter(this,MOBILE_OS)); 

          gridview.setOnItemClickListener(new OnItemClickListener() {
              public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                  // Toast.makeText(ProductCollection.this, "" + MOBILE_OS[position], Toast.LENGTH_SHORT).show();

              //  Log.e("Item map value", ITEM_MAP.get(position).toString());
               //   for (Map.Entry<String,ProductItem> entry : ITEM_MAP.entrySet()) {

此处调用getValue方法。

                     getValue(Integer.toString(position));
                //  }


                //   if((MOBILE_OS[position]).toString()== ITEM_MAP.get(position).toString())
                  //    {
                                //intent.putExtra(EXTRA_MESSAGE,(MOBILE_OS[position]).toString());
                                //startActivity(intent);
                   //   }
               }
            });


        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

onResumeonPause方法仅用于调用AsyncTask并清除HashMap

@Override
protected void onResume()
{
    super.onResume();
    (new objectTransfer()).execute(null,null,null);
    //Log.e("Task Running", "AsyncTask");

}

@Override
protected void onPause()
{
    super.onPause();
    ITEM_MAP.clear();
}



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.product_collection, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(
                    R.layout.fragment_product_collection, container, false);
            return rootView;
        }
    }

}

来自我日食的logcat:

04-17 14:14:55.820: D/dalvikvm(14073): GC_FOR_ALLOC freed 124K, 27% free 6530K/8899K, paused 0ms
04-17 14:14:55.820: I/dalvikvm-heap(14073): Grow heap (frag case) to 10.931MB for 2524908-byte allocation
04-17 14:14:55.890: D/dalvikvm(14073): GC_CONCURRENT freed 1K, 22% free 8995K/11395K, paused 0ms+0ms
04-17 14:14:56.020: D/dalvikvm(14073): GC_FOR_ALLOC freed 2468K, 40% free 7629K/12547K, paused 0ms
04-17 14:14:56.140: I/PGA(14073): New SOCKET connection: bile_e_commerce (pid 14073, tid 14073)
04-17 14:14:59.960: D/dalvikvm(14073): GC_CONCURRENT freed 1259K, 34% free 8402K/12547K, paused 0ms+0ms
04-17 14:15:00.100: E/dalvikvm(14073): No JIT support for bytecode f0 at offsetPC 0
04-17 14:15:00.100: E/dalvikvm(14073): JIT implementation not found
04-17 14:15:00.100: I/dalvikvm(14073): codeGenBasicBlockJit returns negative number
04-17 14:15:00.100: E/dalvikvm(14073): No JIT support for bytecode f0 at offsetPC 0
04-17 14:15:00.100: E/dalvikvm(14073): JIT implementation not found
04-17 14:15:00.100: I/dalvikvm(14073): codeGenBasicBlockJit returns negative number
04-17 14:15:00.160: D/dalvikvm(14073): GC_FOR_ALLOC freed 540K, 24% free 9553K/12547K, paused 10ms
04-17 14:15:00.210: D/dalvikvm(14073): GC_FOR_ALLOC freed 1172K, 32% free 9056K/13315K, paused 10ms
04-17 14:15:00.210: I/dalvikvm-heap(14073): Grow heap (frag case) to 15.110MB for 4320012-byte allocation
04-17 14:15:00.310: D/dalvikvm(14073): GC_FOR_ALLOC freed <1K, 25% free 13274K/17539K, paused 90ms
04-17 14:15:00.330: D/dalvikvm(14073): GC_CONCURRENT freed 0K, 25% free 13274K/17539K, paused 0ms+0ms
04-17 14:15:00.350: D/dalvikvm(14073): GC_FOR_ALLOC freed 2K, 25% free 13282K/17539K, paused 0ms
04-17 14:15:00.360: I/dalvikvm-heap(14073): Grow heap (frag case) to 16.948MB for 1920012-byte allocation
04-17 14:15:00.370: D/dalvikvm(14073): GC_FOR_ALLOC freed <1K, 23% free 15156K/19459K, paused 10ms
04-17 14:15:00.390: D/dalvikvm(14073): GC_FOR_ALLOC freed 4221K, 44% free 10943K/19459K, paused 0ms
04-17 14:15:00.400: I/dalvikvm-heap(14073): Grow heap (frag case) to 14.978MB for 2250012-byte allocation
04-17 14:15:00.440: D/dalvikvm(14073): GC_CONCURRENT freed <1K, 33% free 13140K/19459K, paused 0ms+0ms
04-17 14:15:01.050: D/dalvikvm(14073): GC_CONCURRENT freed 3141K, 39% free 11952K/19459K, paused 0ms+0ms
04-17 14:15:04.030: W/System.err(14073): java.lang.NullPointerException
04-17 14:15:04.030: W/System.err(14073):    at com.example.mobile_e_commerce.ProductCollection.getValue(ProductCollection.java:162)
04-17 14:15:04.030: W/System.err(14073):    at com.example.mobile_e_commerce.ProductCollection$1.onItemClick(ProductCollection.java:202)
04-17 14:15:04.040: W/System.err(14073):    at android.widget.AdapterView.performItemClick(AdapterView.java:292)
04-17 14:15:04.040: W/System.err(14073):    at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
04-17 14:15:04.040: W/System.err(14073):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
04-17 14:15:04.040: W/System.err(14073):    at android.widget.AbsListView$1.run(AbsListView.java:3168)
04-17 14:15:04.040: W/System.err(14073):    at android.os.Handler.handleCallback(Handler.java:605)
04-17 14:15:04.040: W/System.err(14073):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-17 14:15:04.040: W/System.err(14073):    at android.os.Looper.loop(Looper.java:137)
04-17 14:15:04.040: W/System.err(14073):    at android.app.ActivityThread.main(ActivityThread.java:4424)
04-17 14:15:04.040: W/System.err(14073):    at java.lang.reflect.Method.invokeNative(Native Method)
04-17 14:15:04.040: W/System.err(14073):    at java.lang.reflect.Method.invoke(Method.java:511)
04-17 14:15:04.040: W/System.err(14073):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
04-17 14:15:04.040: W/System.err(14073):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
04-17 14:15:04.040: W/System.err(14073):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

检查你的getValue()方法

试试这个

public String getValue(String id)
{   
  ProductItem value;               
   try{           
  if(ITEM_MAP != null )               
    value = ITEM_MAP.get(id.trim());//check here later       
  if(value != null){         
    Log.e("Value: ", value.toString());        
}       
    return "";  
}
catch(Exception ee)
{
    ee.printStackTrace();
}
    return "";
}