Skip to content

Instantly share code, notes, and snippets.

@neonankiti
Created April 9, 2016 14:06
Show Gist options
  • Save neonankiti/05922cf0a44108a2e2732671ed9ef386 to your computer and use it in GitHub Desktop.
Save neonankiti/05922cf0a44108a2e2732671ed9ef386 to your computer and use it in GitHub Desktop.
How to create text file.
package com.finc.strageframewok;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
/**
* This is {@link android.app.Activity} for folder creation.
*/
public class FileCreateActivity extends AppCompatActivity {
private static final int WRITE_REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_create);
findViewById(R.id.create_txt_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createFile();
}
});
}
// create text file
private void createFile() {
// when you create document, you need to add Intent.ACTION_CREATE_DOCUMENT
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
// filter to only show openable items.
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Create a file with the requested Mime type
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TITLE, "Neonankiti.txt");
startActivityForResult(intent, WRITE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == WRITE_REQUEST_CODE) {
switch (resultCode) {
case Activity.RESULT_OK:
if (data != null
&& data.getData() != null) {
writeInFile(data.getData(), "bison is bision");
}
break;
case Activity.RESULT_CANCELED:
break;
}
}
}
private void writeInFile(@NonNull Uri uri, @NonNull String text) {
OutputStream outputStream;
try {
outputStream = getContentResolver().openOutputStream(uri);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
bw.write(text);
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@weysaw
Copy link

weysaw commented Sep 2, 2021

Thank you with this example

@vky342
Copy link

vky342 commented Jul 4, 2024

thanks for the simple example.

@danqdinh
Copy link

danqdinh commented Nov 1, 2024

im receiving requestCode==1 instead of 101
I followed the guide on android doc and startActivityForResult with code 1, is that why it's 1?

@danqdinh
Copy link

danqdinh commented Nov 1, 2024

2024, is it "onActivityResult(ActivityResult result)" instead?
ref: https://developer.android.com/training/basics/intents/result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment