Socket EACCESS permission denied with Android Studio - android-studio

I am trying to connect my android emulator to my host computer with socket connection.
I have a simple Java server running and lessening in the host on port 6789.
I have the following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Declares streamText to refer to text area to show all messages
TextView streamText = ((TextView) findViewById(R.id.streamText));
streamText.setText("");
streamText.append("Attempting connection at " + serverIP + " : 6789 \n");
try {
connection = new Socket(InetAddress.getByName(serverIP), 6789); // WHAT IP to connect to host, not virtual device host
streamText.append("Connected to: " + connection.getInetAddress().getHostAddress());
}catch(IOException Exception){
streamText.append(Exception.toString());
Exception.printStackTrace();
}
}
And i am getting this error on logcat:
02-05 11:46:52.257 2663-2663/net.ruiruivo.myfirstapp.chatclientv1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: net.ruiruivo.myfirstapp.chatclientv1, PID: 2663
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{net.ruiruivo.myfirstapp.chatclientv1/net.ruiruivo.myfirstapp.chatclientv1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2071)
at net.ruiruivo.myfirstapp.chatclientv1.MainActivity.<init>(MainActivity.java:33)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
          
And inside my textView window the Exception Says:
java.net.SocketException: socket failed: EACCES (Permission denied)
I have search this and other sites, the answered that appeared the closest to this was <permission android:name="android.permission.INTERNET"></permission> in my manifest but did not solved the problem.
Can anyone help?

Your problem is somewhere else.
1.) post your XML file because it seems that you run into a NPE because streamText is null
2.) You can not do network code in the main thread - this will cause a
android.os.NetworkOnMainThreadException
You have to implement a separate task for that, e.g.:
private class NetworkTask extends AsyncTask<Void, Void, Object>{...}
Update:
Here you go:
#Override
protected void onCreate(Bundle savedInstanceState) {
//your code
new NetworkTask().execute();
}
private class NetworkTask extends AsyncTask<Void, Void, Object>{
#Override
protected Object doInBackground(Void... v) {
try {
//do your network stuff here
return "";
}
catch (HttpException e) {
return e;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(Object result) {
if(result instanceof String){
//everything was fine
}
else{
if(((HttpException)result).getMessage()!=null){
//exception occured
}
}
}
}

Related

MqttAndroidClient.connect() to Raspberry Pi

I am trying to build an app in android studio that makes mqtt publishes to the broker which is on a Raspberry Pi. This is my the onCreate function of my main layout, but it returns this error and I can't figure out why. I can publish from a command prompt so there is no problem with the broker.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bureau_klein);
final String clientId = "Android1";
final String ip = "192.168.1.198:1883";
final MqttAndroidClient client = new MqttAndroidClient(this.getApplicationContext(), ip, clientId);
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d("TAG", "onSuccess");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d("TAG", "onFailure "+ clientId + " " + ip);
Log.e("MYAPP", "exception", exception);
Log.e("MYAPP", "exception", asyncActionToken.getException());
}
});
} catch (MqttException e) {
e.printStackTrace();
}
Error:
06-14 20:24:36.825 5891-5891/com.david.domotica2 E/MYAPP: exception
java.lang.IllegalArgumentException: 192.168.1.198:1883
at org.eclipse.paho.client.mqttv3.MqttConnectOptions.validateURI(MqttConnectOptions.java:473)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:273)
at org.eclipse.paho.android.service.MqttConnection.connect(MqttConnection.java:282)
at org.eclipse.paho.android.service.MqttService.connect(MqttService.java:323)
at org.eclipse.paho.android.service.MqttAndroidClient.doConnect(MqttAndroidClient.java:462)
at org.eclipse.paho.android.service.MqttAndroidClient.access$200(MqttAndroidClient.java:70)
at org.eclipse.paho.android.service.MqttAndroidClient$MyServiceConnection.onServiceConnected(MqttAndroidClient.java:109)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1685)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1714)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6798)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
06-14 20:24:36.825 5891-5891/com.david.domotica2 E/MYAPP: exception
What you are passing to the MqttAndroidClient as an IP address should be a full URI.
e.g. you are passing in 192.168.1.198:1883 which is a IP address and a port but is missing a schema (protocol)
In this case you should be passing in tcp://192.168.1.198:1883

