java - 当我将正在开发的应用程序下载到智能手机时,我看不到一些文字
问题描述
我目前正在开发一个将图像文件传送到服务器的活动。但是,在测试过程中,我可以在 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,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", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, 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, 0, bufferSize);
Log.d("Test", "image byte is " + bytesRead);
// read image
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = mFileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = mFileInputStream.read(buffer, 0, 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);
}
}
}
解决方案
推荐阅读
- selenium - 如何在众多元素中点击少数已启用的元素
- git - 使用一个远程管理两个本地 GIT 存储库
- excel - 复制/粘贴范围不相同:错误...为什么会这样?
- python - 读取 Json 文件并将其转换为 python 中的列
- android - 在哪里可以找到有关 android 特定权限的更多信息
- r - 在 R 中安装 tidyverse 时出现问题
- php - php max_execution_time 实际测量的是什么?
- python - 为什么我需要多对一关系的关系和外键?
- wpf - Azure SQL 服务器防火墙规则不适用于我的 WPF 应用程序
- subquery - 联合 MDX 中的两个子选择