java - 执行 textView 命令时应用程序崩溃
问题描述
我的 android 应用程序应该通过套接字将图像发送到本地 java 服务器,处理图像后,结果必须再次发送到应用程序,我应该在文本视图中显示它。我已成功收到结果,但当我尝试在文本视图中显示结果时,应用程序崩溃并显示以下错误。
错误:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void java.text.BreakIterator.setText(java.lang.String)”
我是 Android 编程新手。我尝试了很多事情,但无法解决。请帮助我!提前致谢!
代码:主要活动
package com.example.image1;
import android.app.Activity;
import android.app.MediaRouteButton;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
import java.util.Objects;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
private static final int GET_PICTURE =1 ;
private PrintWriter printwriter;
public static String selectedImagePath;
public static String selectedImageUri;
private ImageView img;
public static String st;
TextView status1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("34");
img = (ImageView) findViewById(R.id.ivPic);
System.out.println("36");
Button send = (Button) findViewById(R.id.bSend);
//status = (TextView) findViewById(R.id.tvStatus);
status1 = (TextView) findViewById(R.id.result);
((Button) findViewById(R.id.bBrowse))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
System.out.println("40");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
System.out.println("47");
}
});
;
System.out.println("51");
//status1.setText("fjfjf");
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//status1.setText("fjfjf");
new SendImageTask().execute();
//final TextView status1 = (TextView) findViewById(R.id.result);
//status1.setText(s);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
}
SendImageTask code
package com.example.image1;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
class SendImageTask extends AsyncTask<Void, Void, String> {
private PrintWriter printwriter;
private Bitmap IOUtils;
private BreakIterator status1;
private static String st;
@SuppressLint("WrongThread")
@Override
protected String doInBackground(Void... voids) {
Socket sock;
try {
sock = new Socket("192.168.43.120", 8000);
System.out.println("Connecting...");
System.out.println("Sending...");
String s = getFileToByte(MainActivity.selectedImagePath);
System.out.println(s);
printwriter = new PrintWriter(sock.getOutputStream(), true);
printwriter.write(String.valueOf(s)); // write the message to output stream
printwriter.flush();
printwriter.close();
sock.close();
try {
System.out.println("Another socket");
Socket sock1 = new Socket("192.168.43.120", 6000);
System.out.println("Connecting1...");
InputStreamReader streamReader = new InputStreamReader(sock1.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
System.out.println(st);
System.out.println("ascscasc");
sock1.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
}
protected void onPostExecute(String st){
System.out.println("asasdcwdcwdc");
System.out.println(st);
status1.setText(String.valueOf(st));
}
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
String str1=encodeString.replaceAll("[\r\n]+", " ");
str1 = str1.replaceAll("\\s+","");
return "data:image/jpeg;base64,"+str1+"/n";
}
}
首先我的应用程序崩溃了,因为我在 doInBackground 方法中执行 textView 操作,然后我才知道无法在那里完成 ui 操作。然后我在 onPostExecute 方法中执行了这些命令。但是我的应用程序仍然崩溃说 NullPointerException。我还将在此处包含 logcat。提前致谢。
日志猫:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.image1, PID: 20241
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:147)
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:19)
at android.os.AsyncTask.finish(AsyncTask.java:667)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:186)
at android.app.ActivityThread.main(ActivityThread.java:6509)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:804)
I/Process: Sending signal. PID: 20241 SIG: 9
解决方案
您需要初始化您的BreakIterator
对象status1
,否则它将为空。
我没有使用过 BreakIterator,但快速查看文档表明这是获取实例的方式。
BreakIterator status1 = BreakIterator.getWordInstance();
底线是在使用它之前对其进行初始化。
推荐阅读
- scala - sbt 目录结构的变体
- reactjs - 优化由反应脚本生成的包大小所需的建议
- google-maps - 带有 zIndex 的 Flutter Google-Map Markers 不能可靠地工作
- python - 从字符串和列表的元组中将所有值作为字符串返回
- angular - 何时使用 zone.run()?
- swift - 自定义操作按钮未显示远程通知
- unity3d - 为什么我在统一构建 android 后会提醒保护?
- html - 动态增加 div 的高度正在为同级 div 创造空间
- javascript - 期望中间件函数调用下一个函数或发送 http 400 代码
- c# - 价值任务
和异步状态机