Error when connecting to MS SQL Server Database - java

I am trying to connect to a MS SQL Server in Android and I am having the following error on the Logcat:
Process: za.co.plus94.rate, PID: 22863
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/ietf/jgss/GSSManager;
at net.sourceforge.jtds.jdbc.TdsCore.createGssToken(TdsCore.java:4400)
at net.sourceforge.jtds.jdbc.TdsCore.sendMSLoginPkt(TdsCore.java:1971)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:617)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:179)
at java.sql.DriverManager.getConnection(DriverManager.java:144)
at za.co.plus94.rate.Helpers.ConnectionClass.connClass(ConnectionClass.java:28)
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:108)
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:95)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.ietf.jgss.GSSManager" on path: DexPathList[[zip file "/data/app/za.co.plus94.rate-2/base.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_dependencies_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_0_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_1_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_2_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_3_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_4_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_5_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_6_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_7_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_8_apk.apk", zip file "/data/app/za.co.plus94.rate-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/za.co.plus94.rate-2/lib/arm64, /vendor/lib64, /system/lib64]]
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 net.sourceforge.jtds.jdbc.TdsCore.createGssToken(TdsCore.java:4400) 
at net.sourceforge.jtds.jdbc.TdsCore.sendMSLoginPkt(TdsCore.java:1971) 
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:617) 
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371) 
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184) 
at java.sql.DriverManager.getConnection(DriverManager.java:179) 
at java.sql.DriverManager.getConnection(DriverManager.java:144) 
at za.co.plus94.rate.Helpers.ConnectionClass.connClass(ConnectionClass.java:28) 
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:108) 
at za.co.plus94.rate.RateKeywordActivity$SendSuggestion.doInBackground(RateKeywordActivity.java:95) 
at android.os.AsyncTask$2.call(AsyncTask.java:295) 
at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
Suppressed: java.lang.ClassNotFoundException: org.ietf.jgss.GSSManager
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)
... 17 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
I think the issue is coming from: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/ietf/jgss/GSSManager; and I don't know how to resolve it.
Here is my DB Connection method class:
public Connection connClass(String username, String password, String database, String server){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";databaseName=" + database + ";user" + username + ";password" + password + ";";
connection = DriverManager.getConnection(ConnectionURL);
}catch (SQLException ex){
Log.e("CONNECTION", ex.getMessage());
}catch(ClassNotFoundException ex){
Log.e("CONNECTION", ex.getMessage());
}catch (Exception ex){
Log.e("CONNECTION", ex.getMessage());
}
return connection;
}
}
I have enabled MultiDex as well.

Try using a previous version of jtds, ver. 1.2.7 to be exact. Try using that one it worked for me when i tried it

Make this change
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + server + "/" + database;
connection = DriverManager.getConnection(ConnectionURL, username, password);

Related

DNS lookup in android- java.lang.NoClassDefFoundError: Failed resolution of: Ljava/applet/Applet;

