Android two network operations at the same time - java

I'm having a problem with two network operations at the same time.
This is the code I'm working on:
public void onClick(View v) {
// TODO onClick
switch(v.getId()){
case R.id.btSelectSong:
openGalleryAudio();
break;
case R.id.btUpload:
if(etSongTitle.getText().toString().isEmpty()){
Toast.makeText(getBaseContext(),
"Select an audio file", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(AddSong.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Log.d("Upload", "Uploading started.....");
}
});
uploadFile(uploadFilePath);
}
}).start();
new Thread(new Runnable() {
public void run(){
runOnUiThread(new Runnable() {
public void run() {
Log.d("Insert", "Inserting audio file metadata to server...");
}
});
insertToServer();
}
}).start();
}
break;
}
}
private void insertToServer(){
String strSongFileName = etSongTitle.getText().toString();
String strSongTitleName = etSongTitleName.getText().toString();
String strSongType = spSongType.getSelectedItem().toString();
String strSongUrl =
"http://mlssabio.x10.mx/strings-of-beads/songs/" +
strSongFileName.replaceAll("\\s+","-").replaceAll("\\'", "") + ".mp3";
String strSongLanguage = spSongLanguage.getSelectedItem().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_SONGTYPE, strSongType));
params.add(new BasicNameValuePair(TAG_SONGTITLE, strSongTitleName));
params.add(new BasicNameValuePair(TAG_SONGURL, strSongUrl));
params.add(new BasicNameValuePair(TAG_SONGLANGUAGE, strSongLanguage));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_insert_song,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath);
runOnUiThread(new Runnable() {
public void run() {
Log.d("Test", "Source File not exist :"
+ uploadFilePath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(maxBufferSize);
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
+ fileName + "'" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+ uploadFilePath;
Log.d("Test", msg);
Toast.makeText(AddSong.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} // end of try
catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Log.d("Test", "MalformedURLException Exception : check script url.");
Toast.makeText(AddSong.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} // end of MalformedURLException ex
catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Log.d("Exception", "Got Exception : see logcat ");
Toast.makeText(AddSong.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
} // End of catch Exception e
dialog.dismiss();
return serverResponseCode;
} // End else block
}
Basically, my app uploads an audio file to the server and also inserts the file's metadata to the database server. But I'm getting an error. Please see my logcat errors below:
01-05 07:31:56.112: E/WindowManager(32278): Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): android.view.WindowLeaked: Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.Dialog.show(Dialog.java:281)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:116)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:99)
01-05 07:31:56.112: E/WindowManager(32278): at com.thesis.string.of.beads.AddSong.onClick(AddSong.java:158)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View.performClick(View.java:4240)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View$PerformClick.run(View.java:17721)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:31:56.112: E/WindowManager(32278): at dalvik.system.NativeStart.main(Native Method)
01-05 07:39:22.201: I/uploadFile(32278): HTTP Response is : OK: 200
01-05 07:39:22.221: D/Test(32278): File Upload Completed.
01-05 07:39:22.221: D/Test(32278): See uploaded file here :
01-05 07:39:22.221: D/Test(32278): /storage/sdcard/John Farnham - Please Don't Ask Me.mp3
01-05 07:39:22.290: D/AndroidRuntime(32278): Shutting down VM
01-05 07:39:22.290: W/dalvikvm(32278): threadid=1: thread exiting with uncaught exception (group=0x41465700)
01-05 07:39:22.332: E/AndroidRuntime(32278): FATAL EXCEPTION: main
01-05 07:39:22.332: E/AndroidRuntime(32278): java.lang.IllegalArgumentException: View not attached to window manager
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:406)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:308)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog.dismissDialog(Dialog.java:323)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog$1.run(Dialog.java:119)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:39:22.332: E/AndroidRuntime(32278): at dalvik.system.NativeStart.main(Native Method)
01-05 07:31:56.112: E/WindowManager(32278): Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): android.view.WindowLeaked: Activity com.thesis.string.of.beads.AddSong has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41879518 V.E..... R.....ID 0,0-200,114} that was originally added here
01-05 07:31:56.112: E/WindowManager(32278): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.Dialog.show(Dialog.java:281)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:116)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ProgressDialog.show(ProgressDialog.java:99)
01-05 07:31:56.112: E/WindowManager(32278): at com.thesis.string.of.beads.AddSong.onClick(AddSong.java:158)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View.performClick(View.java:4240)
01-05 07:31:56.112: E/WindowManager(32278): at android.view.View$PerformClick.run(View.java:17721)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:31:56.112: E/WindowManager(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:31:56.112: E/WindowManager(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:31:56.112: E/WindowManager(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:31:56.112: E/WindowManager(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:31:56.112: E/WindowManager(32278): at dalvik.system.NativeStart.main(Native Method)
01-05 07:39:22.201: I/uploadFile(32278): HTTP Response is : OK: 200
01-05 07:39:22.221: D/Test(32278): File Upload Completed.
01-05 07:39:22.221: D/Test(32278): See uploaded file here :
01-05 07:39:22.221: D/Test(32278): /storage/sdcard/John Farnham - Please Don't Ask Me.mp3
01-05 07:39:22.290: D/AndroidRuntime(32278): Shutting down VM
01-05 07:39:22.290: W/dalvikvm(32278): threadid=1: thread exiting with uncaught exception (group=0x41465700)
01-05 07:39:22.332: E/AndroidRuntime(32278): FATAL EXCEPTION: main
01-05 07:39:22.332: E/AndroidRuntime(32278): java.lang.IllegalArgumentException: View not attached to window manager
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:406)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:308)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog.dismissDialog(Dialog.java:323)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.Dialog$1.run(Dialog.java:119)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.handleCallback(Handler.java:730)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.os.Looper.loop(Looper.java:137)
01-05 07:39:22.332: E/AndroidRuntime(32278): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 07:39:22.332: E/AndroidRuntime(32278): at java.lang.reflect.Method.invoke(Method.java:525)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-05 07:39:22.332: E/AndroidRuntime(32278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 07:39:22.332: E/AndroidRuntime(32278): at dalvik.system.NativeStart.main(Native Method)
Note:
the saving of audio file's metadata is working, but the uploading of audio file seems to be not working.
Any ideas? I'm stuck with this problem. I really need your help. Thanks.

From what i see, you make 2 changes to the UI,
you either dismiss the dialog or closing the activity.
I think that you are closing the activity and then trying to do something with the dialog.
therefor you have a leaked window cause there is no activity.

Related

Error in performing bluetooth file transfer in android

I created an app for Transfer of file from bluetooth in android but unfortunately my app crashes
Following is my main source code and log of error.I have a file named "hi.txt" in my sdcard.
Kindly guide where i a going wrong.
public class MainActivity extends AppCompatActivity
{
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch, buttonOn, buttonDesc, buttonOff;
ArrayAdapter<String> adapter, detectedAdapter, mNewDevicesArrayAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_single_choice);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
#Override
protected void onStart()
{
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices()
{
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if (pairedDevice.size() > 0)
{
for (BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName() + "\n" + device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
class ListItemClicked implements AdapterView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : " + bdDevice.toString());
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if (isBonded) {
Log.i("Log", "Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
Log.i("Log", "The bond is created: " + isBonded);
}
}
public void btSend()
{
String path = Environment.getExternalStorageDirectory()+"/hi.txt";
File file = new File(path);
BluetoothSocket socket= null;
try
{
socket = bdDevice.createRfcommSocketToServiceRecord(applicationUUID);
socket.connect();
}
catch (IOException e)
{
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, path);
values.put(BluetoothShare.DESTINATION,bdDevice.getAddress());
values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
getContentResolver().insert(BluetoothShare.CONTENT_URI,values);
}
class ListItemClickedonPaired implements AdapterView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBond = removeBond(bdDevice);
if (removeBond) {
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed" + removeBond);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Boolean connect(BluetoothDevice bdDevice)
{
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);
} catch (Exception e)
{
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice) throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBond = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean)removeBond.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements View.OnClickListener
{
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Searching for devices", Toast.LENGTH_LONG).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
} catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if (arrayListBluetoothDevices.size() < 1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
detectedAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
} else {
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for (int i = 0; i < arrayListBluetoothDevices.size(); i++) {
if (device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress())) {
flag = false;
}
}
if (flag == true) {
detectedAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}
}
}
};
private void startSearching()
{
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
MainActivity.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth()
{
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
private void offBluetooth()
{
if (bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_LONG).show();
}
}
private void makeDiscoverable()
{
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
#Override
public void handleMessage(Message msg) {
switch (msg.what)
{
case 111:
break;
default:
break;
}
}
}
}
Log file:
13170-13170/com.example.toshiba.bluetoothdemo D/ActivityThread: handleBindApplication:com.example.toshiba.bluetoothdemo
11-16 18:01:45.587 13170-13170/com.example.toshiba.bluetoothdemo D/ActivityThread: setTargetHeapUtilization:0.75
11-16 18:01:45.587 13170-13170/com.example.toshiba.bluetoothdemo D/ActivityThread: setTargetHeapMinFree:2097152
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve interface method 17915: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve interface method 17919: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: GetMethodID: not returning static method Landroid/os/Process;.getTotalMemory ()J
11-16 18:01:45.647 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: GetMethodID: not returning static method Landroid/os/Process;.getFreeMemory ()J
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve virtual method 439: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve virtual method 461: Landroid/content/res/TypedArray;.getType (I)I
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-16 18:01:45.787 13170-13170/com.example.toshiba.bluetoothdemo D/BluetoothAdapter: 1112941536: getState() : mService = null. Returning STATE_OFF
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: ()
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: OpenGL ES Shader Compiler Version: E031.24.02.07
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Build Date: 03/30/15 Mon
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Local Branch:
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Remote Branch:
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Local Patches:
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Reconstruct Branch:
11-16 18:01:45.897 13170-13170/com.example.toshiba.bluetoothdemo D/OpenGLRenderer: Enabling debug mode 0
11-16 18:01:46.037 13170-13170/com.example.toshiba.bluetoothdemo I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#424fa760 time:8721552
11-16 18:01:48.687 13170-13170/com.example.toshiba.bluetoothdemo I/Log: Bluetooth is Enabled
11-16 18:01:48.717 13170-13170/com.example.toshiba.bluetoothdemo W/Toast: From com.example.toshiba.bluetoothdemo, go ahead.
11-16 18:01:50.267 13170-13170/com.example.toshiba.bluetoothdemo I/Timeline: Timeline: Activity_launch_request time:8725789
11-16 18:01:50.297 13170-13170/com.example.toshiba.bluetoothdemo I/Log: Discoverable
11-16 18:01:52.337 13170-13170/com.example.toshiba.bluetoothdemo I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#424fa760 time:8727857
11-16 18:01:53.227 13170-13170/com.example.toshiba.bluetoothdemo I/Log: in the start searching method
11-16 18:01:54.717 13170-13170/com.example.toshiba.bluetoothdemo W/Toast: From com.example.toshiba.bluetoothdemo, go ahead.
11-16 18:01:54.727 13170-13170/com.example.toshiba.bluetoothdemo W/Toast: From com.example.toshiba.bluetoothdemo, go ahead.
11-16 18:01:57.917 13170-13170/com.example.toshiba.bluetoothdemo I/Log: The dvice : 24:EC:99:5C:FA:8C
11-16 18:01:57.947 13170-13170/com.example.toshiba.bluetoothdemo I/Log: The bond is created: false
11-16 18:01:57.957 13170-13170/com.example.toshiba.bluetoothdemo W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
11-16 18:01:57.967 13170-13170/com.example.toshiba.bluetoothdemo D/BluetoothSocket: connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[67]}
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] gammamode=2, cemode=10
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] temp_gammavalue=2, temp_cevalue=10
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] Don't setGamma!
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] Don't setCe!
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] Set temp_prefer temp_ce!
11-16 18:02:02.277 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:574)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:585)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:326)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.example.toshiba.bluetoothdemo.MainActivity.btSend(MainActivity.java:163)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.example.toshiba.bluetoothdemo.MainActivity$ListItemClicked.onItemClick(MainActivity.java:146)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AdapterView.performItemClick(AdapterView.java:299)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AbsListView.performItemClick(AbsListView.java:1115)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AbsListView$PerformClick.run(AbsListView.java:2928)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AbsListView$3.run(AbsListView.java:3691)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.os.Looper.loop(Looper.java:136)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5113)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
11-16 18:02:02.297 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-16 18:02:02.297 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
11-16 18:02:02.297 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at dalvik.system.NativeStart.main(Native Method)
11-16 18:02:02.307 13170-13170/com.example.toshiba.bluetoothdemo D/AndroidRuntime: Shutting down VM
11-16 18:02:02.307 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416d9d58)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: FATAL EXCEPTION: main
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: Process: com.example.toshiba.bluetoothdemo, PID: 13170
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: java.lang.SecurityException: Permission Denial: writing com.android.bluetooth.opp.BluetoothOppProvider uri content://com.android.bluetooth.opp/btopp from pid=13170, uid=10137 requires android.permission.ACCESS_BLUETOOTH_SHARE, or grantUriPermission()
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1472)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.content.ContentProviderProxy.insert(ContentProviderNative.java:468)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.content.ContentResolver.insert(ContentResolver.java:1190)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.example.toshiba.bluetoothdemo.MainActivity.btSend(MainActivity.java:178)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.example.toshiba.bluetoothdemo.MainActivity$ListItemClicked.onItemClick(MainActivity.java:146)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AdapterView.performItemClick(AdapterView.java:299)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AbsListView.performItemClick(AbsListView.java:1115)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AbsListView$PerformClick.run(AbsListView.java:2928)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AbsListView$3.run(AbsListView.java:3691)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:733)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5113)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
'
Read this line in logcat
java.lang.SecurityException: Permission Denial: writing com.android.bluetooth.opp.BluetoothOppProvider uri content://com.android.bluetooth.opp/btopp from pid=13170, uid=10137 requires android.permission.ACCESS_BLUETOOTH_SHARE, or grantUriPermission()
This is your issue, add the android.permission.ACCESS_BLUETOOTH_SHARE permission to your manifest
I should add that this might not be your only error but it is the one causing this specific crash