Invalid Thread Access for JavaFX Dialog from e4 EventHandler

I have the following event handler:
public class AssignPAMHandler {
private static final Logger logger = Logger.getLogger(AssignPAMHandler.class);
#Execute
public void execute() {
System.err.println(Thread.currentThread());
showDialog();
}
private void showDialog() {
Display.getDefault().asyncExec(() -> showDialogSWT());
}
private void showDialogSWT() {
System.err.println(Thread.currentThread());
new JFXPanel(); // initializes JavaFX environment
Platform.runLater(() -> showDialogFX());
}
private void showDialogFX() {
System.err.println(Thread.currentThread());
TextInputDialog dialog = new TextInputDialog("walter");
dialog.setTitle("Text Input Dialog");
dialog.setHeaderText("Look, a Text Input Dialog");
dialog.setContentText("Please enter your name:");
dialog.showAndWait().ifPresent(name -> System.out.println("Your name: " + name));
}
}
When I execute this handler via a menu item, I get the following output and exception (the dialog shows up, nevertheless):
Thread[main,6,main]
Thread[main,6,main]
Thread[JavaFX Application Thread,6,main]
Exception in thread "JavaFX Application Thread" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4533)
at org.eclipse.swt.SWT.error(SWT.java:4448)
at org.eclipse.swt.SWT.error(SWT.java:4419)
at org.eclipse.swt.widgets.Widget.error(Widget.java:483)
at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:421)
at org.eclipse.swt.widgets.Widget.getData(Widget.java:537)
at org.eclipse.e4.ui.internal.workbench.swt.ShellActivationListener.handleEvent(ShellActivationListener.java:61)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.filterEvent(Display.java:1605)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1339)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1366)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1345)
at org.eclipse.swt.widgets.Shell.filterProc(Shell.java:807)
at org.eclipse.swt.widgets.Display.filterProc(Display.java:1621)
at com.sun.glass.ui.gtk.GtkApplication.enterNestedEventLoopImpl(Native Method)
at com.sun.glass.ui.gtk.GtkApplication._enterNestedEventLoop(GtkApplication.java:211)
at com.sun.glass.ui.Application.enterNestedEventLoop(Application.java:511)
at com.sun.glass.ui.EventLoop.enter(EventLoop.java:107)
at com.sun.javafx.tk.quantum.QuantumToolkit.enterNestedEventLoop(QuantumToolkit.java:583)
at javafx.stage.Stage.showAndWait(Stage.java:474)
at javafx.scene.control.HeavyweightDialog.showAndWait(HeavyweightDialog.java:162)
at javafx.scene.control.Dialog.showAndWait(Dialog.java:341)
at net.openchrom.chromatogram.xxd.identifier.supplier.chromident.ui.handler.AssignPAMHandler.showDialogFX(AssignPAMHandler.java:54)
The executing thread seems to be the same all the time and the FX dialog shows up. Nevertheless, the exception is thrown.
Replace JFXPanel with FXCanvas to make it run.

Liferay model listener - on after update handler loop

