Я изменил приложение anywall, чтобы иметь возможность отправлять фотографии на parse.com. Приложение может отправлять текст и изображения на parse.com, но он падает, и я получаю Java.langNullPointerexception, если я отправляю текст с изображением, чтобы перейти с этим текстом. Я хочу иметь возможность размещать текст с изображениями или без них.Как предотвратить Java.langNullPointerexception При сохранении изображений на parse.com
Вот мой код
// UI references.
private EditText txtEdit_Text;
private TextView txtCharacter_count;
private Button btnPost;
private int maxCharacterCount = Application.getConfigHelper().getPostMaxCharacterCount();
private ParseGeoPoint geoPoint;
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
private static FrameLayout imagePreviewFrame;
private ImageView imgView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
Intent intent = getIntent();
Location location = intent.getParcelableExtra(Application.INTENT_EXTRA_LOCATION);
geoPoint = new ParseGeoPoint(location.getLatitude(), location.getLongitude());
txtEdit_Text = (EditText) findViewById(R.id.txtEdit_Text);
txtEdit_Text.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable s) {
updatePostButtonState();
updateCharacterCountTextViewText();
}
});
txtCharacter_count =(TextView) findViewById(R.id.txtCharacter_count);
btnPost = (Button) findViewById(R.id.btnPost);
btnPost.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
post();
}
});
updatePostButtonState();
updateCharacterCountTextViewText();
imagePreviewFrame = (FrameLayout) findViewById(R.id.image_preview_frame);
imgView = (ImageView) findViewById(R.id.image_preview);
//Capture pic
ImageButton butCamera = (ImageButton) findViewById(R.id.btnCapturePhoto);
butCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
//Open gallery
ImageButton butGallery = (ImageButton) findViewById(R.id.btnupload);
butGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
}
});
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgView.setImageBitmap(decodeFile(selectedImagePath));
imagePreviewFrame.setVisibility(View.VISIBLE);
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imagePreviewFrame.setVisibility(View.VISIBLE);
imgView.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth/scale/2 >= REQUIRED_SIZE
&& o.outHeight/scale/2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaStore.MediaColumns.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
private void post() {
String text = txtEdit_Text.getText().toString().trim();
int Count = 0;
// Set up a progress dialog
final ProgressDialog dialog = new ProgressDialog(PostActivity.this);
dialog.setMessage(getString(R.string.progress_post));
dialog.show();
// Create a post.
HowzitPost post = new HowzitPost();
Long time = System.currentTimeMillis();
Bitmap bitmap = BitmapFactory.decodeFile(getImagePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
byte [] image = stream.toByteArray();
ParseFile file = new ParseFile("images.png",image);
ArrayList<String> arrayList = new ArrayList<>();
String currentuserid = ParseUser.getCurrentUser().getObjectId();
arrayList.add(currentuserid);
post.setLocation(geoPoint);
post.setText(text);
post.setTimestamp(time);
post.setVote(Count);
post.setComments(Count);
post.setUser(ParseUser.getCurrentUser());
post.setlist(arrayList);
post.setPhotoFile(file);
// Set the location to the current user's location
ParseACL acl = new ParseACL();
// Give public read access
acl.setPublicReadAccess(true);
acl.setPublicWriteAccess(true);
post.setACL(acl);
// Save the post change to save in the background
post.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
dialog.dismiss();
finish();
}
});
}
private String getPostEditTextText() {
return txtEdit_Text.getText().toString().trim();
}
private void updatePostButtonState() {
int length = getPostEditTextText().length();
boolean enabled = length > 0 && length < maxCharacterCount;
btnPost.setEnabled(enabled);
}
private void updateCharacterCountTextViewText() {
String characterCountString = String.format("%d/%d", txtEdit_Text.length(), maxCharacterCount);
txtCharacter_count.setText(characterCountString);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_post, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Вот мой XML.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PostActivity" >
<include
android:id="@+id/app_bar"
layout="@layout/toolbar2"/>
<EditText
android:id="@+id/txtEdit_Text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/app_bar"
android:background="@null"
android:hint="@string/prompt_post"
android:inputType="textMultiLine"
android:gravity="top">
<requestFocus />
</EditText>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image_preview_frame"
android:visibility="gone"
android:layout_below="@id/txtEdit_Text"
android:layout_centerInParent="true"
android:layout_margin="5dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/image_preview"
android:layout_below="@id/skootText"
android:scaleType="centerCrop"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:onClick="removeImage"
android:text="x"
android:textSize="22sp"
android:clickable="true"
android:textColor="@color/textColorPrimary"
android:layout_marginRight="5dp"/>
</FrameLayout>
<RelativeLayout
android:id="@+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border"
android:layout_alignParentBottom="true">
<ImageButton
android:id="@+id/btnSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_alignBottom="@+id/btnCapturePhoto"
android:contentDescription="@null"
android:background="?android:selectableItemBackground"
android:src="@drawable/ic_action_settings"/>
<ImageButton
android:id="@+id/btnCapturePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="@null"
android:background="?android:selectableItemBackground"
android:src="@drawable/ic_action_picblue"/>
<ImageButton
android:id="@+id/btnupload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="@+id/btnCapturePhoto"
android:contentDescription="@null"
android:background="?android:selectableItemBackground"
android:src="@drawable/ic_action_vidzb"/>
</RelativeLayout>
</RelativeLayout>
Эй я думаю, что вы забыли сохранить изображение после того, как преобразовать в файл синтаксического анализа. поэтому сначала сохраните ParseFile в фоновом методе, затем сохраните это изображение в основном запросе. –