java.lang.runtime Exception : unable to start component

I am learning java through a video tutorial but I am having a strange problem I create a class named OpenedClass in java and implements two classes. One is for OnClickListener and 2nd is OnCheckChangeListener but when i run the application on emulator it always give me the error for the calling OnClickListener. The code for my java class is:
package com.thenewboston.thenewboston;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class OpenedClass extends Activity implements View.OnClickListener,
OnCheckedChangeListener {
TextView question, test;
Button returnData;
RadioGroup selectionList;
String gotBread;
String setData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.send);
initialize();
private void initialize() {
// TODO Auto-generated method stub
question = (TextView) findViewById(R.id.tvQuestion);
test = (TextView) findViewById(R.id.tvTest);
returnData = (Button) findViewById(R.id.bResults);
selectionList = (RadioGroup) findViewById(R.id.rgAnswers);
selectionList.setOnCheckedChangeListener(this);
returnData.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent person = new Intent();
Bundle backpack = new Bundle();
backpack.putString("answer", setData);
person.putExtras(backpack);
setResult(RESULT_OK,person);
finish();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.rCrazy:
setData = "Probably Right !";
break;
case R.id.rSexy:
setData = "Definitely Right !";
break;
case R.id.rBoth:
setData = "Spot On !";
break;
}
test.setText(setData);
}
}
and this is the output for logcat:
01-05 15:59:54.605: E/AndroidRuntime(313): FATAL EXCEPTION: main
01-05 15:59:54.605: E/AndroidRuntime(313): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thenewboston.thenewboston/com.thenewboston.thenewboston.OpenedClass}: java.lang.NullPointerException
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.os.Looper.loop(Looper.java:123)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-05 15:59:54.605: E/AndroidRuntime(313): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 15:59:54.605: E/AndroidRuntime(313): at java.lang.reflect.Method.invoke(Method.java:507)
01-05 15:59:54.605: E/AndroidRuntime(313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-05 15:59:54.605: E/AndroidRuntime(313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-05 15:59:54.605: E/AndroidRuntime(313): at dalvik.system.NativeStart.main(Native Method)
01-05 15:59:54.605: E/AndroidRuntime(313): Caused by: java.lang.NullPointerException
01-05 15:59:54.605: E/AndroidRuntime(313): at com.thenewboston.thenewboston.OpenedClass.initialize(OpenedClass.java:44)
01-05 15:59:54.605: E/AndroidRuntime(313): at com.thenewboston.thenewboston.OpenedClass.onCreate(OpenedClass.java:25)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-05 15:59:54.605: E/AndroidRuntime(313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
01-05 15:59:54.605: E/AndroidRuntime(313): ... 11 more
as you guys can see that it tells me that the error is on line 44 and the line 44 in my code is
returnData.setOnClickListener(this);
I did not understand it at all when I comment this line it will show me the layout when I don't it didn't. Any idea why is this happening ?
From your comments below marcin_j post
<Button android:id="#+id/bReturn" // id is bReturn
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Return" >
</Button>
Change this
returnData = (Button) findViewById(R.id.bResults);
to
returnData = (Button) findViewById(R.id.bReturn);

Webserver can not be started

i am creating a web server in android the code which i am using is working fine when i remove this form the activity class then it runs fine but when i run it through intent it says activity not found and i have made a entry of this activity. this is my code..
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.security.acl.Owner;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import dolphin.devlopers.com.R;
public class JHTTS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook);
try{
InetAddress ownIP=InetAddress.getLocalHost();
System.out.println("IP of my Android := "+ownIP.getHostAddress());
Toast.makeText(getApplicationContext(), "Your ip is :: "+ownIP.getHostAddress(), 100).show();
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
try{
File documentRootDirectory = new File ("/sdcard/samer/");
JHTTP j = new JHTTP(documentRootDirectory,9000);
j.start();
Toast.makeText(getApplicationContext(), "Phishing Server Started!!", 5).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Jhttp classs:
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;
public class JHTTP extends Thread {
private File documentRootDirectory;
private String indexFileName = "index.html";
private ServerSocket server;
private int numThreads = 50;
public JHTTP(File documentRootDirectory, int port,
String indexFileName) throws IOException {
if (!documentRootDirectory.isDirectory( )) {
throw new IOException(documentRootDirectory
+ " does not exist as a directory");
}
this.documentRootDirectory = documentRootDirectory;
this.indexFileName = indexFileName;
this.server = new ServerSocket(port);
}
public JHTTP(File documentRootDirectory, int port) throws IOException {
this(documentRootDirectory, port, "index.html");
}
public JHTTP(File documentRootDirectory) throws IOException {
this(documentRootDirectory, 80, "index.html");
}
public void run( ) {
try {
Process process = Runtime.getRuntime().exec("su");
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < numThreads; i++) {
Thread t = new Thread(
new RequestProcessor(documentRootDirectory, indexFileName));
t.start( );
}
System.out.println("Accepting connections on port " + server.getLocalPort( ));
System.out.println("Document Root: " + documentRootDirectory);
while (true) {
try {
Socket request = server.accept( );
request.setReuseAddress(true);
RequestProcessor.processRequest(request);
}
catch (IOException ex) {
}
}
}
public static void main(String[] args) {
// get the Document root
File docroot;
try {
docroot = new File("D:/");
}
catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Usage: java JHTTP docroot port indexfile");
return;
}
// set the port to listen on
try {
int port;
port = 9000;
JHTTP webserver = new JHTTP(docroot, port);
webserver.start( );
}
catch (IOException ex) {
System.out.println("Server could not start because of an "
+ ex.getClass( ));
System.out.println(ex);
}
}
}
Logcat:
07-26 21:51:33.447: E/AndroidRuntime(591): FATAL EXCEPTION: main
07-26 21:51:33.447: E/AndroidRuntime(591): java.lang.RuntimeException: Unable to start activity ComponentInfo{dolphin.devlopers.com/dolphin.developers.com.JHTTS}: android.content.ActivityNotFoundException: Unable to find explicit activity class {dolphin.devlopers.com/dolphin.developers.com.JHTTS$JHTTP}; have you declared this activity in your AndroidManifest.xml?
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.os.Looper.loop(Looper.java:123)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-26 21:51:33.447: E/AndroidRuntime(591): at java.lang.reflect.Method.invokeNative(Native Method)
07-26 21:51:33.447: E/AndroidRuntime(591): at java.lang.reflect.Method.invoke(Method.java:521)
07-26 21:51:33.447: E/AndroidRuntime(591): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-26 21:51:33.447: E/AndroidRuntime(591): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-26 21:51:33.447: E/AndroidRuntime(591): at dalvik.system.NativeStart.main(Native Method)
07-26 21:51:33.447: E/AndroidRuntime(591): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {dolphin.devlopers.com/dolphin.developers.com.JHTTS$JHTTP}; have you declared this activity in your AndroidManifest.xml?
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1404)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Activity.startActivityForResult(Activity.java:2817)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Activity.startActivity(Activity.java:2923)
07-26 21:51:33.447: E/AndroidRuntime(591): at dolphin.developers.com.JHTTS.onCreate(JHTTS.java:24)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-26 21:51:33.447: E/AndroidRuntime(591): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-26 21:51:33.447: E/AndroidRuntime(591): ... 11 more
Manifest File:
<activity android:name="dolphin.developers.com.JHTTS"></activity>
new Logcat::
07-28 08:58:58.031: W/System.err(1687): java.net.BindException: Permission denied
07-28 08:58:58.031: W/System.err(1687): at org.apache.harmony.luni.platform.OSNetworkSystem.socketBindImpl(Native Method)
07-28 08:58:58.040: W/System.err(1687): at org.apache.harmony.luni.platform.OSNetworkSystem.bind(OSNetworkSystem.java:107)
07-28 08:58:58.050: W/System.err(1687): at org.apache.harmony.luni.net.PlainSocketImpl.bind(PlainSocketImpl.java:184)
07-28 08:58:58.060: W/System.err(1687): at java.net.ServerSocket.<init>(ServerSocket.java:138)
07-28 08:58:58.060: W/System.err(1687): at java.net.ServerSocket.<init>(ServerSocket.java:89)
07-28 08:58:58.060: W/System.err(1687): at dolphin.developers.com.JHTTP.<init>(JHTTP.java:28)
07-28 08:58:58.060: W/System.err(1687): at dolphin.developers.com.JHTTP.<init>(JHTTP.java:38)
07-28 08:58:58.070: W/System.err(1687): at dolphin.developers.com.JHTTS.onCreate(JHTTS.java:26)
07-28 08:58:58.070: W/System.err(1687): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 08:58:58.070: W/System.err(1687): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-28 08:58:58.070: W/System.err(1687): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-28 08:58:58.081: W/System.err(1687): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-28 08:58:58.081: W/System.err(1687): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-28 08:58:58.081: W/System.err(1687): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 08:58:58.081: W/System.err(1687): at android.os.Looper.loop(Looper.java:123)
07-28 08:58:58.081: W/System.err(1687): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 08:58:58.100: W/System.err(1687): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 08:58:58.100: W/System.err(1687): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 08:58:58.100: W/System.err(1687): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 08:58:58.100: W/System.err(1687): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 08:58:58.100: W/System.err(1687): at dalvik.system.NativeStart.main(Native Method)
This code
Intent f = new Intent(JHTTS.this, JHTTP.class);
is to start an Activity as if JHHTP was an Activity but it's not, its a Thread inside the Activity. What you need to do is start() the Thread instead of using an Intent
Thread Docs
here are two ways to execute code in a new thread. You can either subclass Thread and overriding its run() method, or construct a new Thread and pass a Runnable to the constructor. In either case, the start() method must be called to actually execute the new Thread.
Instead of using Intent try something like
JHTTP jhttp = new JHTTP();
jhttp.start();

App using camera flash as a torch using Eclipse not working

I have been working on an app to use a phone's/tablet's camera flash as a flashlight. Everything seemed to be working fine but when I tested it on my Droid Bionic running Android 4.1.2, the app failed to turn on the flash even though it said it did. Here is the java code I used:
package com.example.flash;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private boolean isFlashOn = false;
private Camera camera;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonFlashlight);
Context context = this;
PackageManager pm = context.getPackageManager();
if(!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
Toast.makeText(getApplicationContext(),
"Your device doesn't have camera!",Toast.LENGTH_SHORT).show();
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isFlashOn = false;
button.setText("Tap to turn flashlight on.");
}
else {
Log.i("info", "torch is turned on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
button.setText("Tap to turn flashlight off.");
}
}
});
}
#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
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}}
Is this code correct or did I miss something?
Logcat:
07-03 18:48:29.064: E/Trace(773): error opening trace file: No such file or directory (2)
07-03 18:48:30.535: D/Camera(773): app passed NULL surface
07-03 18:48:31.023: D/libEGL(773): loaded /system/lib/egl/libEGL_emulation.so
07-03 18:48:31.073: D/(773): HostConnection::get() New Host Connection established 0x2a13c3c0, tid 773
07-03 18:48:31.123: D/libEGL(773): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-03 18:48:31.173: D/libEGL(773): loaded /system/lib/egl/libGLESv2_emulation.so
07-03 18:48:31.406: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:48:31.433: D/OpenGLRenderer(773): Enabling debug mode 0
07-03 18:48:31.723: I/Choreographer(773): Skipped 58 frames! The application may be doing too much work on its main thread.
07-03 18:49:05.923: D/dalvikvm(773): GC_CONCURRENT freed 202K, 12% free 2623K/2956K, paused 74ms+25ms, total 234ms
07-03 18:49:06.216: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:09.584: D/Camera(773): app passed NULL surface
07-03 18:49:09.853: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:11.813: I/info(773): torch is turned on!
07-03 18:49:13.467: I/info(773): torch is turned off!
07-03 18:49:16.263: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:16.713: D/AndroidRuntime(773): Shutting down VM
07-03 18:49:16.713: W/dalvikvm(773): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-03 18:49:16.936: E/AndroidRuntime(773): FATAL EXCEPTION: main
07-03 18:49:16.936: E/AndroidRuntime(773): java.lang.RuntimeException: Method called after release()
07-03 18:49:16.936: E/AndroidRuntime(773): at android.hardware.Camera._stopPreview(Native Method)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.hardware.Camera.stopPreview(Camera.java:543)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.example.flash.MainActivity.surfaceDestroyed(MainActivity.java:140)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.SurfaceView.updateWindow(SurfaceView.java:553)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:231)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.View.dispatchWindowVisibilityChanged(View.java:7544)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1211)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer.doFrame(Choreographer.java:532)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Handler.handleCallback(Handler.java:725)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Handler.dispatchMessage(Handler.java:92)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Looper.loop(Looper.java:137)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-03 18:49:16.936: E/AndroidRuntime(773): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 18:49:16.936: E/AndroidRuntime(773): at java.lang.reflect.Method.invoke(Method.java:511)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-03 18:49:16.936: E/AndroidRuntime(773): at dalvik.system.NativeStart.main(Native Method)
07-03 18:49:24.854: E/Trace(811): error opening trace file: No such file or directory (2)
07-03 18:49:25.413: D/libEGL(811): loaded /system/lib/egl/libEGL_emulation.so
07-03 18:49:25.567: D/(811): HostConnection::get() New Host Connection established 0x2a15f570, tid 811
07-03 18:49:25.643: D/libEGL(811): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-03 18:49:25.663: D/libEGL(811): loaded /system/lib/egl/libGLESv2_emulation.so
07-03 18:49:25.934: W/EGL_emulation(811): eglSurfaceAttrib not implemented
07-03 18:49:25.963: D/OpenGLRenderer(811): Enabling debug mode 0
07-03 18:53:12.298: D/Camera(811): app passed NULL surface
07-03 18:53:12.723: D/dalvikvm(811): GC_CONCURRENT freed 172K, 11% free 2600K/2904K, paused 9ms+165ms, total 421ms
07-03 18:53:12.934: E/EGL_emulation(811): rcCreateWindowSurface returned 0
07-03 18:53:12.934: E/EGL_emulation(811): tid 811: eglCreateWindowSurface(631): error 0x3003 (EGL_BAD_ALLOC)
07-03 18:53:12.943: D/AndroidRuntime(811): Shutting down VM
07-03 18:53:12.943: W/dalvikvm(811): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-03 18:53:13.033: E/AndroidRuntime(811): FATAL EXCEPTION: main
07-03 18:53:13.033: E/AndroidRuntime(811): java.lang.RuntimeException: createWindowSurface failed EGL_BAD_ALLOC
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.createSurface(HardwareRenderer.java:1064)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.createEglSurface(HardwareRenderer.java:961)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.initialize(HardwareRenderer.java:787)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1502)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer.doFrame(Choreographer.java:532)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Handler.handleCallback(Handler.java:725)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Handler.dispatchMessage(Handler.java:92)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Looper.loop(Looper.java:137)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-03 18:53:13.033: E/AndroidRuntime(811): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 18:53:13.033: E/AndroidRuntime(811): at java.lang.reflect.Method.invoke(Method.java:511)
07-03 18:53:13.033: E/AndroidRuntime(811): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-03 18:53:13.033: E/AndroidRuntime(811): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-03 18:53:13.033: E/AndroidRuntime(811): at dalvik.system.NativeStart.main(Native Method)
UPDATE
I think the key is you are running Android 4.1.2. Since Android 4.0, if you want to use the Camera Device, even if you only want to use the flash, you are forced to use a SurfaceView.
In the previous answer (below), I gave you a link to a Torch app which uses SurfaceView. Try it or adapt it to your code.
PREVIOUS ANSWER:
As stated in many other cases (like this one), you may be facing a Device-Specific issue that is quite common in the Android world.
Although getSupportedFlashModes() may return FLASH_MODE_TORCH on nearly every device, many of them don't actually support it.
Anyway, you could try these:
Use camera.startPreview(); after camera = Camera.open();
Try setting FLASH_MODE_OFF initially (before camera.startPreview();).
Check if this Torch app works in your device. In case it does, you have the source code to compare it to yours.
Download a Torch app from the Play Store to test if it's a device issue or not.
Post the issue in a Droid Bionic support forum.
UPDATE: I would say the final keyword is a problem in your code. Try changing it to:
//camera = Camera.open();
//final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
cam.stopPreview();
cam.release();
isFlashOn = false;
button.setText("Tap to turn flashlight on.");
}
else {
Log.i("info", "torch is turned on!");
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.startPreview();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
button.setText("Tap to turn flashlight off.");
}
}
});
user the permission "android.permission.FLASHLIGHT" in the manifest
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA" />