I have created custom model listener for DLFileEntry in Liferay 6.2 GA6. However, the onAfterUpdate method is called repeatedly even when no change has been made on DLFileEntry.
Let me describe the situation:
The file entry is changed through the content administration in Liferay
The onAfterUpdate method is triggered (this is OK)
The onAfterUpdate method is triggered again and again - even though there is no update made on this entry
I' ve dumped the stack trace when the (unexpected) update event happenes. It looks like the onAfterUpdate is triggered by incrementViewCounter(..)method, which is triggered by BufferedIncrementRunnable class
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Thread.java:1365)
at eu.package.hook.model.listener.DLFileEntryModelListener.onAfterUpdate(DLFileEntryModelListener.java:63)
at eu.package.hook.model.listener.DLFileEntryModelListener.onAfterUpdate(DLFileEntryModelListener.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.liferay.portal.kernel.bean.ClassLoaderBeanHandler.invoke(ClassLoaderBeanHandler.java:67)
at com.sun.proxy.$Proxy865.onAfterUpdate(Unknown Source)
at com.liferay.portal.service.persistence.impl.BasePersistenceImpl.update(BasePersistenceImpl.java:340)
at com.liferay.portlet.documentlibrary.service.impl.DLFileEntryLocalServiceImpl.incrementViewCounter(DLFileEntryLocalServiceImpl.java:1450)
at sun.reflect.GeneratedMethodAccessor2034.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:115)
at com.liferay.portal.spring.transaction.DefaultTransactionExecutor.execute(DefaultTransactionExecutor.java:62)
at com.liferay.portal.spring.transaction.TransactionInterceptor.invoke(TransactionInterceptor.java:51)
at com.liferay.portal.spring.aop.ServiceBeanMethodInvocation.proceed(ServiceBeanMethodInvocation.java:111)
at com.liferay.portal.increment.BufferedIncreasableEntry.proceed(BufferedIncreasableEntry.java:48)
at com.liferay.portal.increment.BufferedIncrementRunnable.run(BufferedIncrementRunnable.java:65)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I have read the documenantation about the bufferend increment in portal.properties docs page. It's not recommended to disable this feature.
I have also thought about checking if any relevant change has been made on DLFileEntry object in model listener method. I just wanted to check, if there is any configuration that could be made to bypass the onAfterUpdate method when it's triggered by incrementViewCounter method.
Any help is appreciated.
Update:
On after update method:
private void createMessage(DLFileEntry model, String create) {
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
jsonObject.put("action", create);
jsonObject.put("id", model.getFileEntryId());
MessageBusUtil.sendMessage(SUPIN_MESSAGE_LISTENER_DESTINATION, jsonObject);
}
#Override
public void onAfterUpdate(DLFileEntry model) throws ModelListenerException {
if (LOG.isTraceEnabled()) {
URL[] urls = ((URLClassLoader) (Thread.currentThread().getContextClassLoader())).getURLs();
LOG.trace("Current thread classpath is: " + StringUtils.join(urls, ","));
}
LogMF.info(LOG, "File entry on update event - id {0}" , new Object[]{model.getFileEntryId()});
Thread.dumpStack();
createMessage(model, UPDATE);
}
Here is the message listener (message bus) which performs the on after update actions:
private void createOrUpdate(DLFileEntry model, String createOrUpdate) {
try {
initPermissionChecker(model);
LOG.info("Document " + model.getFileEntryId() + " " + createOrUpdate + "d in Liferay. Creating entry in Safe.");
long documentInSafe;
if (UPDATE.equalsIgnoreCase(createOrUpdate)) {
documentInSafe = (long) model.getExpandoBridge().getAttribute(EXPANDO_SAFE_DOCUMENT_ID);
if (documentInSafe > 0) {
safeClient.updateDocumentInSafe(model);
} else {
documentInSafe = safeClient.createDocumentInSafe(model);
}
} else {
documentInSafe = safeClient.createDocumentInSafe(model);
}
LOG.info("Document " + createOrUpdate +"d successfully with id " + documentInSafe);
saveSafeIDToExpando(model, documentInSafe);
} catch (Exception e) {
LOG.error("Unable to safe ID of document in Safe", e);
}
}
private void saveSafeIDToExpando(DLFileEntry model, long documentInSafe) throws SystemException {
try {
ExpandoTable table = ExpandoTableLocalServiceUtil.getDefaultTable(model.getCompanyId(), DLFileEntry.class.getName());
ExpandoColumn column = ExpandoColumnLocalServiceUtil.getColumn(table.getTableId(), EXPANDO_SAFE_DOCUMENT_ID);
ExpandoValueLocalServiceUtil.addValue(model.getCompanyId(), table.getTableId(), column.getColumnId(), model.getClassPK(), String.valueOf(documentInSafe));
LOG.info("ID of document in Safe updated in expando attribute");
} catch (PortalException e) {
LOG.error("Unable to save Safe document ID in expando." , e);
;
}
}
private void initPermissionChecker(DLFileEntry model) throws Exception {
User safeAdminUser = UserLocalServiceUtil.getUserByScreenName(model.getCompanyId(), SAFE_ADMIN_SCREEN_NAME);
PermissionChecker permissionChecher = PermissionCheckerFactoryUtil.create(safeAdminUser);
PermissionThreadLocal.setPermissionChecker(permissionChecher);
PrincipalThreadLocal.setName(safeAdminUser.getUserId());
CompanyThreadLocal.setCompanyId(model.getCompanyId());
LOG.info("Permission checker successfully initialized.");
}
I suggest this, but I am not sure if it resolves your case.
I've changed the body of your own method onAfterUpdate.
Using TransactionCommitCallbackRegistryUtil you can detach the model update request from the subsequent createMessage logic.
public void onAfterUpdate(DLFileEntry model) throws ModelListenerException {
TransactionCommitCallbackRegistryUtil.registerCallback(new Callable() {
#Override
public Void call() throws Exception {
createMessage(model, UPDATE);
}
}

setReadAccess for a user with a null ID. Parse Object

I am having a serious block right now and cant figure out how to fix this error. When I try to open my NewTipActivity class the app unfortunately stops. I know where the error is located here is the logCat:
Caused by: java.lang.IllegalArgumentException: cannot setReadAccess
for a user with null id
at com.parse.ParseACL.setReadAccess(ParseACL.java:308)
at com.parse.ParseACL.getDefaultACL(ParseACL.java:61)
at com.parse.ParseObject.setDefaultValues(ParseObject.java:3385)
at com.parse.ParseObject.(ParseObject.java:181)
at com.parse.ParseObject.(ParseObject.java:127)
at com.holyapp.danshinn.wingman_etiquette.Tip.(Tip.java:17)
at com.holyapp.danshinn.wingman_etiquette.NewTipActivity.onCreate(NewTipActivity.java:20)
This is the NewTipActivity Class
public class NewTipActivity extends Activity {
private Tip tip;
#Override
protected void onCreate(Bundle savedInstanceState) {
tip = new Tip();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
//New Tip Fragment
setContentView(R.layout.activity_new_tip);
FragmentManager manager = getFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new NewTipFragment();
manager.beginTransaction().add(R.id.fragmentContainer, fragment)
.commit();
}
}
public Tip getCurrentTip() {
return tip;
}
}
I am very new to Parse so I know there is something within that that I am missing. I may not have declared my ParseUser GetAuthor() correctly.. Please help thank you
i've similar error and i found the solution in:
SetReadAccess error for new ParseObject
When you setup Parse you have to add:
ParseUser.getCurrentUser().saveInBackground(); // <--- This Line

NoClassDefFoundError in j2me

I have build a jar file and trying to use it in j2me application. I have included the jar in the build path and imported the required classes as well. But when I run my j2me application I am getting NoClassDefFound Error in the line where I am trying to instantiate the class which is present in the jar.
I can instantiate the classes of the jar in the java project but not in j2me.
Below is the error log:
WARNING - MMA -
C:/Builds/jme-sdk/javacall-javame-sdk-305/implementation/share/jsr135_mmapi/ju_mmconfig.c
line 801: caps: optional settings missing: SuspendBehavior
java.lang.NoClassDefFoundError: com/canvasm/ida/gps/LocationUpdater
- com.test.ida.HelloIDA.(HelloIDA.java:11)
- java.lang.Class.newInstance(), bci=0
- com.sun.midp.main.CldcMIDletLoader.newInstance(), bci=46
- com.sun.midp.midlet.MIDletStateHandler.createMIDlet(), bci=66
- com.sun.midp.midlet.MIDletStateHandler.createAndRegisterMIDlet(), bci=17
- com.sun.midp.midlet.MIDletStateHandler.startSuite(), bci=27
- com.sun.midp.main.AbstractMIDletSuiteLoader.startSuite(), bci=52
- com.sun.midp.main.CldcMIDletSuiteLoader.startSuite(), bci=8
- com.sun.midp.main.AbstractMIDletSuiteLoader.runMIDletSuite(), bci=161
- com.sun.midp.main.AppIsolateMIDletSuiteLoader.main(), bci=26 javacall_lifecycle_state_changed() lifecycle: event is
JAVACALL_LIFECYCLE_MIDLET_SHUTDOWN status is JAVACALL_OK
TestApp(j2me app):
import com.test.gps.LocationUpdater;
public class Hello extends MIDlet {
public Hello() {
LocationUpdater loc = new LocationUpdater();
System.out.println("Loc updater object :"+loc.toString());
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
}
}
JAR file main class:
public class LocationUpdater {
private boolean isUpdateSuccess = false;
public static void main(String[] args){
}
public boolean updateLocation(final String serverUrl, final String userMSISDN) throws LocationException{
AppConstants.url = serverUrl;
AppConstants.msisdn = userMSISDN;
LocationCanvas loc = new LocationCanvas();
isUpdateSuccess = loc.getLocation(serverUrl, userMSISDN);
return isUpdateSuccess;
}
}
LocationCanvas class:
public class LocationCanvas {
private Location location;
private LocationProvider locationProvider;
private Coordinates coordinates;
private Criteria criteria;
private Timer tm;
private double lat, lon;
private String posturl;
private boolean status,updateStatus;
public LocationCanvas() {
}
public boolean getLocation(String url, String msisdn) {
tm = new Timer();
criteria = new Criteria();
criteria.setHorizontalAccuracy(500);
try {
locationProvider = LocationProvider.getInstance(criteria);
if (locationProvider != null) {
tm.wait(4000);
try {
location = locationProvider.getLocation(2000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
coordinates = (Coordinates)location.getQualifiedCoordinates();
if (coordinates != null) {
// Use coordinate information
lat = coordinates.getLatitude();
lon = coordinates.getLongitude();
System.out.println("Latitude :"+lat);
System.out.println("Longitude :"+lon);
}
posturl = url + "?IMEI=" + msisdn
+ "&positioningtype=" + "gps" + "&locationdata=" + lat
+ "," + lon;
}else{
//return false.. cos location provider is null
updateStatus = false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return updateStatus;
}
error log:
Exception in thread "main" java.lang.NoClassDefFoundError:
javax/microedition/location/Coordinates
at com.canvasm.ida.gps.LocationUpdater.updateLocation(LocationUpdater.java:17)
at com.test.HelloTest.main(HelloTest.java:10)
Caused by: java.lang.ClassNotFoundException: javax.microedition.location.Coordinates
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
Any help would be appreciated.
It specifies that class file present at compile time is not found at run time.Check for build time and run time classpaths .
Finally able to solve the issue.
The problem was not in the code. It was due to the compilation issue.
First of all To solve the NoClassDefFoundError , I had to right click on the project and in the build path-> order and export -> check the jar that you have added.
Later while running I faced classFormatError 56.
The jar file which was created, was compiled using 1.6v.
And the j2me application was getting compiled with 1.3v.
I had to recompile my library project with 1.3v and create a jar out of it and used it in the j2me application.
Here is the link to guide: Build a Project from the Command Line - Java ME SDK

Resources