问题描述
我目前正在开发一项将图像文件传送到服务器的活动。但是,在测试过程中,我可以在AVD中很好地看到文本,但是在我的智能手机上下载并运行它时却看不到一些文本。
看不见的部分每次运行都是一样的,下图是一样的。
我要开发的屏幕如下。 正如我上面所说,在 AVD 上运行时,它看起来像下面。
下面是xml代码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tempus.ui.boards.WriteActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/layoutborder">
<TextView
android:id="@+id/dayView"
android:layout_width="80dp"
android:layout_height="29dp"
android:text="Write"
android:gravity="center"
android:layout_marginLeft="8dp"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="25dp"/>
<Button
android:id="@+id/changeDisplay"
android:layout_width="128dp"
android:layout_height="41dp"
android:text="Expense list"
android:layout_marginLeft="54dp"
tools:layout_editor_absoluteX="150dp"
android:textSize="12dp"
tools:layout_editor_absoluteY="25dp"/>
<ImageButton
android:id="@+id/addPhoto"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_marginLeft="20dp"
android:src="@mipmap/ic_camera"
android:background="#00ff0000"/>
<Button
android:id="@+id/finButton"
android:layout_width="62dp"
android:layout_height="38dp"
android:text="fin"
android:background="#00ff0000"
android:textColor="#ff50bcdf"
tools:layout_editor_absoluteX="318dp"
tools:layout_editor_absoluteY="16dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/layoutborder4"
android:layout_marginTop="5dp">
<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:text="Date Created"
android:layout_gravity="center"
android:gravity="center"
android:background="@drawable/layoutborder4"/>
<EditText
android:id="@+id/dateEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/layoutborder4">
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:text="Share Settings"
android:gravity="center"
android:background="@drawable/layoutborder4"/>
<RadioGroup
android:id="@+id/radioGroup"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="@+id/allShareRadioButton"
android:text="Share with all acquaintances"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<RadioButton
android:id="@+id/partShareRadioButton"
android:text="Share with specific groups"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<RadioButton
android:id="@+id/nonShareRadioButton"
android:text="Do not share"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RadioGroup>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="30dp"
android:text="content"
android:gravity="center"
android:layout_marginTop="5dp"
android:background="@drawable/layoutborder4"/>
<EditText
android:id="@+id/contentEdit"
android:layout_width="match_parent"
android:layout_height="200dp"
android:gravity="start|top"
android:background="@drawable/layoutborder4"/>
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:text="Photos attached"
android:gravity="center"
android:layout_marginTop="2dp"
android:background="@drawable/layoutborder4"/>
<ImageView
android:id="@+id/userImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:maxWidth="200dp"
android:maxHeight="200dp"
android:adjustViewBounds="true"
android:src="@mipmap/imageborder"/>
</LinearLayout>
这是java代码。
public class WriteActivity extends AppCompatActivity {
private static final int MY_PERMISSION_CAMERA = 1111;
private static final int REQUEST_TAKE_PHOTO = 2222;
private static final int REQUEST_TAKE_ALBUM = 3333;
private static final int REQUEST_IMAGE_CROP = 4444;
Button changeDisplay;
ImageButton addPhoto;
Button finButton;
EditText dateEdit;
EditText contentEdit;
String mCurrentPhotoPath;
Uri imageUri;
Uri photoURI,albumURI;
ImageView userImage;
RadioGroup radioGroup;
String WR_date,WR_body;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
// Disable StrictMode
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitDiskReads()
.permitDiskWrites()
.permitNetwork().build());
changeDisplay = findViewById(R.id.changeDisplay);
changeDisplay.setOnClickListener(view -> {
Intent intent = new Intent(getApplicationContext(),ExpenditureBreakdownActivityForWrite.class);
startActivity(intent);
});
userImage = findViewById(R.id.userImage);
addPhoto = findViewById(R.id.addPhoto);
addPhoto.setOnClickListener(v -> {
// file search
getAlbum();
});
dateEdit = findViewById(R.id.dateEdit);
contentEdit = findViewById(R.id.contentEdit);
finButton = findViewById(R.id.finButton);
finButton.setOnClickListener(view -> {
JSONObject jsonObject = new JSONObject();
JSONObject head = new JSONObject();
JSONObject body = new JSONObject();
String headjson = null;
String bodyjson = null;
WR_date = dateEdit.getText().toString();
WR_body = contentEdit.getText().toString();
String urIString = "http://***.***.*.*/addboard"; // This is what ip came out of,so change to *marking
DoFileUpload(urIString,getAbsolutePath(photoURI));
try {
head.put("WR_ID","1");
head.put("WR_TYPE","A");
jsonObject.put("head",head);
headjson = jsonObject.toString();
body.put("WR_DATE",WR_date);
body.put("WR_BODY",WR_body);
jsonObject.put("body",body);
bodyjson = jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
if (dateEdit.getText().length() == 0 || contentEdit.getText().length() == 0) {
Toast.makeText(WriteActivity.this,"There is no written date or content.",Toast.LENGTH_SHORT).show();
return;
}
Log.e("json","Generated json : " + jsonObject.toString());
String[] params = {headjson,bodyjson};
PostTask Write = new PostTask();
Write.execute(params);
Intent baIntent = new Intent(WriteActivity.this,boardActivity.class);
baIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
WriteActivity.this.finish();
startActivity(baIntent);
});
radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(radioGroupButtonChangeListener);
checkPermission();
}
public void DoFileUpload(String apiUrI,String absolutePath){
HttpFileUpload(apiUrI,"",absolutePath);
}
private String getAbsolutePath(Uri contentUri){
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri,proj,null,null);
cursor.moveToFirst();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
return cursor.getString(column_index);
}
private void captureCamera(){
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e("captureCamera Error",ex.toString());
}
if (photoFile != null) {
Uri providerURI = FileProvider.getUriForFile(this,getPackageName(),photoFile);
imageUri = providerURI;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,providerURI);
startActivityForResult(takePictureIntent,REQUEST_TAKE_PHOTO);
}
}
} else {
Toast.makeText(this,"Storage is not accessible.",Toast.LENGTH_SHORT).show();
return;
}
}
public File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + ".jpg";
File imageFile = null;
File storageDir = new File(Environment.getExternalStorageDirectory() + "/Pictures","photos");
if (!storageDir.exists()) {
Log.i("mCurrentPhotoPath1",storageDir.toString());
storageDir.mkdirs();
}
imageFile = new File(storageDir,imageFileName);
mCurrentPhotoPath = imageFile.getAbsolutePath();
return imageFile;
}
private void getAlbum(){
Log.i("getAlbum","Call");
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
startActivityForResult(intent,REQUEST_TAKE_ALBUM);
}
private void galleryAddPic(){
Log.i("galleryAddPic","Call");
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
Toast.makeText(this,"The photo has been saved to the album.",Toast.LENGTH_SHORT).show();
}
public void cropImage(){
Log.i("cropImage","Call");
Log.i("cropImage","photoURI : " + photoURI + " / albumURI : " + albumURI);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
cropIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
cropIntent.setDataAndType(photoURI,"image/*");
cropIntent.putExtra("aspectX",1);
cropIntent.putExtra("aspectY",1);
cropIntent.putExtra("scale",true);
cropIntent.putExtra("output",albumURI);
startActivityForResult(cropIntent,REQUEST_IMAGE_CROP);
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode,resultCode,data);
switch (requestCode) {
case REQUEST_TAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
try {
Log.i("REQUEST_TAKE_PHOTO","OK");
galleryAddPic();
userImage.setImageURI(imageUri);
} catch (Exception e) {
Log.e("REQUEST_TAKE_PHOTO",e.toString());
}
} else {
Toast.makeText(WriteActivity.this,"Canceled taking a picture.",Toast.LENGTH_SHORT).show();
}
break;
case REQUEST_TAKE_ALBUM:
if (resultCode == Activity.RESULT_OK) {
if (data.getData() != null) {
try {
File albumFile = null;
albumFile = createImageFile();
photoURI = data.getData();
albumURI = Uri.fromFile(albumFile);
cropImage();
} catch (Exception e) {
Log.e("TAKE_ALBUM_SINGLE ERROR",e.toString());
}
}
}
break;
case REQUEST_IMAGE_CROP:
if (resultCode == Activity.RESULT_OK) {
galleryAddPic();
userImage.setImageURI(albumURI);
}
break;
}
}
private void checkPermission(){
if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Notification")
.setMessage("Storage permission denied. If you want to use it,you must allow the permission directly in the settings.")
.setNeutralButton("setting",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
})
.setPositiveButton("Check",int i) {
finish();
}
})
.setCancelable(false)
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSION_CAMERA);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_CAMERA:
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] < 0) {
Toast.makeText(WriteActivity.this,"You need to activate the permission.",Toast.LENGTH_SHORT).show();
return;
}
}
break;
}
}
RadioGroup.OnCheckedChangeListener radioGroupButtonChangeListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup,@IdRes int i) {
if(i == R.id.allShareRadioButton){
Toast.makeText(WriteActivity.this,"Share with all your acquaintances",Toast.LENGTH_SHORT).show();
}
else if(i == R.id.partShareRadioButton){
Toast.makeText(WriteActivity.this,"Share with specific groups",Toast.LENGTH_SHORT).show();
}
else if(i == R.id.nonShareRadioButton){
Toast.makeText(WriteActivity.this,"Not to share",Toast.LENGTH_SHORT).show();
}
}
};
public void HttpFileUpload(String urlString,String params,String fileName) {
try {
FileInputStream mFileInputStream = new FileInputStream(fileName);
URL connectUrl = new URL(urlString);
Log.d("Test","mFileInputStream is " + mFileInputStream);
// open connection
HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
// write data
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName+"\"" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = mFileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable,maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = mFileInputStream.read(buffer,bufferSize);
Log.d("Test","image byte is " + bytesRead);
// read image
while (bytesRead > 0) {
dos.write(buffer,bufferSize);
bytesAvailable = mFileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = mFileInputStream.read(buffer,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Test","File is written");
mFileInputStream.close();
dos.flush(); // finish upload...
// get response
int ch;
InputStream is = conn.getInputStream();
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){
b.append( (char)ch );
}
String s=b.toString();
Log.e("Test","result = " + s);
dos.close();
} catch (Exception e) {
Log.d("Test","exception " + e.getMessage());
}
}
private class PostTask extends AsyncTask<String,Void,String> {
protected String doInBackground(String... params) {
//String hjson = params[0];
String bjson = params[1];
try {
String host_url = "http://***.***.**.***/addboard"; // This is what ip came out of,so change to *marking
URL url = new URL(host_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(15*1000);//Timeout setting
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());
streamWriter.write(bjson);
streamWriter.flush();
streamWriter.close();
int responsecode = conn.getResponseCode();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)