尝试压缩位图时出现空指针异常,因此我可以将其发送到 ByteArrayOutputStream 以获取字节数组。我需要这个字节数组,这样我就可以将图像作为 ParseFile 上传到我的 Parse 数据库。日志错误如下所示。
01-11 23:29:41.522 32015-32015/com.example.whhsfbla.fashionnow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.whhsfbla.fashionnow, PID: 32015
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at com.example.whhsfbla.fashionnow.PostActivity.uploadPost(PostActivity.java:140)
at com.example.whhsfbla.fashionnow.PostActivity.access$100(PostActivity.java:34)
at com.example.whhsfbla.fashionnow.PostActivity$2.onClick(PostActivity.java:92)
at android.view.View.performClick(View.java:5254)
at android.view.View$PerformClick.run(View.java:21179)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6837)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
导致错误的行是 bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
public class PostActivity extends Activity {
private final int SELECT_PHOTO = 1;
private InputStream imageStream;
private Uri uploadFileUri;
private Bitmap bitmap;
private TextView txtPostTitle;
private EditText editText;
private Button btnChoosePic, btnUploadPost;
private ImageView imgPreview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
txtPostTitle = (TextView) findViewById(R.id.txtPostTitle);
editText = (EditText) findViewById(R.id.editText);
btnChoosePic = (Button) findViewById(R.id.btnChoosePic);
btnUploadPost = (Button) findViewById(R.id.btnMakePost);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
txtPostTitle.setText("Title:");
btnChoosePic.setText("Choose Picture");
btnUploadPost.setText("Create Post");
btnUploadPost.setEnabled(false);
/*btnChoosePic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
openImageIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
}); */
btnChoosePic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
openImageIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
});
btnUploadPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadPost();
finish();
}
});
}
private void openImageIntent() throws IOException {
final File root = new File(Environment.getExternalStorageDirectory() +
File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fileName = File.createTempFile("tmp", ".txt").getPath();
final File sdImageMainDirectory = new File(root, fileName);
uploadFileUri = Uri.fromFile(sdImageMainDirectory);
//Camera
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : resolveInfoList) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uploadFileUri);
cameraIntents.add(intent);
}
//Filesystem
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, SELECT_PHOTO);
}
private void uploadPost() {
// Locate the image in res > drawable-hdpi
bitmap = BitmapFactory.decodeResource(getResources(), R.id.imgPreview);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("image.png",image);
// Upload the image into ParseCloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject post = new ParseObject("Post");
// Create a column named "ImageName" and set the string
post.put("title", editText.getText().toString());
// Create a column named "ImageFile" and insert the image
post.put("ImageFile", file);
post.put("user", User.username);
// Create the class and the columns
post.saveInBackground();
// Show a simple toast message
Toast.makeText(PostActivity.this, "Post Uploaded",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageIntent) {
super.onActivityResult(requestCode, resultCode, imageIntent);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PHOTO) {
//Get the URI
final boolean isCamera;
if (imageIntent == null) {
isCamera = true;
} else {
final String action = imageIntent.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = uploadFileUri;
} else {
selectedImageUri = imageIntent == null ? null : imageIntent.getData();
}
//Get the Bitmap from the URI, and set it to the ImageView
try {
imageStream = getContentResolver().openInputStream(selectedImageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imgPreview.setImageBitmap(selectedImage);
btnUploadPost.setEnabled(true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
最佳答案
因为 bitmap 是空的,所以你得到一个空指针异常。替换行
bitmap = BitmapFactory.decodeResource(getResources(), R.id.imgPreview);
有了这个
bitmap = ((BitmapDrawable) imgPreview.getDrawable()).getBitmap();
关于android - 尝试压缩位图时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735726/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案
SPI接收数据左移一位问题目录SPI接收数据左移一位问题一、问题描述二、问题分析三、探究原理四、经验总结最近在工作在学习调试SPI的过程中遇到一个问题——接收数据整体向左移了一位(1bit)。SPI数据收发是数据交换,因此接收数据时从第二个字节开始才是有效数据,也就是数据整体向右移一个字节(1byte)。请教前辈之后也没有得到解决,通过在网上查阅前人经验终于解决问题,所以写一个避坑经验总结。实际背景:MCU与一款芯片使用spi通信,MCU作为主机,芯片作为从机。这款芯片采用的是它规定的六线SPI,多了两根线:RDY和INT,这样从机就可以主动请求主机给主机发送数据了。一、问题描述根据从机芯片手
我正在使用Postgres.app在OSX(10.8.3)上。我已经修改了我的PATH,以便应用程序的bin文件夹位于所有其他文件夹之前。Rammy:~phrogz$whichpg_config/Applications/Postgres.app/Contents/MacOS/bin/pg_config我已经安装了rvm并且可以毫无错误地安装pggem,但是当我需要它时我得到一个错误:Rammy:~phrogz$gem-v1.8.25Rammy:~phrogz$geminstallpgFetching:pg-0.15.1.gem(100%)Buildingnativeextension