I am using JSON format to save some data in a file. When i add one or 2 records, evrything is fine. I can easly check that they are correct or process them on my whish. However, when i adding 3rd record, eclipse and AVD frezees and never respond after that, so i need to kill process. i believe that reason is liying inside code below. Tell me please how can i deal with this problem.
Logs shows, that problem is not in infinite for loop.
Can it be cause by LinkedHashSet?
private void writeJSONtoFile(String jsnStr) {
FileOutputStream fos;
Set<String> copy = new LinkedHashSet<String>();
List<String> adds = new ArrayList<String>();
try {
File file = getBaseContext().getFileStreamPath("json_local.xml");
if(file.exists()){
JSONObject json1=null;
try {
json1 = new JSONObject(readData());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String fav = json1.toString();
String record = fav.substring(fav.indexOf('[')+1, fav.indexOf(']'));
Log.d("RECORD",record);
int stop = 0;
for (stop=0; stop < record.lastIndexOf('}');) {
String rec = record.substring(
record.indexOf('{', stop),
record.indexOf('}', stop + 1) + 1);
stop = record.indexOf('}', stop);
Log.d("RECORD",rec);
adds.add(rec);
}
}
String record = jsnStr.substring(jsnStr.indexOf('[')+1, jsnStr.indexOf(']'));
String rec = record.substring(record.indexOf('{'), record.indexOf('}')+1);
adds.add(rec);
copy.clear();
copy.addAll(adds);
adds.clear();
adds.addAll(copy);
int pages=(int) Math.ceil(adds.size()/10.0);
int total=adds.size();
String result = "{\"count_page\":"+pages+",\"count\":\""+total+"\",\"results\":[";
for (String temp : adds) {
result+=temp;
result+=",";
}
result = result.substring(0, result.length() - 1);
result+="]}";
fos = openFileOutput("json_local.xml", Context.MODE_WORLD_WRITEABLE);
fos.write(result.getBytes());
Log.i("json_convert", result);
fos.flush();
fos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("Favorites", "" + jsnStr);
Toast.makeText(getApplicationContext(),
item_title + " добавлено в избранное", Toast.LENGTH_SHORT)
.show();
}
Related
I am trying to develop a function for editing a value in the root file p2p_supplicant.conf which is located on /root/data/misc/wifi/p2p_supplicant.conf
The toast message always showing "File Not Found"
my code is:
private static final String FILE_PATH = "/root/data/misc/wifi/p2p_supplicant.conf";
private static final String MARKER_LINE = "p2p_oper_channel=";
private static final String TEXT_TO_ADD = "11";
public void changeConfig() {
String message = String.format("Entering Config Class");
Toast.makeText(getApplicationContext(), message,Toast.LENGTH_LONG).show();
List<String> fileLines = new ArrayList<String>();
Scanner scanner = null;
try {
scanner = new Scanner(new File(FILE_PATH));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
fileLines.add(line);
if (line.trim().equalsIgnoreCase(MARKER_LINE)) {
fileLines.add(TEXT_TO_ADD);
String message2 = String.format("File Written");
Toast.makeText(getApplicationContext(), message2,Toast.LENGTH_LONG).show();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
String message1 = String.format("File Not found");
Toast.makeText(getApplicationContext(), message1,Toast.LENGTH_LONG).show();
} finally {
if (scanner != null) {
scanner.close();
}
}
PrintWriter pw = null;
try {
pw = new PrintWriter(new File(FILE_PATH));
for (String line : fileLines) {
pw.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
But the code did not find the location/path of the file. Please suggest.
N.B. My phone is rooted.
Basically, you are reading the file, changing the channel then rewriting the whole file. I am looking for a solution where you read the file first, edit it then write it back. Once I resolve that issue I will edit my answer here.
Note before testing it, make a backup file for your wpa_supplicant.conf file in case errors happen.
Step 1: reading the file = check this solution: Executing a Process in Android to read a file
Step 2: looping over the String containing the text of the file and changing the operating channel and saving the the whole text in String text
Step 3: writing text into the the file
Process p;
try {
// Preform su to get root privileges
p = Runtime.getRuntime().exec("su");
// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("echo \""+text+"\" > /data/misc/wifi/p2p_supplicant.conf\n");
// Close the terminal
os.writeBytes("exit\n");
os.flush();
try {
p.waitFor();
if (p.exitValue() != 255) {
// TODO Code to run on success
}
else {
// TODO Code to run on unsuccessful
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
}
} catch (IOException e) {
// TODO Code to run in input/output exception
}
I need when app starts, to check if file exists, if not to be created..
I need a block of code to append files into it
than I need a block of code that read that text line by line
than to remove a line ....
I found this code at stackoverflow, and they said that the file will be created in that location...
//Here I have this :
//Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead
//
String filePath = "/data/data/com.example.myapp/files/text.txt";
File file = new File(filePath);
if(file.exists()){
//Do nothing
}
else{
try {
final String TESTSTRING = new String("");
FileOutputStream fOut = openFileOutput("text.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
osw.flush();
osw.close();
} catch (IOException ioe)
{ioe.printStackTrace();}
}
}
To add Lines in text I made this :
private void write(){
S ="/data/data/com.example.myapp/files/text.txt";
try {
writer = new FileWriter(S, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.write(emri.getText().toString() + "\n" + link.getText().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And when I have to read them :
public class PlayList extends ListActivity {
ArrayList<String> listaE = new ArrayList<String>();
ArrayList<String> listaL = new ArrayList<String>();
InputStream instream;
int resh=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lexo();
String[] mStringArray = new String[listaE.size()];
mStringArray = listaE.toArray(mStringArray);
setListAdapter(new ArrayAdapter<String>(PlayList.this,android.R.layout.simple_list_item_1,mStringArray));
}
private void lexo(){
String S ="/data/data/com.example.myapp/files/text.txt";
try {
// open the file for reading
instream = new FileInputStream(S);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
do {
line = buffreader.readLine();
if ((resh % 2) == 0) {
listaL.add(line);
}
else {
listaE.add(line);
}
// do something with the line
} while (line != null);
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code does not work at all, and is missing the code to remove a line..
So everything I need is :
Code to write into file ( file to be saved because will be used until the app will be installed )
Code to read that file line by line ( so to be added in array, odd lines in one array, other lines in another array )
Code to remove a line from that file ( array to be added in listview and when user touches the line, touched line to be removed )
To add lines on list-activity
Any help will be very very appreciated,
Thanks...
First of all, you should use .getFilesDir().getPath() on your app's context, instead of hardcoding the path. That's commented in your first block. Second, create an OutputStream like this:
OutputStream out = new FileOutputStream(filePath);
If you have an InputStream called in, you'll be able to write it to a file using this code:
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
in.close();
out.close();
When you do create a file, check the rest (I didn't look) and get back to StackOverlow, if it fails. Don't make any of us do all the work, okay? Rip it to small part and make an effort.
Good luck with your work.
In my program i am downloading a Json array file contating data of notices. Each notice contain an address field from where senders image is to be downloaded. So I run another async task to download the images for each json array object. But only 1st image is downloaded no matter how many element json array has. I even tried executeOnExecutor but only folders were created and no images were downloaded.
The onpostexecute method is as below
#Override
protected void onPostExecute(JSONObject jsonObject) {
// TODO Auto-generated method stub
super.onPostExecute(jsonObject);
try {
if (jsonObject.getString("status").equalsIgnoreCase("true")) {
// refining the notices sent by server
JSONArray jsonArray = jsonObject.optJSONArray("notices");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonArrayChild = jsonArray.getJSONObject(i);
// Retrieving data for each notice item
String name = jsonArrayChild.optString("name");
String heading = jsonArrayChild.optString("heading");
String date = jsonArrayChild.optString("date");
String noticeContent = jsonArrayChild
.optString("content");
imageaddress = jsonArrayChild.optString("image");
imageName = imageaddress.substring(
imageaddress.lastIndexOf("/") + 1,
imageaddress.length());
// first we need to download the image from location
// specified in string imageaddress
new ProcessDownloadNoticeSenderImage()
.execute(imageaddress);
// now inserting the overall data into database
// storing the local address of downloaded image in
// database
File file = new File(
Environment.getExternalStorageDirectory()
+ "/veda/images/" + imageName);
String localImageAddress = file.getAbsolutePath();
// storing data in database
noticeMainDatabase.insertNotice(name, heading, date,
noticeContent, localImageAddress);
// first we need to download the image from location
// specified in string imageaddress
}
}
}
and ProcessDownloadNoticeSenderImage is as below
private class ProcessDownloadNoticeSenderImage extends
AsyncTask<String, Integer, Bitmap> {
Bitmap bitmap = null;
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
File folder = new File(Environment.getExternalStorageDirectory()
+ "/veda/images");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(
getApplicationContext(),
"veda/images folder is successfully created to store the images",
Toast.LENGTH_SHORT).show();
}
// saving the downloaded image into folder
File f = new File(Environment.getExternalStorageDirectory(),
"/veda/images/" + imageName);
if (f.exists()) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
} else if (!f.exists()) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
}
try {
bitmap = downloadImageFromServer(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
help me in how to download multiple images so that i can show them in list.
I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.
In my first Activity I'm saving coordinates in FileOutputStream then in another Activity I read the data. But it always adds "null" to my coordinations. Am I doing something wrong?
Activity 1 where I write data to FileOutPutStream
FileOutputStream fos;
try {
String lat, lng;
lat = String.valueOf(location_latitude);
lng = String.valueOf(location_longitude);
fos = openFileOutput("my_latitude", Context.MODE_PRIVATE);
fos.write(lat.getBytes());
fos.close();
fos = openFileOutput("my_longitude", Context.MODE_PRIVATE);
fos.write(lng.getBytes());
fos.close();
Log.e("SPLASHER",lat);
} catch (Exception e) {
e.printStackTrace();
}
Activity 2 where I read data
private void getLocations() {
String[] locations = getApplicationContext().fileList();
for (int i = 0; i < locations.length; i++) {
FileInputStream fis;
try {
fis = openFileInput(locations[i]);
byte[] input = new byte[fis.available()];
if (locations[0].equals("my_latitude")) {
while (fis.read(input) != -1) {
myLat += new String(input);
// int start = myLat.indexOf("null");
// String suffix = myLat.substring(start);
myLat.replaceAll(".*?null", "");
Log.e("READING", myLat);
}
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.e("LOCATTTIEEEE", locations[i]);
}
}
Log
06-07 01:28:10.565: E/SPLASHER(9769): 51.1878003
06-07 01:25:41.660: E/YESSIR(6359): null51.1878167
So I think the writing is okay, but something is going wrong in the reading part?
I have found the error..
I had to initialize String lat, lng; like so String lat="", lng="";
This solved my problem!!