Created
June 5, 2023 07:36
-
-
Save st235/488d8d6855dc43704f76d11094f91708 to your computer and use it in GitHub Desktop.
POC of saving to files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
private Button button; | |
ActivityResultLauncher<Intent> launcher = registerForActivityResult( | |
new ActivityResultContracts.StartActivityForResult(), | |
new ActivityResultCallback<ActivityResult>() { | |
@Override | |
public void onActivityResult(ActivityResult result) { | |
Uri uri = result.getData().getData(); | |
try { | |
OutputStream stream = getContentResolver().openOutputStream(uri); | |
PrintWriter writer = new PrintWriter(stream); | |
writer.println("Hello World"); | |
writer.println(55); | |
writer.println("some more text"); | |
writer.close(); | |
Toast.makeText(MainActivity.this, "Finished", Toast.LENGTH_LONG).show(); | |
} catch (FileNotFoundException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} | |
); | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
button = findViewById(R.id.button); | |
button.setOnClickListener(v -> { | |
createFile(); | |
}); | |
} | |
private void createFile() { | |
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); | |
intent.addCategory(Intent.CATEGORY_OPENABLE); | |
intent.setType("application/text"); | |
intent.putExtra(Intent.EXTRA_TITLE, "file.txt"); | |
launcher.launch(intent); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment