Java NullPointer使用imageadapter将远程图像加载到android库

时间:2013-04-28 03:30:52

标签: java android

您好我正在尝试将图像从服务器加载到图库中,但始终不断给我这个错误:

04-28 00:54:47.596: W/dalvikvm(715): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-28 00:54:47.608: E/AndroidRuntime(715): FATAL EXCEPTION: main
04-28 00:54:47.608: E/AndroidRuntime(715): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.plateamobile/com.plateamobile.ProdDetails}: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.os.Looper.loop(Looper.java:123)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-28 00:54:47.608: E/AndroidRuntime(715):  at java.lang.reflect.Method.invokeNative(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715):  at java.lang.reflect.Method.invoke(Method.java:521)
04-28 00:54:47.608: E/AndroidRuntime(715):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-28 00:54:47.608: E/AndroidRuntime(715):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-28 00:54:47.608: E/AndroidRuntime(715):  at dalvik.system.NativeStart.main(Native Method)
04-28 00:54:47.608: E/AndroidRuntime(715): Caused by: java.lang.NullPointerException
04-28 00:54:47.608: E/AndroidRuntime(715):  at com.plateamobile.ProdDetails.set_info(ProdDetails.java:138)
04-28 00:54:47.608: E/AndroidRuntime(715):  at com.plateamobile.ProdDetails.onCreate(ProdDetails.java:49)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-28 00:54:47.608: E/AndroidRuntime(715):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-28 00:54:47.608: E/AndroidRuntime(715):  ... 11 more

这是我的代码:

package com.plateamobile;



import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

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

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.Gallery.LayoutParams;

public class ProdDetails extends Activity {

    private ImageSwitcher mSwitcher;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.prod_details);
        Bundle extras = getIntent().getExtras();
        ((TextView)findViewById(R.id.prod_name)).setText(extras.getString("name"));
        ((TextView)findViewById(R.id.price_prod)).setText(new general().formatNumb(extras.getString("price")));


        set_info();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.prod_details, menu);
        return true;
    }

    public void set_info(){
        ObjConexion object = new ObjConexion();


        SoapObject request = new SoapObject(object.NameSpace(), "getProdinfo");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        Bundle extras = getIntent().getExtras();

        PropertyInfo idPro =new PropertyInfo();
        idPro.setName("id");
        idPro.setValue(extras.getString("id"));
        idPro.setType(String.class);
        request.addProperty(idPro);
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(object.Url());
        androidHttpTransport.debug = true;
        try {

            androidHttpTransport.call("getProdinfo", envelope);

            List<SoapPrimitive> response = (List<SoapPrimitive>) envelope.getResponse();

            ((TextView)findViewById(R.id.commerce)).setText(response.get(0).toString());
            ((TextView)findViewById(R.id.description)).setContentDescription(response.get(1).toString());

        }catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();
        }


        request = new SoapObject(object.NameSpace(), "getProdImg");
        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);


        idPro =new PropertyInfo();
        idPro.setName("id");
        idPro.setValue(extras.getString("id"));
        idPro.setType(Integer.class);
        request.addProperty(idPro);
        envelope.setOutputSoapObject(request);

        androidHttpTransport = new HttpTransportSE(object.Url());
        androidHttpTransport.debug = true;
        ArrayList<SoapObject> imagesList = new ArrayList<SoapObject>();


        try {

            androidHttpTransport.call("getProdImg", envelope);
            List<SoapObject> response = (List<SoapObject>) envelope.getResponse();


            for (int cont=0; cont<response.size() ;cont++){

                SoapObject responseChild = (SoapObject) response.get(cont);
                imagesList.add(responseChild);
            }


        }catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage() == null){

                Toast.makeText(this,"Error en la conexion",Toast.LENGTH_LONG).show();

            }else{

                Toast.makeText(this,e.getMessage().toString(),Toast.LENGTH_LONG).show();

            }

        }

        Gallery _gallery_ = (Gallery) findViewById(R.id.images_prod);

        if (imagesList!=null){
            _gallery_.setAdapter(new ImageAdapter(getApplicationContext(), imagesList));
        }else{
            Log.e("DEBUGTAG", "Remtoe Image Exception");
        }


    }
    public void goBack(View v){
        Intent intent = new Intent(ProdDetails.this, main_win.class);
        startActivity(intent);


    }

    public class ImageAdapter extends BaseAdapter {
        /** The parent context */
        private Context myContext;

        /** URL-Strings to some remote images. */
        private ArrayList<SoapObject> pckg_data;

        /** Simple Constructor saving the 'parent' context. */
        public ImageAdapter(Context c, ArrayList<SoapObject> data) { 
            this.myContext = c; 
            this.pckg_data = data;
            }

        /** Returns the amount of images we have defined. */
        public int getCount() { return this.pckg_data.size(); }

        /* Use the array-Positions as unique IDs */
        public Object getItem(int position) { return position; }
        public long getItemId(int position) { return position; }

        /** Returns a new ImageView to
         * be displayed, depending on
         * the position passed. */
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(this.myContext);

            try {
                /* Open a new URL and get the InputStream to load data from it. */
                URL aURL = new URL(pckg_data.get(position).getPropertyAsString(1));
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                /* Buffered is always good for a performance plus. */
                BufferedInputStream bis = new BufferedInputStream(is);
                /* Decode url-data to a bitmap. */
                Bitmap bm = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
                /* Apply the Bitmap to the ImageView that will be returned. */
                i.setImageBitmap(bm);
                        } catch (IOException e) {
                                Log.e("DEBUGTAG", "Remtoe Image Exception", e);
                        }

            /* Image should be scaled as width/height are set. */
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            /* Set the Width/Height of the ImageView. */
            i.setLayoutParams(new Gallery.LayoutParams(150, 150));
            return i;
        }

        /** Returns the size (0.0f to 1.0f) of the views
         * depending on the 'offset' to the center. */
        public float getScale(boolean focused, int offset) {
                /* Formula: 1 / (2 ^ offset) */
            return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
        }
    }

}

2 个答案:

答案 0 :(得分:0)

((TextView)findViewById(R.id.price_prod)).setText(new 
 general().formatNumb(extras.getString("price")));

检查extras.getString("price")的回复。它可能是异常的起源,因为他找不到“price”。

答案 1 :(得分:0)

第一次创建应用时,没有intent调用它。因此Bundle extras = getIntent().getExtras();会导致NullPointerException

将声明括在try块中。

try
{
     Bundle extras = getIntent().getExtras();
}
catch(Exception E){
//do nothing
}

但这不是正确的做法。

如果要再次调用此活动,建议您使用onNewIntent()方法并执行此活动singleTop

http://developer.android.com/reference/android/app/Activity.html http://developer.android.com/guide/topics/manifest/activity-element.html