AutoCompleteTextView is not showing strings loaded from the Internal Storage - java

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.

Related

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

how to internal storage item display on another activity of editbox

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();

Unable to read/write to file in android

I'm trying to get my app to write text into a text file from an EditText and read from it into a TextView. It never updated the TextView earlier and now the app is crashing. Any advise would be very appreciated!
public class MainActivity extends Activity implements OnClickListener {
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button rea = (Button) findViewById(R.id.reads1);
rea.setOnClickListener(this);
Button ap = (Button) findViewById(R.id.appends1);
ap.setOnClickListener(this);
}
private void toast(String text)
{
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
}
#SuppressWarnings("resource")
#Override
public void onClick(View v) {
TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);
switch(v.getId()) {
case R.id.reads1:
try
{
FileInputStream fis = new FileInputStream(file);
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
String in;
StringBuffer stringBuffer = new StringBuffer();
while ((in = bfr.readLine()) != null) {
stringBuffer.append(in + "\n");
}
tv.setText(stringBuffer.toString());
toast("File successfully loaded.");
}
catch (Exception ex)
{
toast("Error loading file: " + ex.getLocalizedMessage());
}
break;
case R.id.appends1:
String txt=et.getText().toString();
try
{
FileWriter writer = new FileWriter(file);
writer.write(txt);
writer.flush();
writer.close();
toast("File successfully saved.");
}
catch (Exception ex)
{
toast("Error saving file: " + ex.getLocalizedMessage());
}
break;
}
}
}
Get the sdcard directory using Environment.getExternalStorageDirectory(). Try changing this line in you code:
String file = "sdcard/CSCI598.txt";
With:
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
Also, as #Yahya mentioned make sure you have this permission in your android manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If this doesn't work. Try reading the file like this:
FileReader fr = new FileReader(file);
BufferedReader inputReader = new BufferedReader(fr);
Then use your while loop as it is right now.
Write the file like this
FileWriter out = new FileWriter(file, true);
out.write(txt + "\n");
out.close();
Provide crash log.
Have you given sdcard read write permission in your manifest xml file.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Instead of using hard coded path like String file = "sdcard/CSCI598.txt"; use below
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
As you are using emulator have have you alot sd card space while creating AVD

File is partly downloaded from Webview Android

I getting issue while downloading a PDF file on click of button click in webview.
File is downloaded but the file is partly downloaded that's why i am getting below error
"The document cannot be opened because it is not a valid PDF document"
Below is Asyncetask activity of my to download file:
public class DownloadPDFTask extends AsyncTask<String, Void, Integer>
{
protected ProgressDialog mWorkingDialog; // progress dialog
protected String mFileName; // downloaded file
protected String mError; // for errors
#Override
protected Integer doInBackground(String... urls)
{
String filename = "";
String str[] = urls[2].split(";");
String st[] =str[1].split("=");
filename = st[1];
String extStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
File myDir = new File(extStorageDirectory, "NCR");
File file = new File(extStorageDirectory+"/NCR/"+filename);
// create the directory if it does not exist
if (!myDir.exists())
myDir.mkdirs();
if (file.exists()) {
System.out.println("INSIDE FILE EXIST");
file.delete();
}
try
{
byte[] dataBuffer = new byte[4096];
int nRead = 0;
mFileName = filename;
System.out.println("mFileName<><><> " +mFileName);
// download URL and store to strFileName
// connection to url
java.net.URL urlReport = new java.net.URL(urls[0]);
URLConnection urlConn = urlReport.openConnection();
urlConn.setRequestProperty("User-Agent", urls[1]);
urlConn.setRequestProperty("Content-Disposition", urls[2]);
urlConn.setRequestProperty("Content-Type", "application/pdf");
urlConn.setRequestProperty("Accept", "*/*");
InputStream streamInput = urlReport.openStream();
BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput,8192);
FileOutputStream outputStream = new FileOutputStream(extStorageDirectory+"/NCR/"+mFileName);
while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
outputStream.write(dataBuffer, 0, nRead);
streamInput.close();
outputStream.close();
// displayPdf(mFileName);
}
catch (Exception e)
{
Log.e("myApp", e.getMessage());
mError = e.getMessage();
return (1);
}
return (0);
}
#Override
protected void onPreExecute()
{
// show "Downloading, Please Wait" dialog
mWorkingDialog = ProgressDialog.show(context, "", "Downloading PDF Document, Please Wait...", true);
return;
}
#Override
protected void onPostExecute (Integer result)
{
if (mWorkingDialog != null)
{
mWorkingDialog.dismiss();
mWorkingDialog = null;
}
switch (result)
{
case 0: // a URL
try
{
displayPdf(mFileName);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(context, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}
break;
case 1: // Error
Toast.makeText(context, mError, Toast.LENGTH_LONG).show();
break;
}
}
}
Friends I am stuck on this, Please help me out.
Hope this will help you. I tested this code and this is working fine.
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
int count;
try{
URL url=new URL(params[0]);
URLConnection connection=url.openConnection();
connection.connect();
//getting file length
long lengthOfFile=connection.getContentLength();
//input stream to read file with 8k buffer
InputStream input=new BufferedInputStream(url.openStream(),8192);
//out stream to write file
OutputStream output=new FileOutputStream(Environment.getExternalStorageDirectory()+"/Download/Test/software_testing.pdf");
byte data[]= new byte[1024];
long total =0;
while ((count = input.read(data)) != -1){
if(isCancelled())
return null;
total +=count;
//publishing the progress
//After this onProgressUpdate will be called
if(lengthOfFile > 0){
//System.out.println((int)((total*100)/lengthOfFile)+"First Line");
//Call onProgressUpdate() for display status
publishProgress((int)((total*100)/lengthOfFile));
}
//writing data to file
output.write(data,0,count);
}
//flushing output
output.flush();
//closing stream
output.close();
input.close();
}catch(Exception e){
Log.e("Error", e.getMessage());
System.out.println("Exception :"+e.getMessage());
}
return null;
}
EDITED:
Extend your class from AsyncTask<String, Integer, String> and override its' methods.
`
onPreExecute() used to do process before start the download.
doInBackground(String... params) used to do the process while
downloading the file. The above code is for this method.
onProgressUpdate(Integer... progress) used to do setting the
progress bar according to the current download percentage. Once you use publishProgress (), this method will invoke.
onPostExecute(String file_url) This method can used to dismiss the
dislog after the file was downloaded.
So what you have to do is set your progress bar to update according to the downloading percentage inside onProgressUpdate (Integer... progress). You can use setProgress() method for that.
I hope now you understand the process well :)
This might not be an issue, but your while loop isn't correct:
while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
outputStream.write(dataBuffer, 0, nRead);
The BufferedInputStream.read() returns a -1 when it reaches the end of the stream.
Rather, your terminating condition should be:
while ((nRead = bufferedStreamInput.read(dataBuffer)) != -1)
outputStream.write(dataBuffer, 0, nRead);
I hope this helps.

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