0

我在做照片库时遇到问题。我正在从网络中检索。问题是无法在图库中设置图像。我知道我可能在某个地方犯了一些愚蠢的错误。谁能帮我解决这个问题。

这是我的更新代码:

MainActivity.java

public class MainActivity extends Activity implements OnItemClickListener {
String FILENAME = "http://122.com/12.php";
private static final String tag = "Main";
private static String carId = "";
private Gallery _gallery;
private ImageAdapter _imageAdapter;
static String j_img1 = null;
static String j_img2 = null;
static String j_img3 = null;
static String j_img4 = null;
ImageView img1;
Bitmap decodedByte;

SharedPreferences sp;
String s_id, is, str;

ArrayList<HashMap<String, String>> ImageList = new ArrayList<HashMap<String, String>>();
static ArrayList<Bitmap> bitimg = new ArrayList<Bitmap>();
// static ArrayList<Bitmap> img = new ArrayList<Bitmap>();

private static final String IMAGE1 = "img";
private static final String IMAGE2 = "img2";
private static final String IMAGE3 = "img3";
private static final String IMAGE4 = "img4";

/** Called when the activity is first created. */
public void getcarid(String car_id) {
    // TODO Auto-generated method stub
    carId = car_id;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setTitle("Android Honeycomb Photo Gallery Example");

    sp = PreferenceManager.getDefaultSharedPreferences(this);
    s_id = sp.getString("logID", null);
    Toast.makeText(getApplicationContext(), "ID= " + s_id,
            Toast.LENGTH_LONG).show();
    Toast.makeText(getApplicationContext(), "Car_ID= " + carId,
            Toast.LENGTH_LONG).show();
    //img1 = (ImageView) this.findViewById(R.id.imageView1);
     final Vibrator vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
    /* img1.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                vibrator.vibrate(100);
                AlertDialog.Builder dialogo1 = new AlertDialog.Builder(
                        MainActivity.this);
                dialogo1.setItems(R.array.Save,
                        new DialogInterface.OnClickListener() {
                            @SuppressLint("ShowToast")
                            public void onClick(
                                    DialogInterface dialoginterface,
                                    int i) {

                                if (i == 0) {
                                    saveImage();

                                }
                            }
                }).show();

                return true;
            }
        });*/

    _gallery = (Gallery) this.findViewById(R.id.gallery1);
    startDownload();

    _gallery.setAdapter(_imageAdapter);
    _gallery.setOnItemClickListener(this);
}

public void send_img() {
    Toast.makeText(this, "Send_img", Toast.LENGTH_SHORT).show();
    _imageAdapter = new ImageAdapter(this);
    _imageAdapter.setimage(bitimg);
}

void saveImage() {

   // String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File("/sdcard/CarList/");
    Long tsLong = System.currentTimeMillis()/1000;
    String ts = tsLong.toString();


    String fname = ts+".jpg";
    Toast.makeText(getApplicationContext(), "String name=:" + fname, Toast.LENGTH_LONG).show();
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);

           decodedByte.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}

@Override
public void onItemClick(AdapterView arg0, View view, int position,
        long duration) {
    int resourcId = (Integer)
    _imageAdapter.getItem(position);
    Toast.makeText(getApplicationContext(), "Inside OnItemClick= ",
            Toast.LENGTH_LONG).show();


    // Drawable drawable =getResources().getDrawable(resourcId);

/*    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
      resourcId);

     Toast.makeText( this, "Selected Image: " +
      getResources().getText(resourcId) + "\nHeight: " + bitmap.getHeight()
      + "\nWidth: " + bitmap.getWidth(), Toast.LENGTH_SHORT).show();*/


}


private void startDownload() {
    Toast.makeText(this, "StartDownload", Toast.LENGTH_SHORT).show();
    new AppTask().execute(FILENAME);
    // return bitimg;
}

public class AppTask extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        str = result;
        Toast.makeText(getApplicationContext(), "Array= " + str,
                Toast.LENGTH_LONG).show();

        try {

            JSONArray jArray = new JSONArray(str);

            for (int i = 0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                j_img1 = jObject.getString(IMAGE1);
                j_img2 = jObject.getString(IMAGE2);
                j_img3 = jObject.getString(IMAGE3);
                j_img4 = jObject.getString(IMAGE4);

                System.out.println("Image Array = " + jArray);
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(IMAGE1, j_img1);
                map.put(IMAGE2, j_img2);
                map.put(IMAGE3, j_img3);
                map.put(IMAGE4, j_img4);

                ImageList.add(map);

                for (int j = 0; j < ImageList.size(); j++) {
                    Iterator myVeryOwnIterator = map.keySet().iterator();
                    while (myVeryOwnIterator.hasNext()) {
                        String key = (String) myVeryOwnIterator.next();
                        String value = (String) map.get(key);
                        byte[] decodedString = Base64.decode(value,
                                Base64.DEFAULT);
                        decodedByte = BitmapFactory.decodeByteArray(
                                decodedString, 0, decodedString.length);
                        //img1.setImageBitmap(decodedByte);
                        bitimg.add(decodedByte);
                    }

                }
                //img1.setImageBitmap(decodedByte);

            }
            Toast.makeText(getApplicationContext(),
                    "bitimg Size= " + bitimg.size(), Toast.LENGTH_LONG)
                    .show();
            send_img();

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

    @Override
    protected String doInBackground(String... params) {

        // TODO Auto-generated method stub
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(FILENAME);
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    1);
            nameValuePairs.add(new BasicNameValuePair("cid", carId));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = EntityUtils.toString(entity);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

        return is;

    }

}

}

