位图的输出始终以android形式显示为null

时间:2014-09-23 09:24:25

标签: android bitmap upload

我有java类android的问题,用于将文件上传到远程服务器。

在表单中,我在智能手机上的图库图像上选择文件,但位图的输出始终显示为null,表单开始被阻止。

Log.d("HomeActivity.class", "Output: " + bitmap);

这开始让我相信我的整体结构是不正确的。

我错过了什么?

代码有什么问题?

我非常感谢您在解决这个问题时能给我的任何帮助。

public class HomeActivity extends Activity {

    Button btnSend;
    Spinner area;
    EditText description;
    ImageView viewImage;
    Button b, upload;
    Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        b = (Button) findViewById(R.id.btnSelectPhoto);
        viewImage = (ImageView) findViewById(R.id.viewImage);
        upload = (Button) findViewById(R.id.button1);
        area = (Spinner) findViewById(R.id.my_spinner_new);
        description = (EditText) findViewById(R.id.editText);

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

        upload.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                if (area.getSelectedItem().toString().trim()
                        .equalsIgnoreCase("Select area")) {
                    Toast.makeText(HomeActivity.this, "Area.",
                            Toast.LENGTH_SHORT).show();
                } else if (description.getText().toString().length() <= 0) {
                    description.setError("description");
                } else if (bitmap == null) {
                    Toast.makeText(getApplicationContext(),
                            "pic", Toast.LENGTH_SHORT)
                            .show();
                    Log.d("HomeActivity.class", "Output: " + bitmap);
                } else {
                    ProgressDialog.show(HomeActivity.this,
                            "Uploading" + bitmap, "Please wait...", true);
                }
            }
        });

        new Thread() {
            @Override
            public void run() {
                String path = "http://localhost/list.txt";
                URL u = null;
                try {
                    u = new URL(path);
                    HttpURLConnection c = (HttpURLConnection) u
                            .openConnection();
                    c.setRequestMethod("GET");
                    c.connect();
                    InputStream in = c.getInputStream();
                    final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                    byte[] buffer = new byte[5120 * 512];
                    in.read(buffer);
                    bo.write(buffer);
                    String s = bo.toString();

                    final Vector<String> str = new Vector<String>();
                    String[] line = s.split("\n");
                    int index = 0;
                    while (index < line.length) {
                        str.add(line[index]);
                        index++;
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Spinner spinner = (Spinner) findViewById(R.id.my_spinner_new);
                            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                    HomeActivity.this,
                                    android.R.layout.simple_spinner_item, str);
                            spinner.setAdapter(adapter);
                            try {
                                bo.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    private void selectImage() {

        final CharSequence[] options = { "Take Photo", "Choose from Gallery",
                "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment
                            .getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                } else if (options[item].equals("Choose from Gallery")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);

                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == 1) {

                File f = new File(Environment.getExternalStorageDirectory()
                        .toString());

                for (File temp : f.listFiles()) {

                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {

                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            bitmapOptions);

                    viewImage.setImageBitmap(bitmap);

                    Log.d("HomeActivity.class", "Valore restituito: " + bitmap);

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System
                            .currentTimeMillis()) + ".jpg");
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {

                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePath,
                        null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.w("path of image from gallery......******************.........",
                        picturePath + "");
                viewImage.setImageBitmap(thumbnail);
            }
        }
    }
}

修改#1

upload.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {

        if (area.getSelectedItem().toString().trim()
                .equalsIgnoreCase("Select area")) {
            Toast.makeText(HomeActivity.this, "Area.",
                    Toast.LENGTH_SHORT).show();
        } else if (description.getText().toString().length() <= 0) {
            description.setError("description");
        } else if (bitmap == null) {
            Toast.makeText(getApplicationContext(),
                    "pic", Toast.LENGTH_SHORT)
                    .show();
            Log.d("HomeActivity.class", "Output: " + bitmap);
        } else {
            ProgressDialog.show(HomeActivity.this,
                    "Uploading" + bitmap, "Please wait...", true);
        }
    }
});

1 个答案:

答案 0 :(得分:0)

您正在onCreate中启动上传线程。因此位图为空。最好在onClick处理程序中启动你的线程。

顺便说一下:Log.d("HomeActivity.class", "Output: " + bitmap);。尝试打印位图非常糟糕。如果要检查位图是否为空,请执行以下操作:

 if ( bitmap==null )
     Log.d(TAG, "bitmap==null");
 else
     Log.d(TAG, "we have a nice bitmap");