Object is not writing to file triggering FileNotFoundException - java

When I try to write the file, it does not want to write a new file. The FileNotFoundException occurs when the app tries to write to the file. I have seen this code working here: https://www.youtube.com/watch?v=YzwiuRDgSSY
package com.example.serialization;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.UUID;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
TextView label;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Person arthur = new Person();
arthur.name = "Arthur Dent";
arthur.age = 44;
label = (TextView) findViewById(R.id.textView1);
label.setText("Nothing here");
String fileName = "data.txt";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
os.writeObject(arthur);
os.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
label.setText("File not found");
}
catch (IOException e) {
// TODO Auto-generated catch block
label.setText("IOException");
e.printStackTrace();
}
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(fileName));
Person p = (Person) is.readObject(); // read object
label.setText("Show name: " + p.name + " Show age: " + p.age);
is.close();
}
catch (StreamCorruptedException e) {
label.setText("Stream corrupted");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (FileNotFoundException e) {
label.setText("File not found 2");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
label.setText("IOException");
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
label.setText("Class not found");
// TODO Auto-generated catch block
e.printStackTrace();
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Person.java
package com.example.serialization;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2794858669568274884L;
public String name;
public int age;
//streams are not Serializable
public ObjectOutputStream os;
}

Try this:
File outputFile = new File(getFilesDir(), fileName);
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(outputFile));
os.writeObject(arthur);

The example video is for desktop java, where you can normally write files without specifying a path. However on Android you should always specify one - you can use internal storage or external storage. Here's the Android guide on how to write files to internal storage: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Related

Issue with Http Client in android studio