这是我更新的 ImageAdapter.java

public class ImageAdapter extends BaseAdapter {
private Context _context = null;
String s;
public static ArrayList<Bitmap> imageIds;

String size;

public ImageAdapter(Context context) {
    this._context = context;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub

    Toast.makeText(_context, "getCount= " + imageIds.size(),
            Toast.LENGTH_LONG).show();
    return (imageIds == null) ? 0 : imageIds.size();

}

@Override
public Object getItem(int index) {
    return imageIds.get(index);
}

@Override
public long getItemId(int index) {
    return index;
}

@Override
public View getView(int postion, View view, ViewGroup group) {
    ImageView imageView = new ImageView(_context);

    Toast.makeText(_context, "outside forloop= ", Toast.LENGTH_LONG).show();
    for (int i = 0; i<=postion;i++) //< imageIds.size(); postion++) 
        {
        Toast.makeText(_context, "Inside getView= ", Toast.LENGTH_LONG)
                .show();
        imageView.setImageBitmap(imageIds.get(postion));
        imageView.setScaleType(ScaleType.FIT_XY);
        imageView.setLayoutParams(new Gallery.LayoutParams(400, 400));

        //imageView.setImageResource(imageIds[position]);

        // System.gc();

    }

    return imageView;
}

public void setimage(ArrayList<Bitmap> bitimg) {
    imageIds = bitimg;
    Toast.makeText(_context, "setimage Size= " + imageIds.size(),
            Toast.LENGTH_LONG).show();

}

}

更新的 LOGCAT

07-19 08:42:07.623: E/AndroidRuntime(881): FATAL EXCEPTION: main
07-19 08:42:07.623: E/AndroidRuntime(881): java.lang.NullPointerException
07-19 08:42:07.623: E/AndroidRuntime(881):  at com.carlist.ImageAdapter.getCount(ImageAdapter.java:35)
07-19 08:42:07.623: E/AndroidRuntime(881):  at     android.widget.AbsSpinner.setAdapter(AbsSpinner.java:113)
07-19 08:42:07.623: E/AndroidRuntime(881):  at com.carlist.MainActivity.send_img(MainActivity.java:126)
07-19 08:42:07.623: E/AndroidRuntime(881):  at com.carlist.MainActivity$AppTask.onPostExecute(MainActivity.java:244)
07-19 08:42:07.623: E/AndroidRuntime(881):  at com.carlist.MainActivity$AppTask.onPostExecute(MainActivity.java:1)
07-19 08:42:07.623: E/AndroidRuntime(881):  at android.os.AsyncTask.finish(AsyncTask.java:417)
07-19 08:42:07.623: E/AndroidRuntime(881):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-19 08:42:07.623: E/AndroidRuntime(881):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-19 08:42:07.623: E/AndroidRuntime(881):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-19 08:42:07.623: E/AndroidRuntime(881):  at android.os.Looper.loop(Looper.java:123)
07-19 08:42:07.623: E/AndroidRuntime(881):  at android.app.ActivityThread.main(ActivityThread.java:3683)
07-19 08:42:07.623: E/AndroidRuntime(881):  at java.lang.reflect.Method.invokeNative(Native Method)
07-19 08:42:07.623: E/AndroidRuntime(881):  at java.lang.reflect.Method.invoke(Method.java:507)
07-19 08:42:07.623: E/AndroidRuntime(881):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-19 08:42:07.623: E/AndroidRuntime(881):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-19 08:42:07.623: E/AndroidRuntime(881):  at dalvik.system.NativeStart.main(Native Method)

它甚至没有进入 getview() 方法。我需要帮助,如果有人可以的话,我会很感激你。

4

1 回答 1

1

您创建的时间ImageAdaterimageIds空:更改getCount以检查空值

@Override
public int getCount() {
    return (imageIds == null) ? 0 : imageIds.size(); 
}


@Override
public View getView(int postion, View view, ViewGroup group) {
     ImageView imageView = new ImageView(_context);
     imageView.setImageBitmap(imageIds.get(postion));
     imageView.setScaleType(ScaleType.FIT_XY);
     imageView.setLayoutParams(new Gallery.LayoutParams(400, 400));

     return imageView;
}

   public void send_img() {
         Toast.makeText(this, "Send_img", Toast.LENGTH_SHORT).show();
         if (_imageAdapter == null) {
              _imageAdapter = new ImageAdapter(this);
              _gallery.setAdapter(_imageAdapter);
         }
        _imageAdapter.setimage(bitimg);
        _imageAdapter.notifyDataSetChanged();
   }
于 2013-07-15T10:16:41.797 回答