Writing contacts on an xml file in Android - android

Hello I have this code(pasted below) which reads and displays the phone contacts in a ListView. Apart from this it should also have one more functionality and that is it should be able to write the contacts as they are being read onto to a xml file. I want to store that xml in my SD card.Please check the code below.
public class ContactsListActivity extends Activity implements
OnItemClickListener
{
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
XmlSerializer serializer = Xml.newSerializer();
File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/new.xml");
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
//we have to bind the new file with a FileOutputStream
FileOutputStream fileos = null;
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
//we set the FileOutputStream as output for the serializer, using UTF-8 encoding
try {
serializer.setOutput(fileos, "UTF-8");
//Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null)
serializer.startDocument(null, Boolean.valueOf(true));
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
//create a new file called "new.xml" in the SD card
//we create a XmlSerializer in order to write xml data
try {
//set indentation option
// serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
//start a tag called "root"
serializer.startTag(null, name);
//i indent code just to have a view similar to xml-tree
serializer.startTag(null, "name");
serializer.text(name);
serializer.endTag(null, "name");
serializer.startTag(null, "phonenumber");
serializer.text(phoneNumber);
serializer.endTag(null, "phonenumber");
serializer.endTag(null, name);
//write xml data into the FileOutputStream
serializer.flush();
//finally we close the file stream
fileos.close();
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
try {
//write xml data into the FileOutputStream
// serializer.flush();
//finally we close the file stream
// fileos.close();
serializer.endDocument();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
phones.close();
ContactAdapter objAdapter = new ContactAdapter(
ContactsListActivity.this, R.layout.alluser_row, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
AlertDialog alert = new AlertDialog.Builder(
ContactsListActivity.this).create();
alert.setTitle("");
alert.setMessage(list.size() + " Contact Found!!!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
} else {
showToast("No Contact Found!!!");
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position,
long id) {
ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
showCallDialog(bean.getName(), bean.getPhoneNo());
}
#SuppressWarnings("deprecation")
private void showCallDialog(String name, final String phoneNo) {
AlertDialog alert = new AlertDialog.Builder(ContactsListActivity.this)
.create();
alert.setTitle("Call?");
alert.setMessage("Are you sure want to call " + name + " ?");
alert.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String phoneNumber = "tel:" + phoneNo;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(phoneNumber));
startActivity(intent);
}
});
alert.show();
}
}
I got this code off the internet and it has a flaw. Only the last read contact is getting added to the xml file on my sd card. When i debugged the code, It shows proper traversing of the code and all contacts.
I would like to add all the read contacts onto the xml file am storing. Any help or correction in this code is very much appreciated. Thanks in advance.

Related

How to capture a photo and immediately put it into an existing pdf?

