ArrayIndexOufofBoundExceptin in zipping file by android programming - java

I am newbie in android programming, Currently i am trying to do zipping multiple files in android. in my SD card a zipfile is created but it has no files inside and 0.00 byte showing . In logcat i have got some exception like
java.lang.ArrayIndexOutOfBoundsException: length=2040; regionStart=0; regionLength=-1
at java.util.Arrays.checkOffsetAndCount(Arrays.java:1732)
Here is my code
package com.example.zipfile;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import android.util.Log;
public class CompressFile
{
public static final int Buffer=2040;
public String[]localfiles;
public String zippedFile;
public CompressFile(String[]localfileset,String zipFileset)
{
// TODO Auto-generated constructor stub
this.localfiles=localfileset;
this.zippedFile= zipFileset;
}
public void zip()
{
try
{
BufferedInputStream bufferstream=null;
FileOutputStream fileout=new FileOutputStream(zippedFile);
ZipOutputStream zipout=new ZipOutputStream(new BufferedOutputStream(fileout));
byte[]data=new byte[Buffer];
for(int i=0;i<localfiles.length;i++)
{
Log.d("add",localfiles[i]);
Log.v("Compress","AddingFiles:"+ localfiles[i]);
FileInputStream fileinput=new FileInputStream(localfiles[i]);
bufferstream=new BufferedInputStream(fileinput,Buffer);
ZipEntry zipentry=new ZipEntry(localfiles[i].substring(localfiles[i].lastIndexOf("/")+1));
zipout.putNextEntry(zipentry);
int count;
while((count=bufferstream.read(data,0,Buffer))!=-1);
{
zipout.write(data,0,count);
}
bufferstream.close();
}
zipout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
and my MainActvity code
package com.example.zipfile;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[]filelist=new String[2];
String path=Environment.getExternalStorageDirectory().getPath();
filelist[0]=path+"/facebooklogo1.png";
filelist[1]=path+"/formpicture.jpg";
CompressFile compress=new CompressFile(filelist,path+"/Testzip.zip");
compress.zip();
}
#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);
}
}
i am not getting why it is happening , A help is appreciated
Thanks in advance

1) Check file path
2) localfiles[i].substring(localfiles[i].lastIndexOf("/")+1) this should be unique entry for Zip file.
`
byte[] data = new byte[4096];
// Read bytes from packed file and store them in the ZIP output stream
int bytesNum;
while ((bytesNum = bufferstream.read(data)) > 0) {
zipout.write(data, 0, bytesNum);
}
`

