File creation Kotlin Android 12 not working without device restart - json

I am new to Android, I am trying to create 3 json files in device documents directory on app installation if the files do not already exist which they wont.
Problem is that the below sequence works in creating files successfully
device restart
app install
But following sequence is not able to create the files
app uninstall
manual file deletetion from devise
app install
what is going wrong?
Below is the code i am using to create file:
private fun createDirectory() {
val Dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
if (!Dir.exists()) {
Dir.mkdirs()
}
//create all files
val IncomeFile = File(Dir, "Income.json")
if(!IncomeFile.exists()) {
val data: String = "{\"Incomes\":[]}"
val out: FileOutputStream = FileOutputStream(IncomeFile)
out.write(data.toByteArray())
}
val InvFile = File(Dir, "Investments.json")
if(!InvFile.exists()) {
val data: String = "{\"Investments\":[]}"
val out: FileOutputStream = FileOutputStream(InvFile)
out.write(data.toByteArray())
}
val ExpensesFile = File(Dir, "Expenses.json")
if(!ExpensesFile.exists()) {
val data: String = "{\"Expenses\":[]}"
val out: FileOutputStream = FileOutputStream(ExpensesFile)
out.write(data.toByteArray())
}
}
I have the permission request before this:
private fun askPermission() {
ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.READ_EXTERNAL_STORAGE),
PackageManager.PERMISSION_GRANTED)
}
I have the uses in manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Tried createFile and file.write(text) both not able to create new files.

Related

Why did the quality of the GUI deteriorate by half after creating the exe file with jpackage?

I'm using jpackage to convert the jar file to an exe, with the exe file provided by the internal JRE. As a result of the conversion, good results were obtained, the JRE weighs about 38.5 mb.
When I run the exe, the GUI quality is twice as WORSE as in a normal jar! In addition, the window of the new exe file increases on its own. Thus, very strange changes appear, as if the exe file is trying to imitate a window jar file. I want to point out that I am using libGdx for the GUI.
desktop gradle:
{
plugins { id 'org.beryx.runtime' version '1.8.4' }
sourceCompatibility = 1.8
sourceSets.main.java.srcDirs = ["src/"]
sourceSets.main.resources.srcDirs = ["../android/assets"]
mainClassName = "com.iapp.chess.desktop.DesktopLauncher"
def osName = System.getProperty('os.name').toLowerCase(Locale.ROOT)
project.ext.assetsDir = new File("../android/assets")
task runGame(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
}
task debug(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
task dist(type: Jar) {
manifest {
attributes 'Main-Class': project.mainClassName
}
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
with jar
destinationDirectory = file("$buildDir/lib")
}
jpackageImage.dependsOn dist
dist.dependsOn classes
eclipse.project.name = appName + "-desktop"
runtime {
options = ['--strip-debug',
'--compress', '2',
'--no-header-files',
'--no-man-pages',
'--strip-native-commands',
'--vm', 'server']
modules = ['java.base',
'java.desktop',
'jdk.unsupported']
distDir = file(buildDir)
jpackage {
jpackageHome = 'C:\\Program Files\\Java\\jdk-17.0.2'
mainJar = dist.archiveFileName.get()
if (osName.contains('windows')) {
imageOptions = ["--icon", file("../icons/icon.ico")]
} else if (osName.contains('linux')) {
imageOptions = ["--icon", file("../icons/icon.png")]
} else if (osName.contains('mac')) {
imageOptions = ["--icon", file("../icons/icon.icns")]
}
}
}
}

Schema Extension Value is always NULL when updating through Microsoft Graph SDK

Step 1:
Created GraphServiceClient using Microsoft.Graph 4.9.0 and Microsoft.Graph.Core 2.0.5 SDK
var scopes = new[] { "https://graph.microsoft.com/.default" };
ClientSecretCredential clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, new ClientSecretCredentialOptions()
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
});`
GraphServiceClient graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
Step 2:
And created a custom schema extension like below.
SchemaExtension schemaExtension = new SchemaExtension()
{
Id = "data1",
Description = "creating test schema extn",
TargetTypes = new List<string>()
{
"User"
},
Properties = new List<ExtensionSchemaProperty>()
{
new ExtensionSchemaProperty()
{
Name ="prop1",
Type ="String"
}
}
};
Step 3:
Updated the Schema extension status to "Available"
var updatedExtn = await graphServiceClient
.SchemaExtensions[schemaExtension.Id].Request()
.UpdateAsync(new SchemaExtension()
{
Status = "Available"
});
Step 4:
Create Class for extension data
public class data1
{
// You must serialize your property names to camelCase if your SchemaExtension describes as such.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "prop1", Required = Newtonsoft.Json.Required.Default)]
public string Prop1 { get; set; }
}
Step 5:
Find the User and add the created schema extension to the user
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
// The below line is not working. but doesn't throw error
extensionInstance.Add(schemaExtension.Id, new data1 { prop1 = "testing" });
var usrCollection = await graphServiceClient.Users
.Request()
.Filter($"userPrincipalNames eq '{adelev_Mail}'")
.GetAsync();
var usr = usrCollection.FirstOrDefault();
if(usr != null)
{
usr.AdditionalData.Add(extensionInstance);
var updatedUser = await graphServiceClient.Users[usr.Id]
.Request()
.UpdateAsync(usr);
}
Step 6:
When you try to retrieve the extension the value is NULL.
User updatedUser = await graphServiceClient.Users[usr.Id].Request()
.Select($"id, {schemaExtension.Id}")
.GetAsync();
But it works with API using Graph Explorer.
PATCH https://graph.microsoft.com/v1.0/users/{userId}
{
"extXXXXXXXX_data1":
{
"prop1" : "testing"
}
}
Please let me know if I'm missing anything here. Any help here is much appreciated.
You should accessing the data on AdditionalData property. Try looking at user.AdditionalData in your result. Here is a screenshot with my example.
Getting User with Schema extension from Graph explorer.
While using the SDK, i access my custom data in user.AdditionalData
Check this thread - Graph SDK and SchemaExtensions for details.

How to connect mysql to my play slick scalaSlickTest file

object scalaSlickTest extends App {
val parsedConfig = ConfigFactory.parseFile(newFile("src/main/resources/Application.conf"))
val conf = ConfigFactory.load(parsedConfig)
val db = Database.forConfig("mydb")
val lines = new ArrayBuffer[ Any ]()
val employees = TableQuery[ Employees ]
}
I am getting the exception below:
You'll need to pass your loaded config
val db = Database.forConfig("mydb", config)
Otherwise forConfig uses the default config file, which is application.conf (case matters).

How to Add a shapefile data to postgis(postgres) using c#

am trying to add shapefile data to postgis using c#
string path = browse_path.Text;
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
Process p = new Process();
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
p = Process.Start(startInfo);
string chgdir = #"chdir " + #"C:\Program Files\PostgreSQL\9.4\bin\";
p.StandardInput.WriteLine(chgdir);
string pass = #"set PGPASSWORD=postgres";
p.StandardInput.WriteLine(pass);
string cmd = #"shp2pgsql -I -s 4326 " + path + " public.states | psql -U postgres -d postgres";
p.StandardInput.WriteLine(cmd);
p.WaitForExit();
p.Close();`
and for waiting almost 7-8 mins its not working. my shp file is 160 kb only.. but the command is working fine if i run it in the cmd rather then using code..
This is a function I wrote to import shapefiles to PG. It uses Nuget packages CliWrap and Npgsql and I just copied shp2pgsql and its dependencies to a project folder 'Tools' so it can be run on a machine that doesn't have PostgreSQL installed. Its a bit messy and you might need to add error handling but it worked for my needs.
public async static Task<bool> OutputSHPtoPSGLAsync(string shpfile, string host, string user, string pwd, string db, string schema = "public", bool dropIfExists = true, string table = "[SHPNAME]")
{
FileInfo shp = new FileInfo(shpfile);
if (!shp.Exists) return false;
if (table == "[SHPNAME]") table = Path.GetFileNameWithoutExtension(shpfile).ToLower();
string args = string.Format("{0} {1}.{2}", shpfile, schema, table);
Command cli = Cli.Wrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"tools\shp2pgsql.exe")).WithArguments(args);
ExecutionResult eo = await cli.ExecuteAsync();
string sql = eo.StandardOutput;
if (dropIfExists) sql = sql.Replace("CREATE TABLE", string.Format("DROP TABLE IF EXISTS \"{0}\".\"{1}\";\r\nCREATE TABLE", schema, table));
string constring = string.Format("Host={0};Username={1};Password={2};Database={3}", host, user, pwd, db);
using (NpgsqlConnection connection = new NpgsqlConnection(constring))
{
connection.Open();
new NpgsqlCommand(sql, connection).ExecuteNonQuery();
}
return true;
}
I was looking at NetTopologySuite which has type definitions compatible with Npgsql and PostGIS but its all still pre-release and couldn't be bothered working it out.