I couldn't find the solution for my issue. My MainActivity creates a pdf file, the user adds some text via EditText and closes it, no problem with that. Then I have a secondary activity that is calling the MediaStore.ACTION_IMAGE_CAPTURE to take pictures. Once a picture is taken, I'd like to know how I can get this just-captured image into that pdf.
I know I have to reopen the pdf, that is no problem, since I have the pdf file name saved in a variable. The major problem that I see is that I don't know how to programmatically get the file name of the picture, once it is automatically named after "yyyyMMdd_hhMMss.jpg". So how to get the file name from a picture taken by my secondary activity?
*EDIT - Showing code:
From MainActivity:
public class MainActivity extends Activity {
public String FILE = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
public static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
public static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
public static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
public static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
EditText estRep;
EditText sensRep;
EditText cabRep;
String estais;
String sensores;
String cabos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
estRep = (EditText)findViewById(R.id.estaisRep);
sensRep = (EditText)findViewById(R.id.sensoresRep);
cabRep = (EditText)findViewById(R.id.cabosRep);
}
public void gerarPDF(View view) {
estais = estRep.getText().toString();
sensores = sensRep.getText().toString();
cabos = cabRep.getText().toString();
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("CoManut");
alertDialog.setMessage("Picture?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
startActivity(intent);
}
});
alertDialog.setButton2("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Thanks for using this app!", Toast.LENGTH_LONG).show();
MainActivity.this.finish();
}
});
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.show();
}
private static void addMetaData(Document document) {
document.addTitle("Image and text to PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Ricardo Gramowski");
document.addCreator("Ricardo Gramowski");
}
private static void addTitlePage(Document document)
throws DocumentException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
preface.add(new Paragraph("Maintenance report", catFont));
addEmptyLine(preface, 1);
preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph("This doc is important", smallBold));
addEmptyLine(preface, 8);
preface.add(new Paragraph("This doc has been generated by Gramowski.",
redFont));
document.add(preface);
// Start a new page
document.newPage();
}
private void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("Chapter 1", catFont);
anchor.setName("Chapter 1");
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Results", subFont);
Section subCatPart = catPart.addSection(subPara);
addEmptyLine(subPara, 1);
createTable(subCatPart);
document.add(catPart);
}
private void createTable(Section subCatPart)
throws BadElementException {
PdfPTable table = new PdfPTable(2);
PdfPCell c1 = new PdfPCell(new Phrase("Item"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Is that good? (OK/Not OK)"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.addCell("Estais da Torrre ");
table.addCell(estais);
table.addCell("Sensores ");
table.addCell(sensores);
table.addCell("Cabos ");
table.addCell(cabos);
subCatPart.add(table);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
}
And my PhotoActivity:
public class PhotoActivity extends ActionBarActivity {
Button b1;
ImageView iv;
Bitmap bp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
b1 = (Button) findViewById(R.id.button1);
iv = (ImageView) findViewById(R.id.imageView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
// Button to go back to the MainActivity
public void onclickButton2(View view) {
PhotoActivity.this.finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Override your onActivitResult() method in your Main Activity
Here you will get the image bitmap from (Intent Data)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
}
}
Now you have the bitmap. You can add bitmap image like below using the iText Library
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // Try with Bitmap.CompressFormat.JPG also
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
}catch(IOException ex){
ex.printStackTrace();
}
Update1
Your onActivityResult() should look like this.
Note Make sure you have WRITE_EXTERNAL_STORAGE permissions in your menifest.xml file.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
img.setImageBitmap(mImageBitmap);
String fpath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/sample.pdf";
File file = new File(fpath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(fpath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = null;
try {
myImg = Image.getInstance(stream.toByteArray());
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myImg.setAlignment(Image.MIDDLE);
try {
document.add(myImg);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}
This will create a sample.pdf file in your sdcard and add Image bitmap into it.
Hope this helps.
I tested it here its working. :)

Android save to file.txt appending

I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).
public void saveText(View view){
try {
//open file for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
//write information to file
EditText text = (EditText)findViewById(R.id.editText1);
String text2 = text.getText().toString();
out.write(text2);
out.write('\n');
//close file
out.close();
Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
//if caught
Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
}
}
Change this,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
to,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
This will append your new contents to the already existing file.
I Hope it helps!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
try {
String filename = Environment.getExternalStorageDirectory()
.getAbsolutePath() + mFileName;
FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
fw.write(mValue + "\n\n");
fw.close();
} catch (IOException ioe) {
}
}
To display the content of the saved file with the line breaks with a button click use:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(fileTitle);
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
To Delete content of existing file whist retaining the filename you can use:
deleteOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_PRIVATE);
// fOut.write(data.getBytes());
dataTitle = "";
fOut.write(data.getBytes());
fOut.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This worked for me. Takes content of a TextEdit called textTitle. Writes it to file called dataTitle. Then writes a new line with fOut.write("\n"). The next text entered into TextEdit is added to the file with a line break.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Android getting data dynamically from an outside source into a list view activity

I am new at developing Android apps. What I want to do is get data to store into an array and display that data into a list activity view. In a way, the app is going to be similar to a parsed tree where click on one item in the list will take you to a different item and so on and so forth. The thing is I'm going to be having multiple different lists and most are going to be connected somehow (depending on the category selected before hand). I have been looking into the MapsDemo sample application and know there's a way - however I have yet to figure it out. If this is confusing at all please let me know...
Thanks all
Try this out for starters, then once you can do this, then move to using dynamic data. I used this for a very similar project and worked well:
http://www.ezzylearning.com/tutorial.aspx?tid=1763429
Here is the code I used. Maybe this will help you:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.dining);
//Hard coded array
ListData newListItem = new ListData();
ArrayList<ListData> itemObject=null;
try {
itemObject= newListItem.getData(DATAURL);
Log.e(TAG, "item object: "+itemObject.toString());
ListAdapter adapter = new ListAdapter(this, R.layout.dininglistview, itemObject);
//Create listview
this.listView1 = (ListView)this.findViewById(android.R.id.list);
this.listView1.setAdapter(adapter);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Unexpected error", e);
} catch (ServiceException e){
AlertDialog alertDialog = new AlertDialog.Builder(DiningActivity.this).create();
alertDialog.setTitle("Temporarily unavailable");
alertDialog.setMessage("Please contact top25#uievolution.com");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent homeIntent = new Intent(DiningActivity.this, HomeActivity.class);
DiningActivity.this.startActivity(homeIntent);
}
});
alertDialog.show();
}
//implement dining adapter
}
Here is the getData() method that I used to parse the XML:
public ArrayList<ListData> getData(String DATAURL) throws InterruptedException, ServiceException {
ArrayList<ListData> items=null;
HttpURLConnection conn = null;
try {
URL url = new URL(DATAURL);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
if(Thread.interrupted())
{
throw new InterruptedException();
}
items = parseXML(conn);
} catch (MalformedURLException e) {
Log.e(TAG, "Invalid URL", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Unable to connect to URL", e);
}
finally{
if(conn!=null){
conn.disconnect();
}
}
return items;
}
Here is my parser:
private static ArrayList<ListData> parseXML(HttpURLConnection conn) throws ServiceException {
ArrayList<ListData> dataArray = new ArrayList<ListData>();
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
Log.e(TAG, "Parse Configuration issue", e);
throw new ServiceException("Service Exception Error");
} catch (IllegalAccessError e){
Log.e(TAG, "Illegal Accessor Error", e);
throw new ServiceException("Service Exception Error");
}
try {
//parse input from server
Document document = builder.parse(conn.getInputStream());
Element xmlElement = document.getDocumentElement();
NodeList recordNodes = xmlElement.getChildNodes();
//assign parsed data to listItem object
for(int i=0; i<recordNodes.getLength(); i++){
Node record = recordNodes.item(i);
NodeList recordDetails = record.getChildNodes();
ListData listItem = new ListData();
for(int ii=0; ii<recordDetails.getLength(); ii++){
Node detailItem = recordDetails.item(ii);
String detailType = detailItem.getNodeName();
String detailValue = detailItem.getTextContent();
//assign attributes to listItem object
if(detailType.matches("item")){
int itemValue = Integer.parseInt(detailValue);
listItem.setItem(itemValue);
} else if(detailType.matches("title")){
listItem.setTitle(detailValue);
} else if(detailType.matches("subhead")){
listItem.setSubhead(detailValue);
} else if(detailType.matches("thumb")){
ImageManager im = new ImageManager();
Bitmap tImg = im.getImage(detailValue);
listItem.setThumb(tImg);
} else if(detailType.matches("photo")){
ImageManager im = new ImageManager();
Bitmap pImg = im.getImage(detailValue);
listItem.setPhoto(pImg);
} else if(detailType.matches("localAddress")){
listItem.setLocalAddress(detailValue);
} else if(detailType.matches("phone")){
listItem.setPhone(detailValue);
} else if(detailType.matches("webUrl")){
URL webUrl1 = new URL(detailValue);
listItem.setWebURL(webUrl1);
} else if(detailType.matches("facebook")){
listItem.setFacebook(detailValue);
} else if(detailType.matches("twitter")){
listItem.setTwitter(detailValue);
} else if(detailType.matches("latitude")){
float itemLat = Float.parseFloat(detailValue);
listItem.setLatitude(itemLat);
} else if(detailType.matches("longitude")){
float itemLon = Float.parseFloat(detailValue);
listItem.setLatitude(itemLon);
} else if(detailType.matches("notes")){
listItem.setNotes(detailValue);
} else if(detailType.matches("comments")){
listItem.setComments(detailValue);
}
}
dataArray.add(listItem);
}
} catch (SAXException e) {
//TODO
e.printStackTrace();
} catch (IOException e) {
//TODO
e.printStackTrace();
}
return dataArray;
}

