Hi I am trying to print a text file with the double data, line by line, read from a file on my android device however it doesn't seem to be working what is wrong? I get no errors but not proper print out?
in my bodyTempInfo View I get readout:
Your Body Temperature Readings are:[]
my temp2.txt file, there is a total of 1440 numbers, not going to paste them all here
37.06750839
36.89390613
36.88484785
36.81941363
36.81815453
36.97372599
37.0510889
36.90421803
36.90452867
36.81245808
36.91739551
37.05989195
36.80757783
36.85141347
37.04927826
36.80384926
36.94000689
37.04948705
37.07007973
36.95211596
37.05161886
36.97029703
37.03218835
36.89381629
My bodyTempInfo.Java
package com.teamfara.circadianrhythmmonitor4;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class bodyTempInfo extends AppCompatActivity {
ArrayList<Double> currentBodyTemp;
public void displayCurrentBodyTempArray(View view) throws FileNotFoundException {
ArrayList<Double> list = new ArrayList<>();
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
//Read text from file
File file = new File(sdcard, "temp2.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
list.add(Double.parseDouble(line));
text.append('\n');
}
br.close();
}
catch(IOException e) {
}
/*
Scanner file2 = new Scanner(new File(sdcard, "temp.txt"));
while (file2.hasNextLine()) {
String line = file2.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNextDouble()) {
list.add(scanner.nextDouble());
}
scanner.close();
}
*/
currentBodyTemp = list;
displayBodyTemp("Your Body Temperature Readings are:" + list);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_body_temp_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try {
displayCurrentBodyTempArray(findViewById(R.id.bodyTempInfoArray));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void displayBodyTemp(String bodyTemp) {
TextView textView = (TextView) findViewById(R.id.bodyTempInfoArray);
textView.setText(bodyTemp);
}
}
logcat
10-25 14:15:11.041 11084-11084/? E/Zygote: MountEmulatedStorage()
10-25 14:15:11.041 11084-11084/? E/Zygote: v2
10-25 14:15:11.041 11084-11084/? I/libpersona: KNOX_SDCARD checking this for 10385
10-25 14:15:11.041 11084-11084/? I/libpersona: KNOX_SDCARD not a persona
10-25 14:15:11.051 11084-11084/? I/SELinux: Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_SM-G920V_5.1.1_0033
10-25 14:15:11.051 11084-11084/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
10-25 14:15:11.051 11084-11084/? I/art: Late-enabling -Xcheck:jni
10-25 14:15:11.111 11084-11084/? D/TimaKeyStoreProvider: TimaSignature is unavailable
10-25 14:15:11.111 11084-11084/? D/ActivityThread: Added TimaKeyStore provider
10-25 14:15:11.211 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
10-25 14:15:11.231 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: Inside getClassLibPath caller
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 D/InjectionManager: InjectionManager
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 D/InjectionManager: fillFeatureStoreMap com.teamfara.circadianrhythmmonitor4
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: Constructor com.teamfara.circadianrhythmmonitor4, Feature store :{}
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: featureStore :{}
10-25 14:15:11.301 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SecWifiDisplayUtil: Metadata value : SecSettings2
10-25 14:15:11.491 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor mIsFloating : false
10-25 14:15:11.491 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor flags : -2139029248
10-25 14:15:11.761 11084-11084/com.teamfara.circadianrhythmmonitor4 D/Activity: performCreate Call Injection manager
10-25 14:15:11.771 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchOnViewCreated > Target : com.teamfara.circadianrhythmmonitor4.MainActivity isFragment :false
10-25 14:15:11.791 11084-11175/com.teamfara.circadianrhythmmonitor4 D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-25 14:15:11.821 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
10-25 14:15:11.821 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled return false
10-25 14:15:11.891 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SRIB_DCS: log_dcs ThreadedRenderer::initialize entered!
10-25 14:15:11.951 11084-11175/com.teamfara.circadianrhythmmonitor4 D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so
10-25 14:15:11.991 11084-11175/com.teamfara.circadianrhythmmonitor4 I/OpenGLRenderer: Initialized EGL, version 1.4
10-25 14:15:12.001 11084-11175/com.teamfara.circadianrhythmmonitor4 I/OpenGLRenderer: HWUI protection enabled for context , &this =0x7f79c8abc0 ,&mEglDisplay = 1 , &mEglConfig = 1912140464
10-25 14:15:12.011 11084-11175/com.teamfara.circadianrhythmmonitor4 D/OpenGLRenderer: Get maximum texture size. GL_MAX_TEXTURE_SIZE is 8192
10-25 14:15:12.011 11084-11175/com.teamfara.circadianrhythmmonitor4 D/OpenGLRenderer: Enabling debug mode 0
10-25 14:15:12.011 11084-11175/com.teamfara.circadianrhythmmonitor4 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
10-25 14:15:12.391 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchCreateOptionsMenu :com.teamfara.circadianrhythmmonitor4.MainActivity
10-25 14:15:12.391 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchPrepareOptionsMenu :com.teamfara.circadianrhythmmonitor4.MainActivity
10-25 14:15:12.461 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#2f8d81aa time:4028871
10-25 14:15:12.801 11084-11084/com.teamfara.circadianrhythmmonitor4 V/ActivityThread: updateVisibility : ActivityRecord{81a0e76 token=android.os.BinderProxy#2f8d81aa {com.teamfara.circadianrhythmmonitor4/com.teamfara.circadianrhythmmonitor4.MainActivity}} show : true
10-25 14:15:14.701 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#2f8d81aa time:4031112
10-25 14:15:14.921 11084-11084/com.teamfara.circadianrhythmmonitor4 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
10-25 14:15:14.971 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_launch_request id:com.teamfara.circadianrhythmmonitor4 time:4031384
10-25 14:15:15.051 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor mIsFloating : false
10-25 14:15:15.051 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor flags : -2139029248
10-25 14:15:15.071 11084-11084/com.teamfara.circadianrhythmmonitor4 D/Activity: performCreate Call Injection manager
10-25 14:15:15.121 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchOnViewCreated > Target : com.teamfara.circadianrhythmmonitor4.bodyTempInfo isFragment :false
10-25 14:15:15.121 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SecWifiDisplayUtil: Metadata value : SecSettings2
10-25 14:15:15.141 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
10-25 14:15:15.141 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled return false
10-25 14:15:15.181 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SRIB_DCS: log_dcs ThreadedRenderer::initialize entered!
10-25 14:15:15.181 11084-11175/com.teamfara.circadianrhythmmonitor4 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
10-25 14:15:15.201 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchCreateOptionsMenu :com.teamfara.circadianrhythmmonitor4.bodyTempInfo
10-25 14:15:15.201 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchPrepareOptionsMenu :com.teamfara.circadianrhythmmonitor4.bodyTempInfo
10-25 14:15:15.271 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1f826b14 time:4031688
10-25 14:15:15.311 11084-11084/com.teamfara.circadianrhythmmonitor4 V/ActivityThread: updateVisibility : ActivityRecord{81a0e76 token=android.os.BinderProxy#2f8d81aa {com.teamfara.circadianrhythmmonitor4/com.teamfara.circadianrhythmmonitor4.MainActivity}} show : false
My content_body_temp_info.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_body_temp_info"
tools:context="com.teamfara.circadianrhythmmonitor4.bodyTempInfo">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Body Temperature Measurements will go here"
android:id = "#+id/bodyTempInfoArray"/>
</RelativeLayout>
my MainActivity.java
package com.teamfara.circadianrhythmmonitor4;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private final static int REQUEST_ENABLE_BT = 1;
UUID myUUID = UUID.randomUUID();
private static final int DISCOVER_DURATION = 300;
private static final int REQUEST_BLU = 1;
ArrayAdapter<String> mArrayAdapter;
ArrayList<Double> currentBodyTemp;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBIntent, REQUEST_ENABLE_BT);
}
//If there are paired devices
/*Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
//Loop through the paired devices
for (BluetoothDevice device : pairedDevices) {
//add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
*/
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
ArrayList<Double> lightInfo;
public void sendLightFile() {
String filename = "lightInfo";
String string = "Here is light info" + lightInfo;
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// Send information over bluetooth?
}
public void goToBodyInfo(View view) {
Intent intent = new Intent(this, bodyTempInfo.class);
startActivity(intent);
}
#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);
}
public void sendLight(View view) {
Intent intent = new Intent(this, ConnectTest.class);
startActivity(intent);
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("CircadianRhythmMonitor", myUUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
//mmServerSocket.close();
break;
}
}
}
/**
* Will cancel the listening socket, and cause the thread to finish
*/
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
// mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
//.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void displayBodyTemp(String bodyTemp) {
TextView textView = (TextView) findViewById(R.id.bodyTempInfoArray);
textView.setText(bodyTemp);
}
}
my AndroidManfiest.xml
package="com.teamfara.circadianrhythmmonitor4" >
<!-- Allows bluetooth to be used from this app -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".bodyTempInfo"
android:label="#string/title_activity_body_temp_info"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.teamfara.circadianrhythmmonitor4.MainActivity" />
</activity>
<activity
android:name=".ConnectTest"
android:label="#string/title_activity_body_temp_info"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.teamfara.circadianrhythmmonitor4.MainActivity" />
</activity>
</application>
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
</manifest>
In your displayBodyTemp() function, you are passing a String and using + to add an arraylist. That is the story.You need to pass a string only. Or override the toString() method of the Arraylist
OR, try this:
displayBodyTemp("Your Body Temperature Readings are:" + text);
Related
I am beginner in android developing and I am trying to make a camera app. The camera app is opening but camera hardware is not detecting this is the code of main activity code. Now what am I missing to added to detect camera hardware please describe it and help me to solve it
public class CamTestActivity extends Activity {
private static final String TAG = "CamTestActivity";
Preview preview;
Button buttonClick;
Camera camera;
Activity act;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
act = this;
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
((FrameLayout) findViewById(R.id.layout)).addView(preview);
preview.setKeepScreenOn(true);
preview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Toast.makeText(ctx, getString(R.string.take_photo_help), Toast.LENGTH_LONG).show();
buttonClick = (Button) findViewById(R.id.btnCapture);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
preview.mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}catch (Exception e)
{
Toast.makeText(ctx, getString(R.string.camera_not_found), Toast.LENGTH_LONG).show();
}
}
});
buttonClick.setOnLongClickListener(new OnLongClickListener(){
#Override
public boolean onLongClick(View arg0) {
camera.autoFocus(new Camera.AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
//camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
return true;
}
});
}
#Override
protected void onResume() {
super.onResume();
int numCams = Camera.getNumberOfCameras();
if(numCams > 0){
try{
camera = Camera.open(1);
camera.startPreview();
preview.setCamera(camera);
} catch (RuntimeException ex){
Toast.makeText(ctx, getString(R.string.camera_not_found), Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onPause() {
if(camera != null) {
camera.stopPreview();
preview.setCamera(null);
camera.release();
camera = null;
}
super.onPause();
}
private void resetCam() {
camera.startPreview();
preview.setCamera(camera);
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
// Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SaveImageTask().execute(data);
resetCam();
Log.d(TAG, "onPictureTaken - jpeg");
}
};
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
}
this is the manifest code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.niit.cameraapp">
<uses-sdk android:minSdkVersion="9" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".CamTestActivity"
android:screenOrientation="portrait" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
this is the logcat error
04-26 12:20:13.694 9167-9167/com.example.niit.cameraapp I/zygote64: Late-enabling -Xcheck:jni
04-26 12:20:13.969 9167-9167/com.example.niit.cameraapp I/InstantRun: starting instant run server: is main process
04-26 12:20:14.142 9167-9167/com.example.niit.cameraapp W/.niit.cameraapp: type=1400 audit(0.0:84362): avc: denied { read } for name="u:object_r:camera_prop:s0" dev="tmpfs" ino=6271 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:camera_prop:s0 tclass=file permissive=0
04-26 12:20:14.149 9167-9167/com.example.niit.cameraapp E/libc: Access denied finding property "camera.hal1.packagelist"
04-26 12:20:14.152 9167-9167/com.example.niit.cameraapp W/CameraBase: An error occurred while connecting to camera 1: Status(-8): '1: validateClientPermissionsLocked:920: Caller "com.example.niit.cameraapp" (PID 10190, UID 9167) cannot open camera "1" without camera permission'
04-26 12:20:14.181 9167-9330/com.example.niit.cameraapp D/OpenGLRenderer: HWUI GL Pipeline
04-26 12:20:14.233 9167-9330/com.example.niit.cameraapp I/Adreno: QUALCOMM build : 7f08991, I8a9bdcf8d3
04-26 12:20:14.236 9167-9330/com.example.niit.cameraapp I/vndksupport: sphal namespace is not configured for this process. Loading /vendor/lib64/hw/gralloc.msm8953.so from the current namespace instead.
04-26 12:20:14.232 9167-9167/com.example.niit.cameraapp W/RenderThread: type=1400 audit(0.0:84363): avc: denied { search } for name="proc" dev="debugfs" ino=5174 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:qti_debugfs:s0 tclass=dir permissive=0
04-26 12:20:14.244 9167-9330/com.example.niit.cameraapp I/Adreno: PFP: 0x005ff087, ME: 0x005ff063
04-26 12:20:14.249 9167-9330/com.example.niit.cameraapp I/OpenGLRenderer: Initialized EGL, version 1.4
04-26 12:20:14.249 9167-9330/com.example.niit.cameraapp D/OpenGLRenderer: Swap behavior 2
04-26 12:20:14.309 9167-9330/com.example.niit.cameraapp I/vndksupport: sphal namespace is not configured for this process. Loading /vendor/lib64/hw/gralloc.msm8953.so from the current namespace instead.
04-26 12:20:17.316 9167-9202/com.example.niit.cameraapp I/zygote64: Debugger is no longer active
screenshot of the deployed app
The issue is most likely that, while you have asked for the Camera permission in the manifest, you also need to ask at runtime. The reason is that in older versions of Android (I think < Android 6.0), you only needed to declare permissions in the manifest. However, now the user can turn permissions on and off after the app has been installed. So now you are supposed to check during runtime whether you have permission for the feature you require. If you don't have it, then you should ask the user to enable it.
You can find code for this online. But first we need to verify that that is indeed the problem. The simplest way of doing that is by going to your Android Settings app. Then in there, there should be an Apps options. Find your app and click on it. In there, there should be a section with the Permissions. If the camera permission is not checked there, then check it and rerun your app.
If this fixes your issue, then you need to find code to ask the user to grant you the permission after the app opens. One such way of doing this is simply on the splash screen, as demonstrated here.
I assume you are running the app on a device with Android 6 or higher. So, you should additionally check for the runtime permissions to use the camera:
https://developer.android.com/training/permissions/requesting
If you don't add this permission check, Android will block the access to the camera hardware. It will also block hardware detection, because it requires also the camera permission. So, everytime you make a call on camera it will fail with a permission denied exception, which is logged in you logcat:
04-26 12:20:14.152 9167-9167/com.example.niit.cameraapp W/CameraBase: An error occurred while connecting to camera 1: Status(-8): '1: validateClientPermissionsLocked:920: Caller "com.example.niit.cameraapp" (PID 10190, UID 9167) cannot open camera "1" without camera permission'
Additionally, it seems you are using the deprecated camera api instead of the camera2 api:
https://developer.android.com/reference/android/hardware/camera2/package-summary
I'm try to play a loading animation on my loading screen, and I read somewhere that android doesn't support gifs so either you have to break in into frames and then play it or we can use the Movie class.
Heres the leading activity -
package com.myapp.mehul.login.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.myapp.mehul.login.MYGIFView;
import com.myapp.mehul.login.MainActivity;
import com.myapp.mehul.login.R;
import com.myapp.mehul.login.app.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/**
* Created by mehul on 2/6/16.
*/
public class LoadingScreen extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 1000;
/** Called when the activity is first created. */
private Socket mSocket;
String you;
String opponentId;
String username;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new MYGIFView(getApplicationContext()));
//initialise the socket
mSocket.connect();
//call add user
mSocket.emit("add user");
//start a listener for opponent
mSocket.on("opponent", onOpponent);
//initialise the username
username = getIntent().getExtras().getString("username");
}
private Emitter.Listener onOpponent = new Emitter.Listener(){
#Override
public void call(final Object... args){
LoadingScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
you = data.getString("you");
opponentId = data.getString("opponent");
Log.d("LoadingScreen", data.toString());
//setResult(RESULT_OK, i);
finish();
} catch (JSONException e) {
return;
}
Intent i = new Intent(LoadingScreen.this, MainActivity.class);
i.putExtra("opponentId", opponentId);
i.putExtra("you", you);
i.putExtra("username", username);
Log.d("goToChat", username);
startActivity(i);
}
});
}
};
#Override
public void onBackPressed(){
AlertDialog.Builder builder = new AlertDialog.Builder(LoadingScreen.this);
builder.setMessage("I knew you didn't have BALLS.").setCancelable(
false).setPositiveButton("I am a LOSER",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//send the logout information to the server
JSONObject discon = new JSONObject();
try {
discon.put("opponent", opponentId);
discon.put("you", you);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSocket.emit("discon", discon);
mSocket.disconnect();
//finish the current activity.
Intent intent = new Intent(LoadingScreen.this, MainMenu.class);
startActivity(intent);
LoadingScreen.this.finish();
}
}).setNegativeButton("I'll fkin face it",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
In the above code I've set content view by passing it an instance of MYGIFView.class -
Heres MYGIFView.class
package com.myapp.mehul.login;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.view.View;
import java.io.InputStream;
/**
* Created by mehul on 2/7/16.
*/
public class MYGIFView extends View{
Movie movie,movie1;
InputStream is=null,is1=null;
long moviestart;
public MYGIFView(Context context) {
super(context);
is=context.getResources().openRawResource(+ R.drawable.loading);
movie=Movie.decodeStream(is);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
long now=android.os.SystemClock.uptimeMillis();
System.out.println("now="+now);
if (moviestart == 0) { // first time
moviestart = now;
}
System.out.println("\tmoviestart="+moviestart);
int relTime = (int)((now - moviestart) % movie.duration()) ;
System.out.println("time="+relTime+"\treltime="+movie.duration());
movie.setTime(relTime);
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
this.invalidate();
}
}
The loading activity IS creating an instance of MYGIFView.class and it logs the data but then it gives fatal signal 11. I tried to search but I didn't get any answer.
console log -
02-07 12:22:30.321 29092-29092/? I/art: Late-enabling -Xcheck:jni
02-07 12:22:30.341 29092-29102/? I/art: Debugger is no longer active
02-07 12:22:30.422 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.422 29092-29092/? D/LoginActivity: already logged in
02-07 12:22:30.425 29092-29092/? I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71360781
02-07 12:22:30.487 29092-29092/? D/MainMenu: painted again
02-07 12:22:30.490 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.554 29092-29149/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-07 12:22:30.559 29092-29092/? D/Atlas: Validating map...
02-07 12:22:30.596 29092-29149/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030_msm8974_LA.BF.1.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 04/15/15 Wed
Local Branch: mybranch9068252
Remote Branch: quic/LA.BF.1.1.1_rb1.19
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030 + NOTHING
02-07 12:22:30.597 29092-29149/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-07 12:22:30.611 29092-29149/? D/OpenGLRenderer: Enabling debug mode 0
02-07 12:22:30.660 29092-29092/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#387f1572 time:71361016
02-07 12:22:31.898 29092-29092/com.myapp.mehul.login D/go to chat: was called
02-07 12:22:31.899 29092-29092/com.myapp.mehul.login I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71362255
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: now=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: moviestart=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: time=0 reltime=1850
02-07 12:22:32.007 29092-29092/com.myapp.mehul.login A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 29092 (app.mehul.login)
02-07 12:22:32.541 29092-29092/com.myapp.mehul.login W/app.mehul.login: type=1701 audit(0.0:302): auid=4294967295 uid=10250 gid=10250 ses=4294967295 subj=u:r:untrusted_app:s0 reason="memory violation" sig=11
I received a batch for this question which means its being viewed a lot, so I'll answer this question -
What I figured out was the line below was throwing the error -
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
Now the problem is that this error specifically can be caused by lots of reasons, its never a specific reason.. the reason mine wasn't working out was because my device didn't work well with hardware acceleration, so I just had to disable it in the manifest application, like this -
<android:hardwareAccelerated="false">
Now its possible that the reason might not be the same....but the core reason is the same, its memory related, and most chances are its a bug in the firmware of the device or emulator you are testing upon.
In the Manifest set in your activity :
<activity
android:name="LoadingScreen"
android:hardwareAccelerated="false">
</activity>
I got here with the exact same problem but in React Native, so I will put a solution for those who need it too. The error may be triggered by react-native-webview and/or React Navigation. In some cases, like me, you don't want to disable Hardware Acceleration on the whole app, so here's a workaround:
react-native-webview
<WebView
androidHardwareAccelerationDisabled
source={source}
/>
React Navigation 5
<NavigationContainer>
<Stack.Navigator initialRouteName="HomeScreen">
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{
animationEnabled: false,
}}
/>
</Stack.Navigator>
</NavigationContainer>
https://github.com/react-native-webview/react-native-webview/issues/575
I am trying to turn on the portable Wifi hotspot ON, by referring this link:
how to set advanced settings of android wifihotspot
This is working well on Samsung Galaxy S3 Android v4.4.2.(no issues)
But on other devices with the same or lower Android version, the application crashes and restarts the device.
The code is as follows:
package com.android.startwifi;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class Main extends Activity {
public WifiManager wifiManager;
public Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("hi1","hi");
createWifiAccessPoint();
}
private void createWifiAccessPoint() {
WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods();
boolean methodFound=false;
for(Method method: wmMethods){
if(method.getName().equals("setWifiApEnabled")){
methodFound=true;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
try {
boolean apstatus=(Boolean) method.invoke(wifiManager, netConfig,true);
//statusView.setText("Creating a Wi-Fi Network \""+netConfig.SSID+"\"");
for (Method isWifiApEnabledmethod: wmMethods)
{
if(isWifiApEnabledmethod.getName().equals("isWifiApEnabled")){
while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){
};
for(Method method1: wmMethods){
if(method1.getName().equals("getWifiApState")){
int apstate;
apstate=(Integer)method1.invoke(wifiManager);
// netConfig=(WifiConfiguration)method1.invoke(wifi);
//statusView.append("\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");
}
}
}
}
if(apstatus)
{
System.out.println("SUCCESSdddd");
//statusView.append("\nAccess Point Created!");
//finish();
//Intent searchSensorsIntent = new Intent(this,SearchSensors.class);
//startActivity(searchSensorsIntent);
}else
{
System.out.println("FAILED");
//statusView.append("\nAccess Point Creation failed!");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if(!methodFound){
//statusView.setText("Your phone's API does not contain setWifiApEnabled method to configure an access point");
}
}
#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);
}
}
Permissions that I have defined in the manifest file are:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
The log file generated is as follows:
09-10 18:35:01.644: D/jdwp(29752): prepping for JDWP over ADB
09-10 18:35:01.644: D/jdwp(29752): ADB transport startup
09-10 18:35:01.644: D/dalvikvm(29752): Elevating priority from 0 to -8
09-10 18:35:01.645: D/jdwp(29752): JDWP: thread running
09-10 18:35:01.645: D/jdwp(29752): acceptConnection
09-10 18:35:01.646: D/jdwp(29752): trying to receive file descriptor from ADB
09-10 18:35:01.646: D/dalvikvm(29752): zygote get thread init done
09-10 18:35:01.653: D/jdwp(29752): received file descriptor 34 from ADB
09-10 18:35:01.658: D/jdwp(29752): processIncoming
09-10 18:35:01.659: D/jdwp(29752): processIncoming
09-10 18:35:01.659: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000040, flags=0x0, dataLen=0x8
09-10 18:35:01.661: D/jdwp(29752): processIncoming
09-10 18:35:01.661: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x17, id=0x40000041, flags=0x0, dataLen=0xC
09-10 18:35:01.663: D/jdwp(29752): processIncoming
09-10 18:35:01.663: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000042, flags=0x0, dataLen=0x8
09-10 18:35:01.665: D/jdwp(29752): processIncoming
09-10 18:35:01.665: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000043, flags=0x0, dataLen=0x8
09-10 18:35:01.676: D/jdwp(29752): sendBufferedRequest : len=0x3D
09-10 18:35:01.736: D/jdwp(29752): sendBufferedRequest : len=0x45
09-10 18:35:01.754: W/asset(29752): AssetManager-->addDefaultAssets CIP path not exsit!
09-10 18:35:02.219: I/hi1(29752): hi
09-10 18:35:02.261: D/WifiManager(29752): Enter init, sThreadRefCount:0
09-10 18:35:02.268: D/WifiManager(29752): Create WifiManager handlerthread
09-10 18:35:03.599: I/System.out(29752): SUCCESSdddd
09-10 18:35:03.634: V/PhoneWindow(29752): DecorView setVisiblity: visibility = 4
09-10 18:35:03.745: V/PhoneWindow(29752): DecorView setVisiblity: visibility = 0
09-10 18:35:03.922: D/libEGL(29752): loaded /system/lib/egl/libEGL_mali.so
09-10 18:35:03.924: D/libEGL(29752): loaded /system/lib/egl/libGLESv1_CM_mali.so
09-10 18:35:03.927: D/libEGL(29752): loaded /system/lib/egl/libGLESv2_mali.so
09-10 18:35:04.111: D/OpenGLRenderer(29752): Enabling debug mode 0
09-10 18:35:10.610: E/InputEventReceiver(29752): channel '41f21f48 com.android.startwifi/com.android.startwifi.Main (client)' ~ Publisher closed input channel or an error occurred. events=0x9
Thus I have the following questions:
I would like to know why is this app behaving normally on Samsung S3
but not on other devices?
How can I fix this issue?
I had the same issue. You must to erase the following code line:
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
That works for me in versions 4.1.1, 4.2 and 4.3.
Try this code .I test in android 5.0.1 :
public boolean setHotSpot(String SSID,String passWord){
Method[] mMethods = mWifiManager.getClass().getDeclaredMethods();
for(Method mMethod: mMethods){
if(mMethod.getName().equals("setWifiApEnabled")) {
WifiConfiguration netConfig = new WifiConfiguration();
if(passWord==""){
netConfig.SSID = SSID;
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}else{
netConfig.SSID = SSID ;
netConfig.preSharedKey = passWord;
netConfig.hiddenSSID = true;
netConfig.status = WifiConfiguration.Status.ENABLED;
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
try {
mMethod.invoke(mWifiManager, netConfig,false);
mWifiManager.saveConfiguration();
return true;
} catch (Exception e) {
e.getMessage();
}
}
}
return false;
}
Insert this permission in AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
If you are using WPA_PSK authentication, you have to specify preSharedKey.
netConfig.preSharedKey = "testPassword";
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
Otherwise it will crash and restart the device.
I have been trying to learn how Google Cloud Messaging works in Android apps, specifically multicast messaging, so I found a tutorial with source code. Unfortunately I can get the program to compile without error but when it runs, I get a fatal exception. Anyone know what is wrong?
Here is the main activity:
package com.ganyo.pushtest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
import static com.ganyo.pushtest.Util.*;
import static com.ganyo.pushtest.Util.TAG;
public class PushMainActivity extends Activity {
private TextView messageTextView;
private Button sendButton;
private AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is a hack to force AsyncTask to be initialized on main thread. Without this things
// won't work correctly on older versions of Android (2.2, apilevel=8)
try {
Class.forName("android.os.AsyncTask");
} catch (Exception ignored) {}
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
initUI();
AppServices.loginAndRegisterForPush(this);
}
private void initUI() {
setContentView(R.layout.main);
messageTextView = (TextView)findViewById(R.id.lblMessage);
sendButton = (Button)findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AppServices.sendMyselfANotification(v.getContext());
}
});
registerReceiver(notificationReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
}
/**
* Receives push Notifications
* */
private final BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take some action upon receiving a push notification here!
**/
String message = intent.getExtras().getString(EXTRA_MESSAGE);
if (message == null) { message = "Empty Message"; }
Log.i(TAG, message);
messageTextView.append("\n" + message);
alert.showAlertDialog(context, getString(R.string.gcm_alert_title), message);
Toast.makeText(getApplicationContext(), getString(R.string.gcm_message, message), Toast.LENGTH_LONG).show();
WakeLocker.release();
}
};
// this will be called when the screen rotates instead of onCreate()
// due to manifest setting, see: android:configChanges
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
initUI();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(notificationReceiver);
}
}
Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ganyo.pushtest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/>
<permission android:name="com.ganyo.pushtest.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.ganyo.pushtest.permission.C2D_MESSAGE" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity android:name="com.ganyo.pushtest.PushMainActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.ganyo.pushtest" />
</intent-filter>
</receiver>
<service android:name="GCMIntentService" />
</application>
</manifest>
Here is Appservices:
package com.ganyo.pushtest;
import android.content.Context;
import android.util.Log;
import com.apigee.sdk.ApigeeClient;
import com.apigee.sdk.data.client.DataClient;
import com.apigee.sdk.data.client.callbacks.ApiResponseCallback;
import com.apigee.sdk.data.client.callbacks.DeviceRegistrationCallback;
import com.apigee.sdk.data.client.entities.Device;
import com.apigee.sdk.data.client.entities.Entity;
import com.apigee.sdk.data.client.response.ApiResponse;
import com.apigee.sdk.data.client.utils.JsonUtils;
import com.google.android.gcm.GCMRegistrar;
import com.apigee.sdk.data.client.push.GCMPayload;
import com.apigee.sdk.data.client.push.GCMDestination;
import java.util.HashMap;
import static com.ganyo.pushtest.Util.*;
import static com.ganyo.pushtest.Settings.*;
public final class AppServices {
private static DataClient client;
private static Device device;
static synchronized DataClient getClient(Context context) {
if (client == null) {
if (ORG.equals("<<your org name here>>")) {
Log.e(TAG, "ORG value has not been set.");
} else {
ApigeeClient apigeeClient = new ApigeeClient(ORG,APP,API_URL,context);
client = apigeeClient.getDataClient();
}
}
return client;
}
static void loginAndRegisterForPush(final Context context) {
if ((USER != null) && (USER.length() > 0)) {
DataClient dataClient = getClient(context);
if (dataClient != null) {
dataClient.authorizeAppUserAsync(USER, PASSWORD, new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "login response: " + apiResponse);
registerPush(context);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Login Exception: " + e);
Log.i(TAG, "login exception: " + e);
}
});
} else {
Log.e(TAG,"Data client is null, did you set ORG value in Settings.java?");
}
} else {
registerPush(context);
}
}
static void registerPush(Context context) {
final String regId = GCMRegistrar.getRegistrationId(context);
if ("".equals(regId)) {
GCMRegistrar.register(context, Settings.GCM_SENDER_ID);
} else {
if (GCMRegistrar.isRegisteredOnServer(context)) {
Log.i(TAG, "Already registered with GCM");
} else {
AppServices.register(context, regId);
}
}
}
/**
* Register this user/device pair on App Services.
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device: " + regId);
DataClient dataClient = getClient(context);
if (dataClient != null) {
dataClient.registerDeviceForPushAsync(dataClient.getUniqueDeviceID(), NOTIFIER, regId, null, new DeviceRegistrationCallback() {
#Override
public void onResponse(Device device) {
Log.i(TAG, "register response: " + device);
AppServices.device = device;
displayMessage(context, "Device registered as: " + regId);
DataClient dataClient = getClient(context);
if (dataClient != null) {
// connect Device to current User - if there is one
if (dataClient.getLoggedInUser() != null) {
dataClient.connectEntitiesAsync("users", dataClient.getLoggedInUser().getUuid().toString(),
"devices", device.getUuid().toString(),
new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "connect response: " + apiResponse);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Connect Exception: " + e);
Log.i(TAG, "connect exception: " + e);
}
});
}
} else {
Log.e(TAG,"data client is null, did you set ORG value in Settings.java?");
}
}
#Override
public void onException(Exception e) {
displayMessage(context, "Register Exception: " + e);
Log.i(TAG, "register exception: " + e);
}
#Override
public void onDeviceRegistration(Device device) { /* this won't ever be called */ }
});
} else {
Log.e(TAG, "Data client is null, did you set ORG value in Settings.java?");
}
}
static void sendMyselfANotification(final Context context) {
if (device == null) {
displayMessage(context, "Device not registered. ORG value set in Settings.java?");
} else {
DataClient dataClient = getClient(context);
if (dataClient != null) {
GCMDestination destination = GCMDestination.destinationSingleDevice(device.getUuid());
GCMPayload payload = new GCMPayload();
payload.setAlertText("Hi there!");
dataClient.pushNotificationAsync(payload, destination, "google", new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "send response: " + apiResponse);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Send Exception: " + e);
Log.i(TAG, "send exception: " + e);
}
});
} else {
Log.e(TAG, "data client is null, did you set ORG value in Settings.java?");
}
}
}
/**
* Unregister this device within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device: " + regId);
register(context, "");
}
}
Gmcintentservices:
package com.ganyo.pushtest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import com.google.android.gcm.GCMBaseIntentService;
import static com.ganyo.pushtest.Settings.GCM_SENDER_ID;
import static com.ganyo.pushtest.Util.displayMessage;
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
super(GCM_SENDER_ID);
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: " + registrationId);
displayMessage(context, getString(R.string.gcm_registered, registrationId));
AppServices.register(context, registrationId);
}
/**
* Method called on device unregistered
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered, registrationId));
AppServices.unregister(context, registrationId);
}
/**
* Method called on receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("data");
Log.i(TAG, "Received message: " + message);
displayMessage(context, message);
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error, errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a Notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, PushMainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentText(message)
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(icon)
.setWhen(when)
.setContentIntent(intent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
Alertdialoguemanager:
package com.ganyo.pushtest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertDialogManager {
public void showAlertDialog(Context context, String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Util:
package com.ganyo.pushtest;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMRegistrar;
public final class Util {
static final String TAG = "com.ganyo.pushtest";
static final String DISPLAY_MESSAGE_ACTION = "com.ganyo.pushtest.DISPLAY_MESSAGE";
static final String EXTRA_MESSAGE = "message";
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
Wakelocker:
package com.ganyo.pushtest;
import android.content.Context;
import android.os.PowerManager;
public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context context) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.ON_AFTER_RELEASE |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE |
PowerManager.SCREEN_DIM_WAKE_LOCK, "WakeLock");
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
Here is the logcat area of the fatal exception:
05-01 00:26:52.757: D/AndroidRuntime(166): Shutting down VM
05-01 00:26:52.777: D/jdwp(166): adbd disconnected
05-01 00:26:52.817: I/AndroidRuntime(166): NOTE: attach of thread 'Binder Thread #3' failed
05-01 00:26:53.050: I/ActivityThread(258): Publishing provider com.svox.pico.providers.SettingsProvider: com.svox.pico.providers.SettingsProvider
05-01 00:26:53.627: I/ActivityManager(58): Start proc com.ganyo.pushtest for activity com.ganyo.pushtest/.PushMainActivity: pid=267 uid=10036 gids={3003}
05-01 00:26:54.687: W/WindowManager(58): No window to dispatch pointer action 0
05-01 00:26:54.707: W/WindowManager(58): No window to dispatch pointer action 1
05-01 00:26:55.467: D/AndroidRuntime(267): Shutting down VM
05-01 00:26:55.467: W/dalvikvm(267): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-01 00:26:55.537: E/AndroidRuntime(267): FATAL EXCEPTION: main
05-01 00:26:55.537: E/AndroidRuntime(267): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ganyo.pushtest/com.ganyo.pushtest.PushMainActivity}: java.lang.ClassNotFoundException: com.ganyo.pushtest.PushMainActivity in loader dalvik.system.PathClassLoader[/data/app/com.ganyo.pushtest-2.apk]
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.os.Looper.loop(Looper.java:123)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.reflect.Method.invoke(Method.java:521)
05-01 00:26:55.537: E/AndroidRuntime(267): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-01 00:26:55.537: E/AndroidRuntime(267): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-01 00:26:55.537: E/AndroidRuntime(267): at dalvik.system.NativeStart.main(Native Method)
05-01 00:26:55.537: E/AndroidRuntime(267): Caused by: java.lang.ClassNotFoundException: com.ganyo.pushtest.PushMainActivity in loader dalvik.system.PathClassLoader[/data/app/com.ganyo.pushtest-2.apk]
05-01 00:26:55.537: E/AndroidRuntime(267): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
05-01 00:26:55.537: E/AndroidRuntime(267): ... 11 more
05-01 00:26:55.617: W/ActivityManager(58): Force finishing activity com.ganyo.pushtest/.PushMainActivity
05-01 00:26:56.499: W/ActivityManager(58): Activity pause timeout for HistoryRecord{460133f8 com.ganyo.pushtest/.PushMainActivity}
05-01 00:26:56.687: I/ARMAssembler(58): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x3261a0:0x32625c] in 1336038 ns
05-01 00:26:56.777: I/ARMAssembler(58): generated scanline__00000177:03515104_00001001_00000000 [ 91 ipp] (114 ins) at [0x3265b8:0x326780] in 1506105 ns
05-01 00:26:57.337: I/ARMAssembler(58): generated scanline__00000077:03545404_00000004_00000000 [ 47 ipp] (67 ins) at [0x326788:0x326894] in 951792 ns
05-01 00:26:57.967: D/AndroidRuntime(271): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
05-01 00:26:58.009: D/AndroidRuntime(271): CheckJNI is ON
05-01 00:27:00.377: D/AndroidRuntime(271): --- registering native functions ---
Thanks for the help!
It turned out to be all the .java files in the java folder. Once I redid them in the src path, the program worked correctly.
I am trying to build my own custom camera application I have learn through the Android developers Group about how to code the whole application but as soon as I launch the camera it crashes I don't know what is the problem here is my code:
package com.example.tapeit;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Files.FileColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class CameraActivity extends Activity implements Camera.PictureCallback {
private Camera mCamera;
private CameraPreview mPreview;
String TAG = "TapeIt";
public static final int MEDIA_TYPE_IMAGE = 1;
Button captureButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_layout);
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(preview);
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
}
private boolean checkCameraHardware(Context context){
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
return true;
}else{
return false;
}
}
public static Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: " );
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
private static File getOutputMediaFile(int mediaTypeImage) {
// TODO Auto-generated method stub
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraApp");
if(! mediaStorageDir.exists()){
if(! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: " );
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
}
And here is my preview Class:
package com.example.tapeit;
import java.io.IOException;
import android.content.Context;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.hardware.Camera;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private Camera mCamera;
private SurfaceHolder mHolder;
String TAG = "TapeIt";
public CameraPreview (Context context, Camera camera){
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
}
public void surfaceCreated(SurfaceHolder holder){
try{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(IOException e){
Log.d(TAG, "Error setting camera preview" + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// TODO Auto-generated method stub
if(mHolder.getSurface() == null){
return;
}
try{
mCamera.stopPreview();
}catch(Exception e){
}
//You should make here changes when the device is rotated or when any other change
// set preview size and make any resize, rotate or
// reformatting changes here
//mCamera.getParameters().getSupportedPreviewSizes();
try{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(IOException e){
Log.d(TAG, "Error setting camera preview" + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
}
My manifest uses all the permision here they are:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.tapeit.CameraActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My logcat in the console is posted here:
04-04 11:19:32.010: D/AndroidRuntime(21270): Shutting down VM
04-04 11:19:32.010: W/dalvikvm(21270): threadid=1: thread exiting with uncaught exception (group=0x40eb72a0)
04-04 11:19:32.010: E/AndroidRuntime(21270): FATAL EXCEPTION: main
04-04 11:19:32.010: E/AndroidRuntime(21270): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tapeit/com.example.tapeit.CameraActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.access$700(ActivityThread.java:134)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.os.Looper.loop(Looper.java:137)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.main(ActivityThread.java:4867)
04-04 11:19:32.010: E/AndroidRuntime(21270): at java.lang.reflect.Method.invokeNative(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270): at java.lang.reflect.Method.invoke(Method.java:511)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
04-04 11:19:32.010: E/AndroidRuntime(21270): at dalvik.system.NativeStart.main(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addViewInner(ViewGroup.java:3439)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3310)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3255)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3231)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.example.tapeit.CameraActivity.onCreate(CameraActivity.java:39)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.Activity.performCreate(Activity.java:5047)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
04-04 11:19:32.010: E/AndroidRuntime(21270): ... 11 more
preview.addView(preview);
You are attempting to add the FrameLayout to itself. This will not work.
Presumably, the parameter should be mPreview.
You may wish to use more distinctive names for variables, such as not having both preview and mPreview.