how to internal storage item display on another activity of editbox - java

I am a new android developer. my problem is how items display from internal storage to another activity of the edit box. internal storage file contains (name, age, position) that file item display on three edit box of another activity.
In my project user select MSG from Inbox and that MSG display on text view of activity_main.xml .when I click save button that file stored in internal storage but when I click on the read button that all item display on one edit box not separately all three edit box from internal storage .
for example in my internal storage file contain(abc,14,ANDROID DEVLOPER) that all item display of another activity of three edit box separately.
Mainctivity.java
Read.setOnClickListener(new View.OnClickListener() {
//private Context context;
#Override
public void onClick(View v) {
//Intent intent = new Intent(getApplicationContext(), MessageBox.class);
// TODO Auto-generated method stub
//Intent intent = new Intent(context,MessageBox.class);
try{
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
Intent in = new Intent(getApplicationContext(),data.class);
//String msg = null;
in.putExtra("Msg_Detail", temp);
startActivity(in);
// et.setText(temp);
Toast.makeText(getBaseContext(),"file read",
Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
}
}
});}
public void save(View view){
data = tv.getText().toString();
try {
FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(),"file saved",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
**data.java**
setContentView(R.layout.data);
et11 = (EditText)(findViewById(R.id.eText123));
Intent intent = getIntent();
String msg = intent.getStringExtra("Msg_Detail");
//String msg = intent.getExtras().getString("Msg_Detail");
((EditText)findViewById(R.id.eText123)).setText(msg);
//et11.setText(msg);
activity_main.xml contain save, read and text view and data.xml contain three edit box(name,age,position).how that msg display on edit box of data.xml from internal storage.
Internal file generate and user select msg display on text view of activity_main.xml of another project but how internal file item display on edit box.
problem is when I click read button all data item display on one edit box.

This snippet...
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
Intent in = new Intent(getApplicationContext(),data.class);
//String msg = null;
in.putExtra("Msg_Detail", temp);
startActivity(in);
// et.setText(temp);
Toast.makeText(getBaseContext(),"file read",
Toast.LENGTH_SHORT).show();
}
is actually doing nothing else but starting a new activity and pausing the current activity as soon as the file stream reads the first byte and it also leaves the file stream open. That's why you are probably getting nothing in data.java.
You should wait till the file stream finishes reading the file to start the new activity and make sure you close that stream. So, move the code that creates the intent, starts the activity and shows the toast out of the while loop...
FileInputStream in = null;
int c;
String temp="";
try{
fin = openFileInput(file);
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
}
catch(Exception e){...}
finally{
if(in != null)
in.close();
}
Intent in = new Intent(getApplicationContext(),data.class);
in.putExtra("Msg_Detail", temp);
startActivity(in);
Toast.makeText(getBaseContext(),"file read", Toast.LENGTH_SHORT)
.show();

Related

How I can prompt a file manager into a known path in an android app?

I have the following activity in my application:
public class DisplaySettingsActivity extends AppCompatActivity implements View.OnClickListener {
Button saveIntoFile;
TextView msg;
private ActivityResultLauncher<String> requestPermissionLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_settings);
requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
Log.d("H300s","Permissions Callback");
if (isGranted) {
Log.d("H300s","Permission Accepted 2");
saveFile();
} else {
permissionSaveDenied();
}
});
this.saveIntoFile = (Button)findViewById(R.id.save);
this.saveIntoFile.setOnClickListener(this);
}
private void saveFile(){
Log.d("Η300s","Saving");
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e("H300s","Unable to detect external storage");
saveMsgHandler(null);
return;
}
this.saveIntoFile.setEnabled(false);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyMMdd");
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File( file.getAbsolutePath(),"voip_h300s_"+pattern.format(LocalDate.now())+".txt");
Log.d("H300s",file.toString());
try {
file.createNewFile();
PrintWriter out = new PrintWriter(new FileWriter(file));
out.println("SOME VALUES");
out.close();
saveMsgHandler(file.getAbsolutePath());
} catch (Exception e) {
saveMsgHandler(null);
}
}
#Override
public void onBackPressed() {
return;
}
private void saveMsgHandler(String savePath){
if (savePath == null) {
msg.setText(R.string.could_not_save_settings);
int errorColor = ContextCompat.getColor(this, R.color.error);
msg.setBackgroundColor(errorColor);
} else {
String string = String.format(getString(R.string.save_success),savePath);
msg.setText(string);
int success = ContextCompat.getColor(this, R.color.success);
msg.setBackgroundColor(success);
}
msg.setVisibility(View.VISIBLE);
this.saveIntoFile.setEnabled(true);
}
private void permissionSaveDenied(){
msg.setVisibility(View.VISIBLE);
msg.setText(R.string.could_not_save_settings);
int errorColor = ContextCompat.getColor(this, R.color.error);
msg.setBackgroundColor(errorColor);
this.saveIntoFile.setEnabled(true);
}
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d("H300s","Permission Accepted");
saveFile();
} else {
requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE );
}
}
}
And I want once I save the file to be able to prompt into androids file manager and list the saved file. Any provided solution tells me hot to select a path before saving as seen in this answer or in this question, but instead I want just to show the file into device's file manager after I successfully saving it.
So far, what I've developed is this method:
public void displayFileIntoFileManager(String path){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivity(intent, 7);
}
As a method to call from a button, once I saved the file in saveFile method. But how I can provide the path to the intent in order to be shown?
I just want to list the file into device's file manager.
I want just to show the file into device's file manager after I successfully saving it.
There is no standard Intent action for "open a file manager on a directory containing a specific file", sorry.
So far, what I've developed is this method
ACTION_GET_CONTENT is to allow the user to select a piece of content. If you are not looking to have the user do that, then this is not a suitable Intent action.
How I can prompt a file manager into a known path in an android app?
Wrong question.
You should have asked:
How can i let ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT and ACTION_OPEN_DOCUMENT_TREE open in a pre determined directory?
That question has been answered before.
The trick is to use extra INITIAL_URI.