I am trying to get DNS records like NS,SOA,MX,TXT in android studio.
I've tried using dnsJava library but its looks like Lookup() method is nolonger available.
So,I've tried usig Javax.naming library(JNDL). The code is working fine in Visual studio code. But when i tried to use it on android studio,
It's throwing java.lang.RuntimeException. Can anyone help with it. Alternative solutions also welcomed
This is my code
try {
InetAddress inetAddress = InetAddress.getByName(domainName);
System.out.println(inetAddress.getHostName() + " " + inetAddress.getHostAddress());
// Properties env = new Properties();
Hashtable<String, String> env = new Hashtable<String, String>();
// env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
// env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.dns.DnsContextFactory");
// javax.naming.directory.DirContext iDirC = new javax.naming.directory.InitialDirContext(env);
InitialDirContext iDirC = new InitialDirContext(env);
Attributes attributes = iDirC.getAttributes("dns:/"+inetAddress.getHostName(),new String[]{ "MX" });
NamingEnumeration attributeEnumeration = attributes.get("MX").getAll();
System.out.println("");
while (attributeEnumeration.hasMore())
{
publishProgress(new DnsRecordData("" + attributeEnumeration.next(), Constants.TYPE_SINGLE_TEXT));
// System.out.println("" + attributeEnumeration.next());
}
iDirC.close();
attributeEnumeration.close();
}
catch (UnknownHostException exception)
{
System.err.println("ERROR: Cannot access '" + domainName + "'");
}
catch (NamingException exception) {
System.err.println("ERROR: No DNS record for '" + domainName + "'");
exception.printStackTrace();
}
This is the error im getting
2022-06-09 17:38:31.689 16956-16992/com.example.dnslookup E/ion: ioctl c0044901 failed with code -1: Invalid argument
2022-06-09 17:38:42.116 16956-17056/com.example.dnslookup E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
Process: com.example.dnslookup, PID: 16956
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:415)
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 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:923)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/applet/Applet;
at com.sun.naming.internal.ResourceManager.getInitialEnvironment(ResourceManager.java:126)
at javax.naming.InitialContext.init(InitialContext.java:222)
at javax.naming.InitialContext.<init>(InitialContext.java:202)
at javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:87)
at com.example.dnslookup.fragments.DNSLookupFragment$DnsLookupTask.doInBackground(DNSLookupFragment.java:246)
at com.example.dnslookup.fragments.DNSLookupFragment$DnsLookupTask.doInBackground(DNSLookupFragment.java:194)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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:923) 
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.applet.Applet" on path: DexPathList[[dex file "/data/data/com.example.dnslookup/code_cache/.overlay/base.apk/classes2.dex", dex file "/data/data/com.example.dnslookup/code_cache/.overlay/base.apk/classes.dex", zip file "/data/app/~~y25ZrZ4ar7ynQYi-349WrA==/com.example.dnslookup-gBOkoymEe50KPUupc4c4Ow==/base.apk"],nativeLibraryDirectories=[/data/app/~~y25ZrZ4ar7ynQYi-349WrA==/com.example.dnslookup-gBOkoymEe50KPUupc4c4Ow==/lib/arm64, /system/lib64, /system_ext/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.sun.naming.internal.ResourceManager.getInitialEnvironment(ResourceManager.java:126) 
at javax.naming.InitialContext.init(InitialContext.java:222) 
at javax.naming.InitialContext.<init>(InitialContext.java:202) 
at javax.naming.directory.InitialDirContext.<init>(InitialDirContext.java:87) 
at com.example.dnslookup.fragments.DNSLookupFragment$DnsLookupTask.doInBackground(DNSLookupFragment.java:246) 
at com.example.dnslookup.fragments.DNSLookupFragment$DnsLookupTask.doInBackground(DNSLookupFragment.java:194) 
at android.os.AsyncTask$3.call(AsyncTask.java:394) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
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:923) 

On some phones there is a connection error

I create applications for android and my application connects to a database.
Not waiting for two smartphones pops up when connecting to the database .
finally tested phones work without a problem. Both phones have versions
4.2.2 Android .
Code:
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
String ip,db,DBUserNameStr,DBPasswordStr;
#SuppressLint("NewApi")
public Connection connectionclasss()
{
// Declaring Server ip, username, database name and password
ip = "123.123.123.123:20833";
db = "top";
DBUserNameStr = "userp";
DBPasswordStr = "secret";
// Declaring Server ip, username, database name and password
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
java.sql.Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnectionURL = "jdbc:jtds:sqlserver://" + ip +";databaseName="+ db + ";user=" + DBUserNameStr+ ";password=" + DBPasswordStr + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
The application is crash on the ruler :
connection = DriverManager.getConnection(ConnectionURL);
Log :
04-04 08:58:03.959 8401-8401/com.example.verdent E/error here 1 :: Network error IOException: failed to connect to /12.123.133.123(port 20833): connect failed: ENETUNREACH (Network is unreachable)
--------- beginning of crash
04-04 08:58:03.965 8401-8401/com.example.verdent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.verdent, PID: 8401
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21768)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5917)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:5280) 
at android.view.View$PerformClick.run(View.java:21768) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5917) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749) 
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference
at com.example.verdent.MainActivity.ChcekDate(MainActivity.java:56)
at com.example.verdent.MainActivity.DownloandData(MainActivity.java:43)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:5280) 
at android.view.View$PerformClick.run(View.java:21768) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5917) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749) 
04-04 08:58:03.970 1199-2287/? E/WindowManager: Unknown window type: 1000
Does anyone have an idea why the application turns off on here?

Unable to connect to Azure sql database using JDBC - error with SSL