Working with concatenated JValues in liftjson

Using Scala 2.8 and Lift 2.2.
I'm calling the Github API and requesting repositories for a user. When the user has less than 30 repos one call is made and there is no need to concatenate JValues. However, when the user has more than 30 repos multiple calls are made. I would like to concatenate these results from these calls and then "flatten" them. i.e. The "repositories" name on a JValue should return all the repos not just the first 30.
The code below returns the following: Array(List(JObject(List(JField(repositories,JArray(...JObject(List(JField(repositories,JArray...))))))))
What I want is: Array(List(JObject(List(JField(repositories,JArray(....))))) where the repositories name points to all of the repos.
I've wrestled with this for a bit and can't seem to get it.
import java.io._
import net.liftweb.json.JsonAST._
import net.liftweb.json.JsonParser._
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.{ DefaultHttpClient }
object Github extends Application {
implicit val formats = net.liftweb.json.DefaultFormats
val client = new DefaultHttpClient()
var repos = JArray(List[JValue]())
//Pick on mojombo since he has 30+ repos requires to calls to API
var method = new HttpGet("http://github.com/api/v2/json/repos/show/" + "mojombo" + "?page=1")
var response = client.execute(method)
var instream = response.getEntity.getContent();
var reader = new BufferedReader(new InputStreamReader(instream))
var line1 = reader.readLine
method = new HttpGet("http://github.com/api/v2/json/repos/show/" + "mojombo" + "?page=2")
response = client.execute(method)
instream = response.getEntity.getContent();
reader = new BufferedReader(new InputStreamReader(instream))
val line2 = reader.readLine
println(parse(line1) ++ parse(line2))
}
Function 'merge' should merge those JSONs like you described:
parse(line1) merge parse(line2)
Or more generically:
List(json1, json2, ...).foldLeft(JNothing: JValue)(_ merge _)