So I need help, I don't know what's I get no errors nothing. Just isn't working
So I got a EditText (TextInput) You write something there for example "potato", when you press the Button (save and addButton) should take whats in the TextInput and put it into the SD card and then the ListView (TextOutput) Should read from that folder and display what it says. Hope you guys understand
The Code I'm using (Updated)
public File file = new File(Environment.getExternalStorageDirectory() + "/accelerometer.html");
public void onCreate1(Bundle savedInstanceState) {
ListView lv = (ListView)findViewById(R.id.textOutput);
final ArrayAdapter<String> arrAdap = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(arrAdap);
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
save();
try {
arrAdap.addAll(load());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arrAdap.notifyDataSetChanged();
}
});
}
public void save() {
String textInput = mTextInput.getText().toString().trim();
if(textInput.equals("")) {
return;
}
}
#SuppressWarnings("unchecked")
public ArrayList<String> load() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
ArrayList<String> returnlist = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
returnlist = (ArrayList<String>) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fis != null)
fis.close();
if(ois != null)
ois.close();
}
return returnlist;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Thanks for all the help in advance :)
add bufferWritter.flush(); after bufferWritter.write(TextImput);
EDIT:
try this code:
private File file = new File(Environment.getExternalStorageDirectory() + "/accelerometer.html");
#Override
public void onCreate(Bundle savedInstanceState) {
ListView lv = (ListView)findViewById(R.id.textOutput);
final ArrayAdapter<String> arrAdap = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(arrAdap);
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
save();
arrAdap.add(load());
arrAdap.notifyDataSetChanged();
}
});
}
public void save() {
String textInput = mTextInput.getText().toString().trim();
if(textInput.equals("")
return;
AddButton.setOnClickListener(new OnClickListener() { //i don't know what this should do
#Override //you set the same text to the same textview
public void onClick(View arg0) { //-> does nothing
mTextInput.setText(mTextInput.getText());
}
});
ArrayList<String> input = new ArrayList<>();
input.add(textInput);
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(input);
oos.flush();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if(fos != null)
fos.close();
if(oos != null)
oos.close();
}
}
public ArrayAdapter<String> load(){
FileInputStream fis;
ObjectInputStream ois;
ArrayList<String> returnlist;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
returnlist = (ArrayList<String>) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fis != null)
fis.close();
if(ois != null)
ois.close();
}
return returnlist;
}
it just coded out of my mind. nothing is tested.
maybe you have to handle some IOExceptions in the finally statement but just put another try{...}catch(){...} around it.
I have also added a comment.
Related
I've created Test.txt on sdcard and write string "test example" on it.
after that, I replace string "test" by "etc" in Test.txt.
this is my code :
String origin_str, old_str , new_str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t2);
origin_str = "test example";
old_str = "test";
new_str = "etc";
Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
bt_create2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
File file = new File(newFolder, "Test" + ".txt");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(origin_str);
myOutWriter.close();
fOut.close();
}
} catch (Exception e) {
System.out.println("e: " + e);
}
}
});
Button bt_replacefileT2 = (Button)findViewById(R.id.bt_replacefileT2);
bt_replacefileT2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] data1 = new byte[1024];
while ( -1 != (len = in.read(data1)) ){
if(new String(data1, 0, len).contains(old_str)){
String s = "";
s = s.replace(old_str, new_str);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
with this code, it was create Test.txt on sdcard and write "test example" on it.
but when replace string "test" by "etc", it not working.
how to fix it?
I will give my code, always worked for me :)
Hope thi can help you :DD
public void saveString(String text){
if(this.isExternalStorageAvailable()){
if(!this.isExternalStorageReadOnly()){
try {
FileOutputStream fos = new FileOutputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeBytes(text);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Toast.makeText(main, "Eror saving String", Toast.LENGTH_SHORT).show();
}
}
}
}
private static boolean isExternalStorageAvailable(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(estadoSD))
return true;
return false;
}
private static boolean isExternalStorageReadOnly(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
return true;
return false;
}
public String getString(){
FileInputStream fis = null;
ObjectInputStream ois = null;
if(this.isExternalStorageAvailable()) {
try {
fis = new FileInputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ois = new ObjectInputStream(fis);
String text = (String)ois.readObject();
return familia;
} catch (FileNotFoundException e) {
//Toast.makeText(main, "The file text doesnt exist", Toast.LENGTH_SHORT).show();
} catch (StreamCorruptedException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch(EOFException e){
try {
if(ois != null)
ois.close();
if(fis != null)
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
//Toast.makeText(main, "eror reading file", Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
//Toast.makeText(main, "String class doesnt exist", Toast.LENGTH_SHORT).show();
}
}
return null;
}
try this
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = line.replace(old,new);
}
br.close();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(line);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
I am getting image from server and display it in my application,and I download that image and downloading is working fine,but when I check my gallery image is not showing there,then in dev tools-Media Scanner I scan my SD card and again check my gallery and then image is showing..so how can I solve it..even I tried it Samsung phone,but with device i need to reboot my device...following is my snippet code...
public class bBusinessCardDL extends Activity{
String[] NAMES = new String[1];
String[] CurID = new String[1];
String[] Detail = new String[1];
String[] Photo = new String[1];
ListView listview;
String BCard;
ImageView image;
Button btnDownload;
ProgressDialog mProgressDialog;
private String Id;
private ImageView bcks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_bu_dl);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + "/mnt/sdcard/")));
bcks=(ImageView)findViewById(R.id.bck_from_bcard);
bcks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intss=new Intent(bBusinessCardDL.this,FirstPage.class);
startActivity(intss);
}
});
Id=this.getIntent().getStringExtra("userids");
System.out.println("checkd advertisement "+Id);
FillData();
btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDownloadAndSave();
Toast msgd = Toast.makeText(getBaseContext(),
"Business card Downloaded..!", Toast.LENGTH_LONG);
msgd.show();
}
});
}
public void mDownloadAndSave() {
File f = new File("/mnt/sdcard/" + Id
+ ".jpg");
//"/mnt/sdcard/"
InputStream is;
try {
is = new URL(BCard).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[] { "ur_file_path" },
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 2048;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static String getJsonFromServer(String url) throws IOException {
BufferedReader inputStream = null;
URL jsonUrl = new URL(url);
URLConnection dc = jsonUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
inputStream = new BufferedReader(new InputStreamReader(
dc.getInputStream()));
// read the JSON results into a string
String jsonResult = inputStream.readLine();
return jsonResult;
}
static class ViewHolder {
TextView VHName;
ImageView VHPhoto;
int position;
}
public void FillData() {
String url = "";
url = "http://www.asdffsfd.com/web-service/b_card.php?user_id="
+ Id;
String jsonString;
jsonString = "";
try {
jsonString = getJsonFromServer(url);
} catch (IOException e) {
}
BCard = "";
try {
JSONArray earthquakes = new JSONArray(jsonString);
NAMES = new String[earthquakes.length()];
Photo = new String[earthquakes.length()];
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject e = earthquakes.getJSONObject(i);
NAMES[i] = e.getString("b_card");
BCard = "http://" + e.getString("b_card");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
BCard = BCard.replace("\\", "");
BCard = BCard.replace(" ", "%20");
ImageView i = (ImageView) findViewById(R.id.BUCARD);
Log.d("Bcard", BCard);
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
BCard).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
after save the image, use below code for scanning file:
MediaScannerConnection.scanFile(this, new String[] { f.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
Someone please read my code its given below,
the process dialog is not showing up,
seems like a minor mistake :D
Thanks in advance.
public class InternalData extends Activity implements OnClickListener {
EditText sharedData;
TextView dataResults;
FileOutputStream fos;
String FILENAME = "internalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
InitializeVars();
}
public void InitializeVars() {
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (EditText) findViewById(R.id.etSharedPrefs);
dataResults = (TextView) findViewById(R.id.tvSharedPrefs);
save.setOnClickListener(this);
load.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bSave:
String data = sharedData.getText().toString();
/*
* //Saving data via File File f = new File(FILENAME); try { fos =
* new FileOutputStream(f); fos.close(); } catch(IOException e) {
* e.printStackTrace(); }
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.bLoad:
new loadSomeStuff().execute(FILENAME);
break;
}
}
public class loadSomeStuff extends AsyncTask<String, Integer, String> {
ProgressDialog dialog = new ProgressDialog(InternalData.this);
protected void onPreExecute(String f) {
// dialog = new ProgressDialog(InternalData.this)
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// all this can be done without making this whole AsyncTask class,
// but it will exaust our activity user interface, / slow it down
String collected = null;
FileInputStream fis = null;
for (int i = 0; i < 20; i++) {
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1) {
collected = new String(dataArray);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
return collected;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
dialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result) {
dataResults.setText(result);
}
}
}
Change your onPreExecute() you're using it wrong, you should this instead
#Override
protected void onPreExecute() {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
i'm new to android and I've been stuck with this for a week now, i did Google a lot
lot and try different things but nothing seem to work for me. I do get something on the client side but i can't open it. here is the server side :
public class MyServer {
Thread m_objThread;
ServerSocket m_server;
String m_strMessage;
DataDisplay m_dataDisplay;
Object m_connected;
public MyServer() {
}
public void setEventListener(DataDisplay dataDisplay) {
m_dataDisplay = dataDisplay;
}
public void startListening() {
m_objThread = new Thread(new Runnable() {
public void run() {
try {
m_server = new ServerSocket(2001);
Socket socket = m_server.accept();
File file = new File("/mnt/extSdCard/pic02.png");
FileInputStream fis = new FileInputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
//send an object with data first here
objectOutputStream.flush();
byte[] b = new byte[socket.getSendBufferSize()];
int read = 0;
while ((read = fis.read(b)) != -1) {
objectOutputStream.write(b, 0, read);
}
objectOutputStream.close();
fis.close();
socket.close();
m_server.close();
} catch (Exception e) {
}
}
});
m_objThread.start();
}
}
The client side :
public class ClientActivity extends Activity {
TextView serverMessage;
Thread m_objThreadClient;
Socket socket;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage = (TextView) findViewById(R.id.textView1);
}
public void Start(View view) {
m_objThreadClient = new Thread(new Runnable() {
public void run() {
try {
socket = new Socket("127.0.0.1", 2001);
InputStream reader = socket.getInputStream();
;
FileOutputStream fos = new FileOutputStream(
"/mnt/extSdCard/in04.png");
byte[] b = new byte[socket.getReceiveBufferSize()];
int read = 0;
while ((read = reader.read(b)) != -1) {
fos.write(b, 0, read);
fos.flush();
// / b = new byte[socket.getReceiveBufferSize()];
}
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
m_objThreadClient.start();
}
}
You're writing with an ObjectOutputStream but you're not reading with an ObjectInputStream. This does not work. You don't need object streams for this. Just use the streams provided by the socket.
NB Don't flush inside the loop. You don't need to keep reallocating the buffer either.
I want to create file in internal memory of android.
then i have to attach it to email.
please help me.
I dont know where this file is stored.???
Read through http://developer.android.com/guide/topics/data/data-storage.html and if you still have questions, post something more specific.
Its easy and try / follow this, i hope it will help you
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
String message = textMessage.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text");
File data = null;
try {
Date dateVal = new Date();
String filename = dateVal.toString();
data = File.createTempFile("Report", ".csv");
FileWriter out = (FileWriter) GenerateCsv.generateCsvFile(
data, "Name,Data1");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(data));
i.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(i, "E-mail"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public class GenerateCsv {
public static FileWriter generateCsvFile(File sFileName,String fileContent) {
FileWriter writer = null;
try {
writer = new FileWriter(sFileName);
writer.append(fileContent);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return writer;
}
}
Add this line in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-
permission>
Here is the code for Create and Read a file,
public class ReadNWriteFile extends Activity {
final String TEST_STRING = new String("Hello Android");
final String FILE_NAME = "SAMPLEFILE.txt";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
fileCreate();
tv.setText(readFile());
setContentView(tv);
}
private void fileCreate() {
try {
OutputStream os = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(TEST_STRING);
osw.close();
} catch (Exception e) {
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
private String readFile() {
try {
FileInputStream fin = openFileInput(FILE_NAME);
InputStreamReader isReader = new InputStreamReader(fin);
char[] buffer = new char[TEST_STRING.length()];
// Fill the buffer with data from file
isReader.read(buffer);
return new String(buffer);
} catch (Exception e) {
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
return null;
}
}
}
To get path, /data/data/package_name/yourFile_Name