Show different layout depending on a condition

In my case I have two layout, but I have check the mainactivity's oncreate, if the file is created then open indexpage, activity_indexpage2.xml, but I can't not print this result to check bug.
protected void onCreate(Bundle savedInstanceState) {
try {
contentfile = read();
} catch (IOException e) {
e.printStackTrace();
}
if(contentfile!=null
){
Intent intent = new Intent(MainActivity.this, indexpage.class);
setContentView(R.layout.activity_indexpage2);
startActivity(intent);
}
`super.onCreate(savedInstanceState);`
public String read() throws IOException {
FileInputStream input = this.openFileInput(File_NAME);
byte[] temp = new byte[1024];
StringBuffer stringBuffer = new StringBuffer("");
int len = 0;
while ((len = input.read(temp)) > 0) {
stringBuffer.append(new String(temp, 0, len));
}
input.close();
return stringBuffer.toString();
}
In onCreate() your first statement should be setContentView() then you need to request permission for reading external storage then if you have permission granted then check if the file exists or not. Then depending on the condition show your proper layout or navigate to another activity using Intent

AutoCompleteTextView is not showing strings loaded from the Internal Storage

I want make a AutoCompleteTextview which will load previously saved suggestion from the internal storage. I successfully loaded the strings from the internal storage to a string array(i used logging to check....).
then as i loaded the string array to an adapter and set the adapter to the AutoCompleteTextview, after that the AutoCompleteTextview is not showing the suggestion-strings which i loaded from the Internal Storage but it is showing the suggestion-string(s) which i loaded to the string array at runtime.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this is the array where i am trying to save my data into
loadedString=new String[1];
loadedString[0]="the pre-loaded String"
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, loadedString);
atcv = (AutoCompleteTextView) findViewById(R.id.autocomplete);
int objectCounter = 0;
try {
FileInputStream fis = this.openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String temp;
while ((temp = br.readLine()) != null) {
//here i am calculating the lines of my data-file
//as 1 line contains 1 string object
//so that i can initialize the string array
objectCounter++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//intializing the array
// objectCounter+1 and index =1 because i loaded an object before
loadedString = new String[objectCounter+1];
int index = 1;
try {
FileInputStream fis = this.openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String temp;
while ((temp = br.readLine()) != null) {
loadedString[index] = temp;
index++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
atcv.setAdapter(adapter);
atcv.setThreshold(1);
}
this is the method i am using to save the data
public void saver(View view) {
String string;
if(actv.getText()!=null){
advice = advices.getText().toString();}
advice=advice+"\n";
try{
FileOutputStream fos = openFileOutput(FILENAME, context.MODE_APPEND);
fos.write(advice.getBytes());
fos.close();
Toast.makeText(this, "File saved" , Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(this, "File could not be saved", Toast.LENGTH_LONG).show();
}
Please help. Note that i used notifyDataSetChanged() method. I will be really grateful.
Note that i used notifyDataSetChanged() method
In your case, that is useless. The ArrayAdapter will continue to use your old String[1]. It does not know about your new String[].
First, do not do disk I/O on the main application thread, as you are doing here. Use some form of background operation, like an AsyncTask.
Second, do not read the data in twice, as that is twice as slow for the user. For example, you could use a data structure like ArrayList<String>, which can expand its size on the fly.
Then, do not create the ArrayAdapter until after you have loaded the strings.

getting the image to the previous UI,after selecting the image form gallery

I have UI which contains the four thing
1) Date
2) Message
3) Socialnetworking
4) Attachment with image
1)For Date ,when i click on the date ,then DateTimePicker comes and i select the date
2)For Message ,when i click on the message ,then new activity is there to write the
message and then press the done then message comes back to the previous UI with message contains
3)For Social Networking,same thing as 2 points is happening
4) But for Image attachment ,when i click the attachment ,it opens the new Activity with UI for selecting the image form the gallery ,The image is selected ,but i want to take the image back to the previous UI .
For Coming new activity and for getting back to the previous UI,i am plying with the Visibilty gone and VISIBLE.
please suggest ,what i can do for fetching the image and get back to the previous screen.
Try this in your first activity from which u will pass intent for gallery:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri SelectedImage = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = SelectedImage.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(SelectedImage);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
ProfilePic.setImageURI(SelectedImage);
//or decode if u want to reduce the size
} else {
bitmap = null;
}
FROM_GALLERY = true;
} catch (Exception e) {
Log.e("Uploaderror", e.getLocalizedMessage());
}
}
}