i have re modified my code i didn't buffredInputStream this time thanks rahul for your suggestion . Here is my code its working
package com.example.ziptest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
String path= Environment.getExternalStorageDirectory().getPath();// stating relative path of SD card rather than hard coded path
String zipfile=path+File.separator+"Filekb.zip"; // the new compressed file with its path
String storagefile1=path+File.separator+"facebooklogo1.png"; // local file which is going to be compressed
String storagefile2=path+File.separator+"formpicture.jpg"; // second local file which is going to be compressed
String[]storagefiles= {storagefile1,storagefile2};// put this local files in a array
public byte[]buffer=new byte[2040]; // create buffer
FileInputStream fileinput;
FileOutputStream fileoutput;
ZipOutputStream zipout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
zip();
}
#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);
}
public void zip()
{
try
{
fileoutput=new FileOutputStream(zipfile);
zipout =new ZipOutputStream(fileoutput);
for(int i=0;i<storagefiles.length;i++)
{
File storagefileindex=new File(storagefiles[i]);
Log.d("Add", storagefiles[i]);
Log.v("compressing","Adding"+storagefiles[i]);
fileinput=new FileInputStream(storagefileindex);
zipout.putNextEntry(new ZipEntry(storagefileindex.getName()));
int bytecount;
while((bytecount= fileinput.read(buffer))>0)
{
zipout.write(buffer,0,bytecount);
}
zipout.closeEntry();
fileinput.close();
}
zipout.close();
}
catch(Exception ioe)
{
Log.d(zipfile, "Error occurs in Creating zip");
}
}
}

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);
}
}

Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
MainActivity.java has following code:
package com.softjourn.redmineclient.activities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.softjourn.redmineclient.R;
import com.softjourn.redmineclient.models.Issue;
import com.softjourn.redmineclient.models.IssuesResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
private final static String URI="https://redmineng.softjourn.if.ua/issues.json?assigned_to_id=me";
#Bind(R.id.list_issues) ListView mListIssues;
Login li;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
li = new Login();
li.execute(URI);
}
#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_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class Login extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(strings[0]).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
c.setUseCaches(false);
try {
c.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("Authorization", "basic " + Base64.encodeToString("osavchak:mhgT7322".getBytes(), 0));
try {
c.connect();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader((c.getInputStream())));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String output;
try {
while ((output = br.readLine()) != null) {
sb.append(output);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JsonArray ja = new JsonParser().parse(result).getAsJsonObject().getAsJsonArray("issues");
IssuesResponse ir = new IssuesResponse(ja);
ArrayAdapter<Issue> adapter = new ArrayAdapter<Issue>(MainActivity.this, android.R.layout.simple_list_item_1, ir.getIssues());
mListIssues.setAdapter(adapter);
}
}
}
I've created two model classes.
First, IssuesResponse.java:
package com.softjourn .redmineclient.models;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class IssuesResponse {
#SerializedName("issues")
private List<Issue> issues;
public IssuesResponse(JsonArray ja) {
if (issues == null) {
}
for(JsonElement je : ja) {
Issue issue = new Issue(je);
issues.add(issue);
}
}
public List<Issue> getIssues() {
return issues;
}
}
The second one, Issue.java:
package com.softjourn.redmineclient.models;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
public class Issue {
#SerializedName("id")
private int id;
#SerializedName("description")
private String description;
public Issue(JsonElement je) {
Issue issue = new Gson().fromJson(je,Issue.class);
this.id = issue.id;
this.description = issue.description;
}
}
When I run my application an error occurs:
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at com.softjourn.redmineclient.models.IssuesResponse.(IssuesResponse.java:26)
at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:125)
at com.softjourn.redmineclient.activities.MainActivity$Login.onPostExecute(MainActivity.java:79)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I wait for your suggestions how it could be fixed.
You haven't initialised List<Issue> in the IssuesResponse class. Try
private List<Issue> issues = new ArrayList<>();

how to write array into android file in the internal storage

I'm newbie at developing android application, so I am making this simple application to save a list of data that user input and able to read it as a list later on. I am able to write user input into a file, but every i input another list, it overwrite the first one, what I want is to add this in the file, and call the list as array to be displayed as a list. How do I write an array or achieve this ? Here's the code :
package com.example.storage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et;
private EditText st;
private String data;
private String file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText)(findViewById(R.id.editText1));
st = (EditText)(findViewById(R.id.showText1));
}
public void save(View view) {
data = et.getText().toString();
file = st.getText().toString();
try {
FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved",
Toast.LENGTH_SHORT).show();
} catch (Exception e){
//TODO Auto-generated catch block
e.printStackTrace();
}
}
public void read(View view) {
file = st.getText().toString();
try {
FileInputStream fin = openFileInput(file);
int c;
String temp = "";
while( (c = fin.read()) != -1) {
temp = temp + Character.toString((char)c);
}
et.setText(temp);
Toast.makeText(getBaseContext(),"file read",
Toast.LENGTH_SHORT).show();
} catch(Exception e) {
}
}
#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);
}
}
Any help greatly appreciated. Thank you in advance.
what about using FileWriter(File file, boolean append) in "append" mode? Have a look here: How to append to a text file in android?
Try it like that:
File f = new File(pathToUrFile);
FileWriter fw = new FileWriter(file, true);
fw.append();
If you are going to save more (and different) values give gson a try to save and load vars or even classes from text files.
Best regards!

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.

Object is not writing to file triggering FileNotFoundException

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

Categories