I am new to android app development, and one of my clients asked me to fix this code his past dev left the job . there were a lot of errors I was able to fix it. But now I am stuck at a point in HTTP request error in java and cannot execute this code. Let me know how to fix it. Current status complied SDK 33 and cannot downgrade the same. Code below. HTTP client is deprecated.
package com.ecom.ecommerce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActivityCategoryList extends Activity {
GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;
// declare adapter object to create custom category list
AdapterCategoryList cla;
// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String CategoryAPI;
int IOConnect = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new
ColorDrawable(getResources().getColor(R.color.header)));
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setTitle("Category");
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listCategory = (GridView) findViewById(R.id.listCategory);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new AdapterCategoryList(ActivityCategoryList.this);
// category API url
CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle list when clicked
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu page
Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
iMenuList.putExtra("category_id", Category_ID.get(position));
iMenuList.putExtra("category_name", Category_name.get(position));
startActivity(iMenuList);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});
}
#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_category, 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.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case R.id.refresh:
IOConnect = 0;
listCategory.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// clear arraylist variables before used
void clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data on list
// otherwise, show alert text
if((Category_ID.size() > 0) && (IOConnect == 0)){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from Category API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject category = object.getJSONObject("Category");
Category_ID.add(Long.parseLong(category.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//cla.imageLoader.clearCache();
listCategory.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
}

How can I make this app more efficient?

I have the following code which is working without any errors, but I get this
Skipped 116 frames. The application may be doing too much work on its main thread.
That happens when I press the Single button and the init() method is executed.
How can I execute the method in another thread so it won't break like that ?
package com.apppppp.pampam;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Set;
import android.support.v7.app.ActionBarActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button singleButton;
BluetoothAdapter mBluetoothAdapter;
BluetoothAdapter blueAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
blueAdapter = BluetoothAdapter.getDefaultAdapter();
singleButton = (Button) findViewById(R.id.button1);
setButtonOnClickListeners();
return true;
}
private void setButtonOnClickListeners(){
singleButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
try {
write("Salut");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("No luck");
}
}
});
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
System.out.println(bondedDevices);
if(bondedDevices.size() > 0){
Iterator iter = bondedDevices.iterator();
BluetoothDevice device = (BluetoothDevice) iter.next();
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
else{
Log.e("error", "No appropriate paired devices.");
}
}else{
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException{
init();
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thank you
You are doing the Bluetooth related calls on the UI thread and you blocking the UI thread with these calls.

Writing multiple strings to file in android

I am looking to write multiple strings to file for storage using android. Is it possible to add all strings to a toString using .getText and if so how. I am looking to create some edit text fields and take the information contained in these fields and write them to a file before then reading the file in a different activity. Any help would be greatly appreciated.
Here is my code so far if it is any help:
package app.project.newapp;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class AddActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
}
public void saveClick(String filename, EditText v){
EditText name = (EditText) findViewById(R.id.namet);
EditText tel = (EditText) findViewById(R.id.emerg_tel);
EditText cond = (EditText) findViewById(R.id.conditions);
EditText other = (EditText) findViewById(R.id.other);
String userDetails = "Hello_File";
String string = "";
FileOutputStream fos = null;
try {
fos = openFileOutput(userDetails, Context.MODE_PRIVATE);
} catch (FileNotFoundException e){
e.printStackTrace();
}
try {
string=name.getText().toString();
string=tel.getText().toString();
string=cond.getText().toString();
string=other.getText().toString();
fos.write(string.getBytes());
} catch (IOException e){
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("hello_file")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
} catch(IOException e) {
e.printStackTrace();
}//end catch
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this in your saveClick method, in the second try:
try {
string=name.getText().toString() + "\n"
+ tel.getText().toString() + "\n"
+ cond.getText().toString() + "\n"
+ other.getText().toString();
fos.write(string.getBytes());
} catch(IOException e) {
e.printStackTrace();
}

Null Pointer Exception in FileOutputStream [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to run a simple program using FileOutputStream. When I run this program the application show a message " Application stoppped unfortunately". Logcat shows NullPointerException. what is wrong with my code??
package com.example.storageinternal;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editname,editemail;
private Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editname = (EditText)findViewById(R.id.editname);
editemail = (EditText)findViewById(R.id.editemail);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
// TODO Auto-generated method stub
String namestring = editname.getText().toString();
String emailstring = editemail.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput("Mystorage",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(namestring.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(emailstring.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (fos != null) {
try {
fos.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Missing your Button initialization in your onCreate().
Just initialize your Button before implementing the onClickListener of it.
Button save=(Button)findViewById(R.id.button);
Try this..
You have not initialize your save Button
save = (Button) findViewById(R.id.buttonid);
before save.setOnClickListener(new OnClickListener() {
your save Button is null then you are trying to use it as save.setOnClickListener that time you will get NPE
save.setOnClickListener(new OnClickListener() {
Move this line into the OnCreate function and before that intitialize save Button.

Android USB to Serial Receive Error

I'm currently working on writing an App on Android to interface with an Arduino Board. I am able to send serial data to my Arduino just fine, however my app crashes at start up the moment I begin trying to receive data.
I currently have it set so a text field takes data from a user, and sends to the Arduino, Arduino does a function.
For my receive, I am making a new thread at start up to constantly listen for data from the Arduino. whenever the code in this thread is executed, it crashes.
I am using this library as my basis: https://github.com/mik3y/usb-serial-for-android
Below is the all the code pertinent, omitted code for other functionality this app is providing, that are unrealted:
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import android.hardware.usb.UsbManager;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Context;
import android.util.Log;
import com.hoho.android.usbserial.driver.UsbSerialProber;
public class MainActivity extends Activity implements SensorEventListener, LocationListener{
private EditText sendTextField;
TextView uartRX;
public Handler Handler;
UsbManager manager;
/** Called to create application activity*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uartRX = (TextView)findViewById(R.id.rxUART);
sendTextField = (EditText) findViewById(R.id.sendTextField);
Handler = new Handler() {
#Override public void handleMessage(Message msg) {
String text = (String)msg.obj;
uartRX.append(text);
}
};
Thread t = new Thread(new Runnable() {
public void run()
{
Message msg = new Message();
msg.obj = "Start Serial Listen\n";
Handler.sendMessage(msg);
rxUART();
}
public void rxUART()
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbSerialDriver rxDriver = UsbSerialProber.acquire(manager);
if (rxDriver != null) {
try {
rxDriver.open();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
int byteSize = 0;
String data = "";
while(true)
{
byte[] arr = null;
try {
rxDriver.setBaudRate(115200);
rxDriver.read(arr, byteSize);
data = new String(arr);
Message msg = new Message();
msg.obj = data;
Handler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
}
public void sendUART(String data)
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
// Find the first available driver.
UsbSerialDriver driver = UsbSerialProber.acquire(manager);
if (driver != null) {
try {
driver.open();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
driver.setBaudRate(115200);
byte buffer[] = new byte[16];
int numBytesRead = driver.read(buffer, 1000);
Log.d(TAG, "Read " + numBytesRead + " bytes.");
byte temp[] = data.getBytes();
driver.write(temp, 16);
} catch (IOException e) {
// Deal with error.
} finally {
try {
driver.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void onClickSendBtn(View v)
{
String data = "";
data = sendTextField.getText().toString();
sendUART(data);
sendTextField.setText(" ");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Can anyone help me figure out why the app crashes on the code created in the thread?
Note: the code also crashes when not in a thread. Code was originally a function called by sendUART() to check for a response. no while(true) either.
Logcat:
11-02 09:49:22.988: E/AndroidRuntime(22652): FATAL EXCEPTION: Thread-964
11-02 09:49:22.988: E/AndroidRuntime(22652): java.lang.NullPointerException
11-02 09:49:22.988: E/AndroidRuntime(22652): at com.example.sensortest.MainActivity$2.rxUART(MainActivity.java:143)
11-02 09:49:22.988: E/AndroidRuntime(22652): at com.example.sensortest.MainActivity$2.run(MainActivity.java:119)
11-02 09:49:22.988: E/AndroidRuntime(22652): at java.lang.Thread.run(Thread.java:856)
The line numbers referenced are:
Thread t = new Thread(new Runnable() {
public void run()
{
Message msg = new Message();
msg.obj = "Start Serial Listen\n";
Handler.sendMessage(msg);
rxUART();
}
public void rxUART()
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbSerialDriver rxDriver = UsbSerialProber.acquire(manager);
if (rxDriver != null) {
try {
rxDriver.open();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
int byteSize = 0;
String data = "";
while(true)
{
byte[] arr = null;
try {
rxDriver.setBaudRate(115200);
rxDriver.read(arr, byteSize);
data = new String(arr);
Message msg = new Message();
msg.obj = data;
Handler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
You don't handle the case rxDriver == null in rxUart() correctly.
The if() statement skips the open() call only, but the while() loop gets executed with rxDriver being NULL resulting in NPE. You have the same problem in `sendUART(), btw.

Categories