I am trying to connect to my Azure sql database through a mobile app, using Android Studio.
String connectionURL = "jdbc:sqlserver://****.database.windows.net:1433;database=****;user=****#****;password=*****;encrypt=false;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30";
public void connect(){
Connection connection = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionURL);
}
catch (Exception e) {
e.printStackTrace();
}
This is my code to connect to the database on Azure. The correct JDBC driver has been imported and I am using the correct username/password (marked in ***s).
I keep getting the same error regarding SSL which is as follows -
04-03 23:04:49.449 31439-31439/com.example.melissa.dbtest W/System.err: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Socket closed". ClientConnectionId:*****
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2435)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1816)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2022)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1687)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1528)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:866)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:569)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:569)
04-03 23:04:49.452 31439-31439/com.example.melissa.dbtest W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:237)
04-03 23:04:49.453 31439-31439/com.example.melissa.dbtest W/System.err: at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1753)
I've looked through so many answers and documents but I still can't seem to fix the problem. How can I connect to the Azure database using an SSL?
Could you try using JTDS driver instead
try {
String SQL = "select * from dbo.Student";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://***.database.windows.net:1433/<your database name>;user=***;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}

OutputStreamWriter IOException occurs [duplicate]

This question already has answers here:
Exception 'open failed: EACCES (Permission denied)' on Android
(34 answers)
Closed 6 years ago.
Currently I have this code where I copy paste from here into my source code. But due to some reason unknown to me, the OutputStreamWriter keep giving IOException. And I'm clueless on what cause this and how to fix it. Please help. Below is my code.
public void generateNoteOnSD(){// create a File object for the parent directory
try {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile = new File(path, "mytextfile.txt");
FileOutputStream fOut = new FileOutputStream(myFile,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("the text I want added to the file");
Log.d("Save File Test : ","Success");
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//do something if an IOException occurs.
Log.d("Save File Test : ","Failed");
}
}
I have already included
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in the manifest, and also running the code in AsyncTask - onPostExecute and on AVD with Lollipop version.
My stacktrace:
08-28 11:22:52.788 30478-30478/com.example.azrie.dummyvoice E/YOUR_APP_LOG_TAG: I got an error
java.io.FileNotFoundException: /storage/emulated/0/Download/mytextfile.txt: open failed: EACCES (Permission denied)
at libcore.io.IoBridge.open(IoBridge.java:452)
at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
at com.example.azrie.dummyvoice.ReadHTML.generateNoteOnSD(ReadHTML.java:126)
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:78)
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:37)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
at libcore.io.IoBridge.open(IoBridge.java:438)
at java.io.FileOutputStream.<init>(FileOutputStream.java:87) 
at com.example.azrie.dummyvoice.ReadHTML.generateNoteOnSD(ReadHTML.java:126) 
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:78) 
at com.example.azrie.dummyvoice.ReadHTML.onPostExecute(ReadHTML.java:37) 
at android.os.AsyncTask.finish(AsyncTask.java:651) 
at android.os.AsyncTask.-wrap1(AsyncTask.java) 
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
private static final String FILE_NAME="score.txt";
BufferedOutputStream o;
try {
o = new BufferedOutputStream(new FileOutputStream(new File(getFilesDir(),FILE_NAME)));
String s = //here write what you want to write to the file . its got to be string to work
o.write(s.getBytes());
o.close();
}catch (FileNotFoundException e ){
}catch (IOException e){
}
for me its work for every time and its not opening new file every time.
if you want to see it in action serch FightWithMath in the play store. you will need to fully restart the app after first login and its writing in the main screen and while the game running every time you win

How to prevent printing exception statements in Log files

I am required to check whether a preexisting data base is present in my application, and for that I have written the following code:
public boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try {
String myPath = "/data/data/com.mycomp.sampleapp/databases/myDB.db";
checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
}
catch (Exception e) { }
return checkDB != null ? true : false;
}
The above code working as expected. Now my problem is that it is printing below exception statements in my Logcat. I just want to do nothing and don't want to print exception in my Logcat.
E/SQLiteDatabase(27655): Failed to open database '/data/data/com.mycomp.sampleapp/databases/myDB.db'.
E/SQLiteDatabase(27655): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:338)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:232)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:512)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:206)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:178)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:885)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:855)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:696)
E/SQLiteDatabase(27655): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:671)
E/SQLiteDatabase(27655): at com.mycomp.sampleapp.DataBaseHelper.checkDataBase(DataBaseHelper.java:63)
E/SQLiteDatabase(27655): at com.mycomp.sampleapp.GetData.doInBackground(GetData.java:55)
E/SQLiteDatabase(27655): at com.mycomp.sampleapp.GetData.doInBackground(GetData.java:1)
E/SQLiteDatabase(27655): at android.os.AsyncTask$2.call(AsyncTask.java:288)
E/SQLiteDatabase(27655): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/SQLiteDatabase(27655): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
E/SQLiteDatabase(27655): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/SQLiteDatabase(27655): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/SQLiteDatabase(27655): at java.lang.Thread.run(Thread.java:841)
I have written my code in try/catch block, but still it's printing the exception in my log files.
The exception is generating from the below statement of my code:
checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
Please let me know how can I prevent printing exception in log files.
You can check whether file exists:
File dbFile = mContext.getDatabasePath(myPath);
boolean exists = dbFile.exists();
For your example:
private static final String DB_PATH = "myDB.db";
public boolean checkDataBase() {
File dbFile = mContext.getDatabasePath(DB_PATH);
return dbFile.exists();
}

Categories