display all textfiles in listview created by your app

The code creates a text file in local memory, but how do I get all files created by my application in a list view:
public class newfile extends Activity {
public EditText textBox,textbox2;
FileOutputStream fos=null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newfile);
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
textBox = (EditText) findViewById(R.id.txtText1);
textbox2 = (EditText) findViewById(R.id.fname);
String FILENAME = textbox2.getText().toString();
String value = textBox.getText().toString();
try{
fos = openFileOutput(FILENAME,MODE_WORLD_WRITEABLE);
}
catch(IOException e)
{
e.printStackTrace();
}
byte[] buffer = value.getBytes();
try {
fos.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_LONG).show();
finish();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
You can get a list all application files using Context.fileList. Then use ArrayAdapter to populate your list view

Saving android specific button sound

I have a soundboard and I am trying to save sounds as a ringtone or notification but it is saving the same sound each time which I think is being pulled from " here can anyone shed some light? Thinking it needs to change R.raw.sound1 so it pulls in the sound of which ever button is clicked to bring up the context menu.
I've added the loop and integrs code which makes the buttons work just in case.
EDIT FULL CODE - Error: selectedSoundId cannot be resolved
:- for each three bits of code that say selectedSoundId
Not sure if I have done this bit:
Where and how do I add this?
The "int selectedSoundId" should be declared as a class field, to make it accessible in every class method.
public class Soundboard extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.soundboard);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.backdoors etc};
final int[] soundIds = { R.raw.back_doors etc };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, v.getId(), 0, "Ringtone");
menu.add(0, v.getId(), 0, "Notification");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
else if(item.getTitle()=="Notification"){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
if
(savering(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if
(savenot(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
//Save into Ring tone Folder
public boolean savering(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=50;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false; }
String path="/sdcard/media/audio/ringtones/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Ohhh Ringtone");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
//Save in Notification Folder
public boolean savenot(int ressound){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false; }
String path="/sdcard/media/audio/notifications/";
String filename="ohhh"+".ogg";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(path+filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Ohhh Notification");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "weee");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
}
I don't see where you are replacing the content of
R.raw.sound1
which you are passing as an argument, thus, as I can observe in your code, you are saving the same sound every time you call the saving methods.
EDIT:
Create int variable which will hold the info about last selected sound:
int selectedSoundId;
In onClickListener set the selectedSoundId to sound id connected with current button:
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
//rest of the code
}
Pass the selectedSoundId to savering and savenot methods:
savering(selectedSoundId);
savenot(selectedSoundId);
Hope this helps.
EDIT 2: I'm pasting your code with my corrections.
Ad.2. This is the part when you need to save the info about current sound id.
final int[] buttonIds = { R.raw.sound1 "etc all buttons here"};
final int[] soundIds = {R.raw.sound1 "etc all sounds here"};
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
Ad.3. This is the part of calling the savering and savenot methods.
if
(savering(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}
public void function2(int id){
if
(savenot(selectedSoundId)){
// Code if successful
Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
}
else
{
// Code if unsuccessful
Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
}
}

Categories

Resources