Android Asynctask and progressDialog

What I would like to do is give my app the ability to download my mp3 of my server. So far I have the download mp3 into a audio file working but it's very finicky and cannot be disturbed in order for it to work properly. That being said I would love to have a progress dialog pop up that cannot be canceled so the user can't interrupt the progress while downloading the file to the folder in the background. After reading it seemed that AsyncTask would be the best way to do this but I cannot get it to work. Below is one of the buttons from my code.
public class music extends Activity {
public static int mProgress = 0;
static String filename;
MediaPlayer buttonclicker;
static Toast msg;
public static int totalSize = 0;
public ProgressDialog dialog;
public static boolean isFinished;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
buttonclicker = MediaPlayer.create(this, R.raw.button );
Button boomFullDownload = (Button) findViewById(R.id.boomfull);
boomFullDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonclicker.start();
filename = "boomboom.mp3";
new downloadPumphouseShow().execute(filename);
}
class downloadPumphouseShow extends AsyncTask<String , Void, Void> {
ProgressDialog dialog;
Toast msg;
protected void onPreExecute (){
dialog = new ProgressDialog(context);
msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
dialog.setMessage("Please Wait Loading");
dialog.setCancelable(false);
dialog.show();
}
}
});
protected void onPostExecute(Void result) {
dialog.hide();
dialog.dismiss();
}
protected Void doInBackground(String... params) {
String filename = params[0];
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://lepumphouse.com/media/" + filename );
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File Music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/Pumphouse/Party Cake");
//create a new file, specifying the path, and the filename
if(Music.exists())
msg.show();
else
Music.mkdirs();
//which we want to save the file as.
File file = new File(Music, filename);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int mProgress = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
mProgress += bufferLength;
//this is where you would do something to report the pr0gress, like this maybe
}
//close the output stream when done
// progressDialog.dismiss();
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
So if I stripped out all the code dealing with asynctask it works it's just extremely un-user friendly but the files do download. When I try to add the progress dialog and background task it quits on me. I have a feeling it has to do with the parameters.
protected void onPreExecute() {
dialog=ProgressDialog.show(mContext, "", "Fetching book oversight");
msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG).show;
super.onPreExecute();
}
protected void onPostExecute(Void result) {
if(dialog!=null)
{
dialog.dismiss();
}
}
Try this, a alternate way to show Dialog
Just a quick scan, I don't think you should be calling msg.show(); from the background thread.

Categories

Resources