In android studio, my code fails as soon as it reaches the following line.
sipStack = sipFactory.createSipStack(properties);
It gives me the following error.
W/System.err: android.javax.sip.PeerUnavailableException: The Peer SIP Stack: gov.nist.javax.sip.SipStackImpl could not be instantiated. Ensure the Path Name has been set.
...
Caused by: java.lang.NoSuchMethodException: gov.nist.javax.sip.SipStackImpl.<init> [class java.util.Properties]
Do you know what might be causing this error?
I'm using the following dependency for Jain-SIP.
compile group: 'javax.sip', name: 'android-jain-sip-ri', version: '1.3.0-91'
The code has no problem running in IntelliJ.
I'm using Android Studio with Ubuntu 18.04.2 LTS.
My MainActivity class is as follows.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Shootist().init();
}
}
My Shootist class is as follows.
public class Shootist implements SipListener {
public void init() {
SipFactory sipFactory = SipFactory.getInstance();
sipFactory.setPathName("gov.nist");
SipStack sipStack = null;
String transport = "udp";
String peerHostPort = "127.0.01:5070";
Properties properties = new Properties();
properties.setProperty("android.javax.sip.OUTBOUT_PROXY", peerHostPort + "/" + transport);
properties.setProperty("android.javax.sip.STACK_NAME", "shootist");
properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "shootistdebug.txt");
properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "DEBUG");
System.out.println("trying to create sip stack");
// create sip stack
try {
sipStack = sipFactory.createSipStack(properties);
System.out.println("sip stack created");
} catch (PeerUnavailableException e) {
e.printStackTrace();
}
}
#Override
public void processRequest(RequestEvent requestEvent) {
}
#Override
public void processResponse(ResponseEvent responseEvent) {
}
#Override
public void processTimeout(TimeoutEvent timeoutEvent) {
}
#Override
public void processIOException(IOExceptionEvent exceptionEvent) {
}
#Override
public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
}
#Override
public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
}
}
The entire error output is below.
07/23 13:55:28: Launching app
D/EGL_emulation: eglMakeCurrent: 0xe431a180: ver 2 0 (tinfo 0xe430f220)
I/System.out: trying to create sip stack
W/testapplicatio: Accessing hidden method Lgov/nist/javax/sip/SipStackImpl;-><init>(Ljava/util/Properties;)V (blacklist, reflection, denied)
W/System.err: android.javax.sip.PeerUnavailableException: The Peer SIP Stack: gov.nist.javax.sip.SipStackImpl could not be instantiated. Ensure the Path Name has been set.
at android.javax.sip.SipFactory.createStack(SipFactory.java:324)
at android.javax.sip.SipFactory.createSipStack(SipFactory.java:152)
at com.example.jainsiptestapplication.Shootist$override.init(Shootist.java:35)
at com.example.jainsiptestapplication.Shootist$override.access$dispatch(Unknown Source:107)
at com.example.jainsiptestapplication.Shootist.init(Unknown Source:12)
at com.example.jainsiptestapplication.MainActivity.onCreate(MainActivity.java:13)
at android.app.Activity.performCreate(Activity.java:7783)
at android.app.Activity.performCreate(Activity.java:7772)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3235)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3396)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:5264)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5172)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:57)
at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:5223)
at android.app.ActivityThread.access$3400(ActivityThread.java:220)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2019)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7319)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.NoSuchMethodException: gov.nist.javax.sip.SipStackImpl.<init> [class java.util.Properties]
at java.lang.Class.getConstructor0(Class.java:2332)
at java.lang.Class.getConstructor(Class.java:1728)
at android.javax.sip.SipFactory.createStack(SipFactory.java:305)
... 25 more
Hot swapped changes, activity restarted
D/OpenGLRenderer: Setting buffer count to 3, min_undequeued 1, extraBuffers 0
D/EGL_emulation: eglMakeCurrent: 0xe431a180: ver 2 0 (tinfo 0xe430f220)
D/OpenGLRenderer: Setting buffer count to 3, min_undequeued 1, extraBuffers 0
D/EGL_emulation: eglMakeCurrent: 0xe431a180: ver 2 0 (tinfo 0xe430f220)
I/chatty: uid=10154(com.example.jainsiptestapplication) RenderThread identical 1 line
D/EGL_emulation: eglMakeCurrent: 0xe431a180: ver 2 0 (tinfo 0xe430f220)
The main issue is
sipFactory.setPathName("gov.nist");
should be
sipFactory.setPathName("android.gov.nist");
Initialisation is slightly different with android. Perhaps you can start with this example https://github.com/usnistgov/jsip/tree/master/src/examples/android/simplecallsetup and built on top of it.
Related
I'm trying to connect an Android Studio app to a remote MYSQL database but an error is displaying that couldn't create a connection to the database.
Some troubleshooting I did:
Reviewed if the database is running (it is)
Connected from MySQL workbench in my computer to the remote database (I was able to connect and retrieve data)
Also I was developing another app (no Android Studio). I used the same connection classes and I was able to access the data.
--- With this, I think that is not a server issue. ---
Used different JDBC drivers (Gradle implementation below of the versions I used)
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.22'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.23'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.13'
I also tried to add the .jar file in the project files but had other errors that didn't recognized the driver.
--- With this, I noticed that implementing the driver in Gradle is not an error as apparently it is recognizing the driver ---
Note: I'm currently using the gradle implementation.
I added the internet permissions to the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I tried to implement the code that retrieves the data from the data base using an ASYNCTASK but received the following errors
Main class WITH ASYNCTASK (MainActivity.java)*
Note: The code in this class was just to test if I was able to get the data from the database. Is not regarding to any functionality I was trying to implement in the app itself.
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Data");
new GetCultivos().execute();
builder.setPositiveButton("Accept", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
class GetCultivos extends AsyncTask<Void, Void, Void>{
String list = "Data = ";
#Override
protected Void doInBackground(Void... voids) {
CultivoDao cultivoDao = new CultivoDao();
List<Cultivo> listaCultivos = cultivoDao.obtenerCultivos();
for (Cultivo i : listaCultivos){
list = i.getIdCultivo() + " " + i.getNombre() + ", ";
}
return null;
}
#Override
protected void onPostExecute(Void eVoid){
builder.setMessage(list);
}
}
}
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.appmov, PID: 5699
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:399)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/sql/SQLType;
at com.mysql.cj.jdbc.DatabaseMetaData.getInstance(DatabaseMetaData.java:729)
at com.mysql.cj.jdbc.ConnectionImpl.getMetaData(ConnectionImpl.java:1180)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:446)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
at java.sql.DriverManager.getConnection(DriverManager.java:580)
at java.sql.DriverManager.getConnection(DriverManager.java:218)
at com.DAO.appmov.CultivoDao.StartConnection(CultivoDao.java:30)
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:49)
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:228)
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:220)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.sql.SQLType" on path: DexPathList[[zip file "/data/app/com.example.appmov-U33MrmDYU8kMl3MFpFCdcA==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.appmov-U33MrmDYU8kMl3MFpFCdcA==/lib/arm64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.mysql.cj.jdbc.DatabaseMetaData.getInstance(DatabaseMetaData.java:729)
at com.mysql.cj.jdbc.ConnectionImpl.getMetaData(ConnectionImpl.java:1180)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:446)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
at java.sql.DriverManager.getConnection(DriverManager.java:580)
at java.sql.DriverManager.getConnection(DriverManager.java:218)
at com.DAO.appmov.CultivoDao.StartConnection(CultivoDao.java:30)
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:49)
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:228)
at com.example.appmov.MainActivity$GetCultivos.doInBackground(MainActivity.java:220)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
I/Process: Sending signal. PID: 5699 SIG: 9
So I tried to implement the code without an ASYNCTASK, but I'm receiving the error that you can see below in the error log.
Class I use to connect to the database (CultivoDao.java)
public class CultivoDao {
private Connection connection;
private Statement statement;
//Method to start the connection
private void StartConnection() {
String url = "jdbc:mysql://remotemysql.com:3306/hUfMa4wLpe";
String usuario = ***HERE IS THE USERNAME***;
String password = ***HERE IS THE PASSWORD***;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, usuario, password);
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
//Method to close the connection
private void CloseConnection(){
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//Methog to get the data
public List<Cultivo> obtenerCultivos(){
List<Cultivo> listaCultivos = new ArrayList<>();
try {
StartConnection();
ResultSet rs = statement.executeQuery("Select * from cultivo");
while(rs.next()){
Cultivo cultivo = new Cultivo(rs.getInt("idCultivo"), rs.getString("nombre"));
listaCultivos.add(cultivo);
}
}catch (Exception e){
e.printStackTrace();
}
CloseConnection();
return listaCultivos;
}
}
Main class WITHOUT ASYNCTASK (MainActivity.java)*
Note: The code in this class was just to test if I was able to get the data from the database. Is not regarding to any functionality I was trying to implement in the app itself.
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder = new AlertDialog.Builder(MainActivity.this);
String list = "Database list = ";
CultivoDao cultivoDao = new CultivoDao();
List<Cultivo> listaCultivos = cultivoDao.obtenerCultivos();
for (Cultivo i : listaCultivos){
list = i.getIdCultivo() + " " + i.getNombre() + ", ";
}
builder.setTitle("Data");
builder.setMessage(list);
builder.setPositiveButton("Accept", null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
The actual version I'm using is the one without the ASYNCTASK
I'm testing this app in a physical device. I don't know that this can affect in some way.
Error log:
W/System.err: java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:110)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
W/System.err: at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1008)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
at java.sql.DriverManager.getConnection(DriverManager.java:580)
at java.sql.DriverManager.getConnection(DriverManager.java:218)
at com.DAO.appmov.CultivoDao.StartConnection(CultivoDao.java:30)
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:49)
at com.example.appmov.MainActivity$1.onClick(MainActivity.java:88)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:132)
at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
at com.mysql.cj.NativeSession.connect(NativeSession.java:152)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:955)
... 22 more
java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.ResultSet java.sql.Statement.executeQuery(java.lang.String)' on a null object reference
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:50)
at com.example.appmov.MainActivity$1.onClick(MainActivity.java:88)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
W/System.err: at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
java.lang.NullPointerException: Attempt to invoke interface method 'void java.sql.Connection.close()' on a null object reference
at com.DAO.appmov.CultivoDao.CloseConnection(CultivoDao.java:40)
at com.DAO.appmov.CultivoDao.obtenerCultivos(CultivoDao.java:58)
at com.example.appmov.MainActivity$1.onClick(MainActivity.java:88)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
How can I solve this issue without implementing PHP that is another way I found as I can't edit anything of the server where the database is hosted.
Thanks!
ClassNotFoundException: Didn't find class "java.sql.SQLType"
Since java.sql.SQLType was added in Java 8, and doesn't exist at all on Android, you need to use a JDBC driver that is Java 7 compatible, which means you cannot use Connector/J 8.0, but must use version 5.1.
I am using the following code to refresh the weather information on the display of the phone, it worked great the first 2 - 3 times but after that it started crashing and giving me this error.
Here is the code:
package com.example.ma18uus.myapplication;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class weatherView extends AppCompatActivity {
//Main url
static final String main_url = "http://api.weatherapi.com/v1/";
//Live or Weekly forecast
static final String live_weather = "current.xml?key=";
//String sevendays_weather = "orecast.xml?key=";
//API Key + q
static final String API_Key = "c3bdfadb90d5452bb8003318201801&q=";
//Location Setters
static final String location = "London";
//Complete url for todays forecast
static final String URLT = main_url + live_weather + API_Key + location;
//XML node keys
static final String KEY_ITEM = "root";//parent node
static final String KEY_NAME = "name";//name of city, string
static final String KEY_WIND_MPH = "wind_mph";//wind mph, float
static final String KEY_WIND_KPH = "wind_kph";//wind kph, float
static final String KEY_C = "temp_c";//Temperature Celsius, int
static final String KEY_C_FEELS = "feelslike_c";//Temperature feeling Celsius, float
static final String KEY_F = "temp_f";//Temperature Fahrenheit, int
static final String KEY_F_FEELS = "feelslike_f";//Temperature feeling Fahrenheit, float
static final String KEY_HUMIDITY = "humidity";//Humidity Level, int
static final String KEY_CONDITION_TEXT = "text";//Weather Condition i.e. cloudy, sunny, clear, string
ArrayList<HashMap<String, String>> menuItems;
private TextView txt;
String xml;
//#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_view);
menuItems = new ArrayList<HashMap<String, String>>();
txt = (TextView) findViewById(R.id.weather_window);
new weatherTask().execute();
// weatherTask.parseXML();
}
private class weatherTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... voids) {
parseXML();
return null;
}
private void parseXML(){
XmlPullParserFactory parserFactory;
try {
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
try {
InputStream is = new URL(URLT).openStream();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
processParsing(parser);
} catch (IOException e) {
e.printStackTrace();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
ArrayList<WeatherConditions> weather = new ArrayList<>();
int eventType = parser.getEventType();
WeatherConditions currentWeather = null;
while(eventType != XmlPullParser.END_DOCUMENT){
String sName = null;
switch(eventType){
case XmlPullParser.START_TAG:
sName = parser.getName();
if ("root".equals(sName)){
currentWeather = new WeatherConditions();
weather.add(currentWeather);
}else if (currentWeather != null){
if ("name".equals(sName)){
currentWeather.name = parser.nextText();
}
else if ("wind_mph".equals(sName)){
currentWeather.wind_mph = parser.nextText();
}else if ("wind_kph".equals(sName)){
currentWeather.wind_kph = parser.nextText();
}else if ("temp_c".equals(sName)){
currentWeather.celsius = parser.nextText();
}else if ("feelsCelsius".equals(sName)){
currentWeather.feelsCelsius = parser.nextText();
}else if ("fahrenheit".equals(sName)){
currentWeather.fahrenheit = parser.nextText();
}else if ("feelsFahrenheit".equals(sName)){
currentWeather.feelsFahrenheit = parser.nextText();
}else if ("humidity".equals(sName)){
currentWeather.humidity = parser.nextText();
}else if ("text".equals(sName)){
currentWeather.condition_text = parser.nextText();
}
}
break;
}
eventType = parser.next();
}
printWeather(weather);
}
private void printWeather(ArrayList<WeatherConditions> weather){
StringBuilder builder = new StringBuilder();
for (WeatherConditions weatherC : weather){
builder.append(weatherC.name).append("\n").append(weatherC.wind_mph).append("\n").append(weatherC.wind_kph).append("\n").append(weatherC.celsius).append("\n").append(weatherC.feelsCelsius).
append("\n").append(weatherC.fahrenheit).append("\n").append(weatherC.feelsFahrenheit).append("\n").append(weatherC.humidity).append("\n").append(weatherC.condition_text).append("\n");
}
txt.setText(builder.toString());
}
}
}
And here is the error output:
01/24 20:06:05: Launching 'app' on Pixel 2 API 29.
$ adb shell am start -n "com.example.ma18uus.myapplication/com.example.ma18uus.myapplication.ClothesApp" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 24573 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/s.myapplicatio: The ClassLoaderContext is a special shared library.
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/RenderThread: type=1400 audit(0.0:300): avc: denied { write } for name="property_service" dev="tmpfs" ino=8445 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0
W/s.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/s.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xdc973e60, tid 24609
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
D/EGL_emulation: eglCreateContext: 0xe7fbaa20: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xe7fbaa20: ver 3 0 (tinfo 0xe7fe5b10)
W/Gralloc3: mapper 3.x is not supported
D/HostConnection: createUnique: call
HostConnection::get() New Host Connection established 0xdc975b70, tid 24609
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0
D/eglCodecCommon: allocate: Ask for block of size 0x1000
D/eglCodecCommon: allocate: ioctl allocate returned offset 0x3ff805000 size 0x2000
D/EGL_emulation: eglMakeCurrent: 0xe7fbaa20: ver 3 0 (tinfo 0xe7fe5b10)
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 1 0
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#8f4b1f9
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
D/EGL_emulation: eglMakeCurrent: 0xe7fbaa20: ver 3 0 (tinfo 0xe7fe5b10)
D/EGL_emulation: eglMakeCurrent: 0xe7fbaa20: ver 3 0 (tinfo 0xe7fe5b10)
D/EGL_emulation: eglMakeCurrent: 0xe7fbaa20: ver 3 0 (tinfo 0xe7fe5b10)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.ma18uus.myapplication, PID: 24573
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:399)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:8191)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1420)
at android.view.View.requestLayout(View.java:24454)
at android.view.View.requestLayout(View.java:24454)
at android.view.View.requestLayout(View.java:24454)
at android.view.View.requestLayout(View.java:24454)
at android.view.View.requestLayout(View.java:24454)
at android.view.View.requestLayout(View.java:24454)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:380)
at android.view.View.requestLayout(View.java:24454)
at android.widget.TextView.checkForRelayout(TextView.java:9681)
at android.widget.TextView.setText(TextView.java:6269)
at android.widget.TextView.setText(TextView.java:6097)
at android.widget.TextView.setText(TextView.java:6049)
at com.example.ma18uus.myapplication.weatherView$weatherTask.printWeather(weatherView.java:159)
at com.example.ma18uus.myapplication.weatherView$weatherTask.processParsing(weatherView.java:145)
at com.example.ma18uus.myapplication.weatherView$weatherTask.parseXML(weatherView.java:89)
at com.example.ma18uus.myapplication.weatherView$weatherTask.doInBackground(weatherView.java:73)
at com.example.ma18uus.myapplication.weatherView$weatherTask.doInBackground(weatherView.java:68)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
D/EGL_emulation: eglMakeCurrent: 0xe7fbaa20: ver 3 0 (tinfo 0xe7fe5b10)
I/Process: Sending signal. PID: 24573 SIG: 9
Process 24573 terminated.
The first time worked fine, then I changed celsius to temp_c, which is the name in the XML file and still worked fine. Then I changed feelsCelsius to feelslike_c which is the name in the XML file and the crash started and kept on happening even after getting the code back to the original state. I tried uninstalling and reinstalling the app as well, but nothing worked.
AsyncTask executes doInBackground() in the non-UI background thread. It cannot interact with the UI.
On the other hand, the onPostExecute method is allowed to touch UI as it's running in the main thread. So, refactor your AsyncTask to have result:
private class weatherTask extends AsyncTask<Void, Void, String> { // has result now
#Override
protected Void doInBackground(Void... voids) {
XmlPullParserFactory parserFactory;
try {
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
try {
InputStream is = new URL(URLT).openStream();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
return processParsing(parser);
} catch (IOException e) {
e.printStackTrace();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
private String processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
ArrayList<WeatherConditions> weather = new ArrayList<>();
int eventType = parser.getEventType();
WeatherConditions currentWeather = null;
while(eventType != XmlPullParser.END_DOCUMENT){
String sName = null;
switch(eventType){
case XmlPullParser.START_TAG:
sName = parser.getName();
if ("root".equals(sName)){
currentWeather = new WeatherConditions();
weather.add(currentWeather);
}else if (currentWeather != null){
if ("name".equals(sName)){
currentWeather.name = parser.nextText();
}
else if ("wind_mph".equals(sName)){
currentWeather.wind_mph = parser.nextText();
}else if ("wind_kph".equals(sName)){
currentWeather.wind_kph = parser.nextText();
}else if ("temp_c".equals(sName)){
currentWeather.celsius = parser.nextText();
}else if ("feelsCelsius".equals(sName)){
currentWeather.feelsCelsius = parser.nextText();
}else if ("fahrenheit".equals(sName)){
currentWeather.fahrenheit = parser.nextText();
}else if ("feelsFahrenheit".equals(sName)){
currentWeather.feelsFahrenheit = parser.nextText();
}else if ("humidity".equals(sName)){
currentWeather.humidity = parser.nextText();
}else if ("text".equals(sName)){
currentWeather.condition_text = parser.nextText();
}
}
break;
}
eventType = parser.next();
}
return printWeather(weather);
}
private String printWeather(ArrayList<WeatherConditions> weather){
StringBuilder builder = new StringBuilder();
for (WeatherConditions weatherC : weather){
builder.append(weatherC.name).append("\n").append(weatherC.wind_mph).append("\n").append(weatherC.wind_kph).append("\n").append(weatherC.celsius).append("\n").append(weatherC.feelsCelsius).
append("\n").append(weatherC.fahrenheit).append("\n").append(weatherC.feelsFahrenheit).append("\n").append(weatherC.humidity).append("\n").append(weatherC.condition_text).append("\n");
}
return builder.toString();
}
/// THIS METHOD ADDED
#Override
protected void onPostExecute(String result) {
txt.setText(result);
}
}
I'm about to go nuts with this. I keep getting errors when trying to open a text file that's in my assets directory, whose full path name is
C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\
app\src\main\assets
Even though we can SEE filename Dictionary.dic in the assets folder for my project...
... I keep getting errors that the file doesn't exist:
W/`````: Can't open <Dictionary.dic>
W/System.err: java.io.FileNotFoundException: Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:328)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:315)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:841)
Doc says you can use hierarchical name in the open statement:
W/`````: Can't open <C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:330)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:317)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
Same problem.
Can you see any problem with my code? The problem HAS to be obvious, but after two days of trying this and that and utterly failing, and it LOOKS so good and therefore MUST be obvious, but I CAN'T SEE IT....
I've included this in case it's not obvious from above. If this doesn't help, I'm on my own.
Here is how DatabaseConnector gets called in onCreate in MainActivity:
assets = getAssets();
dbc = new DatabaseConnector(getApplicationContext(), assets); // to create DB if needed
Here's how mAssets and SOURCE_NAME are defined; also have DatabaseConnector definition and its call to dbOpenHelper.
Here's how LoadDatabase is called from createDbIfNecessary:
LoadDatabase
__loadDb;
__loadDb = new LoadDatabase();
__loadDb.execute((Object[]) null);
EDIT
Another opinion:
EDIT 2
Please note that changing the filename in the code to lowercase doesn't help. AND it's a DOS file, NOT ANDROID. AND File is never leaving drive C:
public static String DATABASE_SOURCE =
"C:\\Users\\Dov\\Desktop\\ServyHelperton\\app\\src\\main" +
"\\assets\\dictionary.dic";
W/`````: Can't open <C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic
I could add more code to prove what I just said, but trust me. The DATABASE_SOURCE name is ALL I changed.
It appears your path is for Dictionary.dic rather than dictionary.dic
See if that helps
In the end, the fix was sort of easy or maybe dumb luck, because I'm not sure why making the InputStream and Scanner local to doInBackground cured the problem.
Refer to the first picture in the original Question. I made no significant changes to MainActivity, but here is the interesting line in it:
dbc = new DatabaseConnector(getApplicationContext(), getAssets());
This is what worked:
public class DatabaseConnector
{
static Context mContext;
public DatabaseConnector(Context _context, AssetManager _assets)
{
mAssets = _assets;
mContext = _context;
mDbOpenHelper = new DbOpenHelper(_context, DATABASE_NAME, null, 1);
createDbIfNecessary();
}
private class DbOpenHelper extends SQLiteOpenHelper
{
DbOpenHelper(Context _context, String _name, CursorFactory _factory, int _version)
{
super(_context, _name, _factory, _version);
}
private class LoadDatabase extends AsyncTask<Object, Integer, Void>
{
protected Void doInBackground(Object[] params)
{
Scanner scDict = null; // ***** MOVING/ADDING THESE
InputStream stream; // ***** TWO LINES HERE WAS KEY
try{
stream = mContext.getAssets().open(DATABASE_SOURCE);
scDict = new Scanner(stream).useDelimiter("\r\n");
}
catch(IOException e){e.printStackTrace(); System.exit(69);}
}
}
}
}
I am trying to solve this problem for 4 hours and I am completely without hope.
I am using android studio for coding this application. I have created a simple activity which holds edit field for user name and password and next there is a button which is meant to be to submit data from these two edit fields.
I am using mysql connector/j and the java code is following:
package allanko.quizzerappandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.sql.*;
public class LoginActivity extends AppCompatActivity
{
private static CDatabase db;
#Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_login );
db = new CDatabase();
}
/*
public static CDatabase getDB()
{
return db;
}*/
public class CDatabase
{
private String db_name;
private String db_user;
private String db_pass;
private Connection connection;
private boolean isConnected;
public CDatabase()
{
db_name = "jdbc:mysql://localhost:3306/quizzer?useSSL=false";
db_user = "quizzer";
db_pass = "pass";
connection = null;
if( connect() == true )
isConnected = true;
else
isConnected = false;
printResult();
}
private boolean connect()
{
try
{
connection = DriverManager.getConnection( db_name, db_user, db_pass );
return true;
}
catch( Exception exc )
{
exc . printStackTrace();
return false;
}
}
private void printResult()
{
TextView dbText = (TextView)findViewById( R.id.dbText );
if( ! isConnected )
dbText . setText( "Connection to database failed" );
else
dbText . setText( "Connected to database." );
}
public ResultSet query( String query) throws SQLException
{
Statement statement = connection . createStatement();
return statement . executeQuery( query );
}
public boolean isConnected()
{
return isConnected;
}
}
}
When I start this application on whether emulator or my phone, it every time write "Connection to database failed." and I am getting this from console:
W/art: Common causes for lock verification issues are non-optimized dex code
W/art: and incorrect proguard optimizations.
W/art: Class android.support.v4.util.LruCache failed lock verification and will run slower.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/System.err: java.sql.SQLException: java.lang.VerifyError: Verifier rejected class com.mysql.jdbc.CharsetMapping: void com.mysql.jdbc.CharsetMapping.<clinit>() failed to verify: void com.mysql.jdbc.CharsetMapping.<clinit>(): [0x4287] Invalid reg type for array index (Precise Reference: com.mysql.jdbc.MysqlCharset[]) (declaration of 'com.mysql.jdbc.CharsetMapping' appears in /data/app/allanko.quizzerappandroid-1/base.apk)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:877)
W/System.err: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:873)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:422)
W/System.err: at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
W/System.err: at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err: at allanko.quizzerappandroid.LoginActivity$CDatabase.connect(LoginActivity.java:55)
W/System.err: at allanko.quizzerappandroid.LoginActivity$CDatabase.<init>(LoginActivity.java:43)
W/System.err: at allanko.quizzerappandroid.LoginActivity.onCreate(LoginActivity.java:19)
W/System.err: at android.app.Activity.performCreate(Activity.java:6664)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
W/System.err: at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6077)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
W/System.err: Caused by: java.lang.VerifyError: Verifier rejected class com.mysql.jdbc.CharsetMapping: void com.mysql.jdbc.CharsetMapping.<clinit>() failed to verify: void com.mysql.jdbc.CharsetMapping.<clinit>(): [0x4287] Invalid reg type for array index (Precise Reference: com.mysql.jdbc.MysqlCharset[]) (declaration of 'com.mysql.jdbc.CharsetMapping' appears in /data/app/allanko.quizzerappandroid-1/base.apk)
W/System.err: at com.mysql.jdbc.CharsetMapping.getNumberOfCharsetsConfigured(CharsetMapping.java:687)
W/System.err: at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:464)
W/System.err: at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err: at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err: at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
W/System.err: ... 19 more
W/gralloc_ranchu: Gralloc pipe failed
I am completely desperate because I tried to google everything that came to my mind and nothing worked.
Thanks in advance for your answers.
Hope that this link should help you in resolving the issue. It so happens that you would've been referring to the project instead of referring to the corresponding library.
The compiler flags problems of this kind where method signatures won't tally. JVM verifies the bytecode when the class is loaded, and throws a VerifyError when the bytecode tries to do something that it should not be allowed to.
Other possibilities to check on this can be:
It can be because of change in the referenced libraries. Clean Project and followed by a Build might help!
Restarting your IDE might also help as it can be the IDE's fault to refer an incorrect version of the necessary jar.
I had same problem. (Sorry, I can't speak english well).
My solution was change MySql Driver x MariaDB Driver.
I think that problem is that there are two class with same name com.mysql.jdbc.CharsetMapping. When I use MariaDB, org.mariadb.jdbc.Driver I change second class to org.mariadb.jdbc.CharsetMapping, and problem solved.
I wish that this help you.
Best regards.
The same code is working if I run the class from eclipse as a java application but when I am using same class in android studio I am getting the following RuntimeException.
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/security/sasl/Sasl;
The log :
FATAL EXCEPTION: Thread-62267
Process: com.abcd.abcd, PID: 14825
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/security/sasl/Sasl;
at org.jivesoftware.smack.sasl.SASLMechanism.authenticate(SASLMechanism.java:92)
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:319)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at com.abcd.abcd.XmppManager.login(XmppManager.java:99)
at com.abcd.abcd.Main.initializeXmppConnection(Main.java:78)
at com.abcd.abcd.Main.init(Main.java:72)
at com.abcd.abcd.Main.<init>(Main.java:61)
at com.abcd.abcd.MainActivity$1.run(MainActivity.java:32)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassNotFoundException: Didn't find class "javax.security.sasl.Sasl" on path: DexPathList[[zip file "/data/app/com.abcd.abcd-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at org.jivesoftware.smack.sasl.SASLMechanism.authenticate(SASLMechanism.java:92)
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:319)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at com.abcd.abcd.XmppManager.login(XmppManager.java:99)
at com.abcd.abcd.Main.initializeXmppConnection(Main.java:78)
at com.abcd.abcd.Main.init(Main.java:72)
at com.abcd.abcd.Main.<init>(Main.java:61)
at com.abcd.abcd.MainActivity$1.run(MainActivity.java:32)
at java.lang.Thread.run(Thread.java:818)
Suppressed: java.lang.ClassNotFoundException: javax.security.sasl.Sasl
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 10 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
I am stuck here and really not getting what the problem is. Any help guys?
hi if you want to update your library for studio that is one option is good but if you want to use same code in studio as well then you can visit this code here and check if you are doing correct or not.Some problem with ssl permission check here correct way
private XMPPConnection connect() throws XMPPException, SmackException,
IOException {
if ((this.connection != null) && (this.connection.isConnected())) {
return this.connection;
}
ConnectionConfiguration config = new ConnectionConfiguration(HOST1,
5222);
SmackConfiguration.DEBUG_ENABLED = true;
SASLAuthentication.supportSASLMechanism("MD5", 0);
System.setProperty("smack.debugEnabled", "true");
config.setCompressionEnabled(false);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setReconnectionAllowed(true);
config.setSendPresence(true);
config.setRosterLoadedAtLogin(true);
if (Build.VERSION.SDK_INT >= 14) {
config.setKeystoreType("AndroidCAStore");
config.setKeystorePath(null);
} else {
config.setKeystoreType("BKS");
String str = System.getProperty("javax.net.ssl.trustStore");
if (str == null) {
str = System.getProperty("java.home") + File.separator + "etc"
+ File.separator + "security" + File.separator
+ "cacerts.bks";
}
config.setKeystorePath(str);
}
if (connection == null) {
this.connection = new XMPPTCPConnection(config);
}
this.connection.connect();
Roster roster = connection.getRoster();
roster.addRosterListener(new RosterListener() {
#Override
public void presenceChanged(Presence arg0) {
Log.d("deb", "ug");
}
#Override
public void entriesUpdated(Collection<String> arg0) {
Log.d("deb", "ug");
}
#Override
public void entriesDeleted(Collection<String> arg0) {
Log.d("deb", "ug");
}
#Override
public void entriesAdded(Collection<String> arg0) {
Log.d("deb", "ug");
}
});
return this.connection;
}
Thankyou
Hope this will help you.
Android runtime does not have javax.security.sasl package, upgrade your Smack library, there is a custom SASL implementation for android
Probably you should upgrade your library or compile your gradle.
For some informations: What is Gradle in Android Studio?