How can I make this app more efficient? - java

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.

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

ArrayIndexOufofBoundExceptin in zipping file by android programming

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

Why, when touching the Android screen it does nothing?

This is the MainActivity.java
package com.test.webservertest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;
import android.util.AndroidRuntimeException;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.Context;
import android.view.View.OnClickListener;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
private TextView text;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(new SingleTouchEventView(this, null));
/*ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;*/
//addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
/*btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
try
{
} catch (Exception e)
{
text.setText("Connection Failed");
}
}
});*/
}
#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);
}
/**
* Dispatch onStart() to all fragments. Ensure any created loaders are
* now started.
*/
#Override
protected void onStart()
{
super.onStart();
TextToSpeechServer.main(null);
}
#Override
protected void onStop() {
super.onStop();
}
public void initTTS() {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == MY_DATA_CHECK_CODE) {
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
mTts = new TextToSpeech(getApplicationContext(), new OnInitListener() {
#Override
public void onInit(int i) {
if(i == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if(result == TextToSpeech.LANG_AVAILABLE
|| result == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
mTts.setPitch(1);
mTts.speak(textforthespeacch, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
});
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public static String textforthespeacch = "";
public static void TextToSpeak(String text) {
textforthespeacch = text;
}
private boolean is_start = true;
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
private Path circlePath = new Path();
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
canvas.drawPath(circlePath, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (is_start == true)
{
response = Get("http://10.0.0.2:8098/?cmd=start");
is_start = false;
}
else
{
response = Get("http://10.0.0.2:8098/?cmd=stop");
is_start = true;
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
textforthespeacch = a;
MainActivity.currentActivity.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
circlePath.reset();
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
}
It was working fine. Maybe I need to enable something on my Android device?
My Android device is connected now to the PC via USB and working fine.
When I'm running my program in debug mode and touch the screen it never stop on:
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
I added a break point on the line: float eventX = event.getX();
But touching the screen does nothing.
You are not at all registering the OnTouchListener. First register OnTouchListener using anonymousclass or just implements it in your class
From your code you need the listener for this SingleTouchEventView view. Just add "implements View.OnTouchListenter" for the class. Because you have already overridden onTouch method in your code.
You have to change your style.xml when you remove "Extends ActionbarActivity"!
Check this change appTheme

Android Bluetooth Service

I made a program which can connect bluetooth to my device and getting byte from my device.
But the program cannot running in the background.
I only want to get byte in the background.
I made another class which extend Service and trying to make my program run.
public class NickyService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
//Wrong code
MainActivity a1 = new MainActivity();
return START_NOT_STICKY;
}
}
I have no idea with fixing this.
How do I fix this big problem?
The following codes is right!
It can get byte and connect to device,but cannot running in the background!!
MainActivity.java
package com.example.bluetooth10;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
// textview for connection status
ListView pairedListView;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
TextView sensorView0, title_paired_devices;
String paired = "";
Handler bluetoothIn;
private TextView connecting_str;
private TextView textView1;
final int handlerState = 0; // used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private ByteArrayBuffer baf1 = new ByteArrayBuffer(32);
String path = Environment.getExternalStorageDirectory().toString();
private ConnectedThread mConnectedThread;
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // SPP UUID service - this should work for most devices
private static String address; // String for MAC address
protected void onHandleIntent(Intent workIntent) {
// Gets data from the incoming Intent
String dataString = workIntent.getDataString();
// Do work here, based on the contents of dataString
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
title_paired_devices = (TextView) findViewById(R.id.title_paired_devices);
...
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
connecting_str.setText("Connection!!");
byte[] readBuf = (byte[]) msg.obj; // obj = buffer from connect thread
for (int i=0; i<msg.arg1; i++) {
baf1.append((byte)readBuf[i]);
if (baf1.length()>1){
String str1 = String.format("%02X",(byte)baf1.byteAt(baf1.length()-2));
String str2 = String.format("%02X",(byte)baf1.byteAt(baf1.length()-1));
if (str1.equals("01") && str2.equals("FF")){
int tmpb = (byte)baf1.byteAt(13);
baf1.clear();
}
}
}
}
int toInt( byte[] bytes ) {
int result = 0;
for (int i=0; i<bytes.length; i++) {
result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
}
return result;
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
public void onResume() {
super.onResume();
checkBTState();
btAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);//make title viewable
for (BluetoothDevice device : pairedDevices) {
if (!paired.equals("")) paired = paired + ",";
paired = paired + device.getName() + ";" + device.getAddress();
}
} else {
paired = "no devices paired";
}
String str0[] = paired.split(",");
String str1 = str0[0]; //pairedListView.getItemAtPosition(0).toString(); //Get MAC address from DeviceListActivity
String str2[] = str1.split(";");
address = str2[1]; //Get the MAC address from the DeviceListActivty via EXTRA
BluetoothDevice device = btAdapter.getRemoteDevice(address); //create device and set the MAC address
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) { }
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
public void onPause() {
super.onPause();
try {
btSocket.close(); //Don't leave Bluetooth sockets open when leaving activity
} catch (IOException e2) { }
}
private void checkBTState() {
btAdapter = BluetoothAdapter.getDefaultAdapter(); // CHECK THIS OUT THAT IT WORKS!!!
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
finish();
} else {
if (!btAdapter.isEnabled()) {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
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);
}
// ***********************************************************
// create new class for connect thread
// ***********************************************************
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[40]; //The arduino is sending a small amount of data so a large buffer is not needed
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget(); //Send message to handler
} catch (IOException e) {
break;
}
}
}
}
}

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