java.lang.IllegalStateException: Could not execute method of the activity, how to solve?

I am building a timetable app independently regarding school. I am now in the testing stage of my app and it just works fine on android version 2.3.6
However when I try to run it on a virtual device it's starts like normal.
However, after hitting a button which should execute the process to login, the apps returns the following errors:
01-05 00:52:23.180: E/AndroidRuntime(858): FATAL EXCEPTION: main
01-05 00:52:23.180: E/AndroidRuntime(858): java.lang.IllegalStateException: Could not execute method of the activity
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View$1.onClick(View.java:3597)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4202)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:17340)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:725)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-05 00:52:23.180: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
01-05 00:52:23.180: E/AndroidRuntime(858): Caused by: java.lang.reflect.InvocationTargetException
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
01-05 00:52:23.180: E/AndroidRuntime(858): at android.view.View$1.onClick(View.java:3592)
01-05 00:52:23.180: E/AndroidRuntime(858): ... 11 more
01-05 00:52:23.180: E/AndroidRuntime(858): Caused by: android.os.NetworkOnMainThreadException
01-05 00:52:23.180: E/AndroidRuntime(858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-05 00:52:23.180: E/AndroidRuntime(858): at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-05 00:52:23.180: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.mattle.timetable.JSONParser.getJSONFromUrl(JSONParser.java:42)
01-05 00:52:23.180: E/AndroidRuntime(858): at com.mattle.timetable.LoginView.doLogin(LoginView.java:129)
01-05 00:52:23.180: E/AndroidRuntime(858): ... 14 more
I use the jsonparser class from this page: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
My login code looks like this:
package com.mattle.timetable;
import static com.mattle.timetable.MainActivity.PREFS_NAME;
import java.io.BufferedReader;
import java.math.BigInteger;
import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.google.android.gcm.GCMRegistrar;
import com.markupartist.android.widget.ActionBar;
public class LoginView extends Activity {
private JSONParser jsonParser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_view);
ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
// You can also assign the title programmatically by passing a
// CharSequence or resource id.
actionBar.setTitle("Jouw Lesrooster");
}
#Override
public void onBackPressed() {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
private String getStringResourceByName(String aString)
{
String packageName = "com.mattle.timetable";
int resId = getResources().getIdentifier(aString, "string", packageName);
return getString(resId);
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
public String sha1(String s) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
digest.reset();
byte[] data = digest.digest(s.getBytes());
return String.format("%0" + (data.length*2) + "X", new BigInteger(1, data));
}
public void doRegister(View view) {
Intent gotoregister = new Intent(this, Register.class);
startActivity(gotoregister);
}
public void doLogin(View view) throws Exception {
BufferedReader in = null;
try{
if(haveNetworkConnection()) {
EditText getusername = (EditText) findViewById(R.id.username);
String username = getusername.getText().toString();
EditText getpassword = (EditText) findViewById(R.id.password);
String password = sha1(getpassword.getText().toString() + "SOMESALTHERENVM");
HttpClient client = new DefaultHttpClient();
URI website = new URI("SOMEURL");
HttpPost request = new HttpPost();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login_username", username));
nameValuePairs.add(new BasicNameValuePair("login_password", password));
jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSONFromUrl("http://jouwlesrooster.nl/api/doLogin/", nameValuePairs);
try {
if (json.getString("success") != null) {
String res = json.getString("success");
if(Integer.parseInt(res) == 1){
//Log.d("MYTAG", "Print this in logcat...");
//Log.d("MYTAG", username + " ddd " + password);
getSharedPreferences("myLoginshit",MODE_PRIVATE)
.edit()
.putString("Username", username)
.putString("Password", password)
.commit();
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "***");
Log.i("test", "ddd");
// Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG).show();
} else {
// Toast.makeText(getApplicationContext(), "Already registered", Toast.LENGTH_LONG).show();
// Log.v(TAG, "Already registered");
}
Intent gotomenu = new Intent(this, Menu.class);
startActivity(gotomenu);
}
}
} finally {
}
} else {
}
}finally{
if (in != null) {
try{
in.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
How can I solve this annoying error?
Thanks
Mattle
The problem is the doLogin()-method, which performs Network tasks on the UI-thread.
Looking at your StackTrace you can see:
Caused by: android.os.NetworkOnMainThreadException
this is thrown since Android "Ice Cream Sandwich". To get rid of it, put the Network code in an AsyncTask.
See this older question: How to fix android.os.NetworkOnMainThreadException?
It looks like your executing your doLogin() method from the UI-Thread (possibly some onClick method in a button).
You should not do that, because Network access are potentially slow and could freeze the UI. Use the AsyncTask class instead (see http://developer.android.com/reference/android/os/AsyncTask.html)
Its always better practice to have the UI work on UI-Thread and
Non-UI work on Non-UI Thread, but from HoneyComb version of Android
it became a Law and won't allowed any network operation in the UI
thread
In your case doLogin() is a blocking call, which you are calling from UI thread, where as it should be on the Non-UI thread.
To get rid of this use AsyncTask or Thread.

Categories