[Q] java and xml - Java for Android App Development

something is wrong with my setup...
Eclipse Keplar
Windows 7 32bit
java 7u51
db = dbf.newDocumentBuilder(); throws ParserConfigurationError..
please help me. this file is as simple as i could make it.
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XMLHELP {
public static void main(String[] args) {
File file = new File("foo.xml");
DocumentBuilderFactory dbf;
DocumentBuilder db = null;
dbf = DocumentBuilderFactory.newInstance();
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Document doc = db.parse(file);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

ParserConfigurationError means that you misconfigured your factory.
Look here at the newInstance() method in the DocumentBuilderFactory API.
That tells you where it looks for configurations if you don't supply any. One of those files may be messed up or out of place, so give it your own configuration. I just ran the exact same code with a dummy XML file and it worked perfectly with no exceptions or errors. Look up how to configure it yourself or what the default should be, and that could fix your problem.

Related

[Q] help on eclipse app

Hi guys,
First of all i`m completly noob on this so don`t be much hard with me
ok. i`m trying to develop a simple app just to run 4 simple command to install another app but for now the only thing that i can get to work was asking for su permissions...
can someone help me with this?
Thks a lot
HTML:
try {
runtime.exec("su -c busybox mount -o rw,remount /system");
runtime.exec("cp /sdcard/gscript/xrecovery.sh /data/local/tmp/xrecovery.sh");
runtime.exec("chmod 777 /data/local/tmp/xrecovery.sh");
runtime.exec("/data/local/tmp/xrecovery.sh");
runtime.exec("reboot");
}
catch (IOException e) {
e.printStackTrace();
do not think anyone has the knowledge to help me: .- (
My intention is to create a simple program that installs a file which is in sh sdcard,
"sdcard / gscript / xrecovery.sh"
until now could only be granted access to the root but do not know where and what command should I put to run that sh file...
is that no one can / want help?
thks
HTML:
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class xRecovery extends Activity {
Button app_name;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app_name = (Button)findViewById(R.id.TextView01);
xRecovery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {;
}
});
setContentView(R.layout.main);
try {
Runtime.getRuntime().exec("/sdcard/gscript/xrecovery.sh");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
{
os.writeBytes("mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system\n" +
"exit \n");
os.flush();
process.waitFor();
}
Runtime.getRuntime().exec("/sdcard/gscript/xrecovery.sh");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected String[] getPackageResourcePath(String string) {
// TODO Auto-generated method stub
return null;
}
private static void setOnClickListener(OnClickListener onClickListener) {
// TODO Auto-generated method stub
}
}
You should be able to execute a .sh file by using:
Code:
sh xrecovery.sh
spolfliet said:
You should be able to execute a .sh file by using:
Code:
sh xrecovery.sh
Click to expand...
Click to collapse
Without sdcard path! ?
And where should i put?
Thks; )
Sent from my AOSP on Xperia (US) using XDA App
Of course you need to specify the path (it cannot guess where your script is, unless you add it to your PATH). So I guess the following should work for you:
Code:
Runtime.getRuntime().exec("sh /sdcard/gscript/xrecovery.sh");
Unfortunely i cant make this work UK sure that im putting the command Sony the wrong place. I've allready try put Sony a different pplaces but never work: (
Thks anyway; )
Sent from my AOSP on Xperia (US) using XDA App
really need help!
here is my complete code for what i want to do
HTML:
package com.rendeiro2005.xRecovery;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class xRecovery extends Activity {
Button INSTALL;
Button REMOVE;
AlertDialog.Builder builder;
AlertDialog Alert;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
Process process = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
DataInputStream inputStream = new DataInputStream(process.getInputStream());
outputStream.writeBytes("\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
process.waitFor();
process.waitFor();
if (process.exitValue() != 255) {
toastMessage("root");
}
else {
toastMessage("not root");
}
}
catch (IOException e)
{
try {
throw new Exception(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
catch (InterruptedException e)
{
try {
throw new Exception(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
INSTALL = (Button)findViewById(R.id.Button01);
REMOVE = (Button)findViewById(R.id.Button02);
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to install xRecovery?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Runtime.getRuntime().exec("sh /sdcard/gscript/xrecovery.sh");
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
Alert = builder.create();
INSTALL.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Alert.show();
}
});
REMOVE.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
}
});
}
private void toastMessage(String string) {
}
}
i haven`t donne the uninstall part.
the problem here is everything work as it should exept the "sh" doesn`t do anything.
can anyone help me with this? i`m just trying to understand how the process works
thks a lot

[APP] Android transation helper script

If your application has different language versions and a lot of changess to strings.xml (strings added, IDs renamed, strings deleted), the translations will soon become a mess and people won't know anymore what is there left to be translated or if particular string needs translation at all. To fix that I've created a simple java proggy, that
1) loads English strings as a golden source for all other strings
2) compares each values-xx/strings.xml to the above
3) adds a XML comment <!-- PLEASE TRANSLATE --> to each missing value
4) outputs modified to values-xx/strings.xml_obr, sorted by ID
Fast and easy. Here's the code (note: requires jdom-2.x.x.jar)
Code:
package pl.qus.utility.ash;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class AndroidStringsHelper {
private class KeyVal {
String key;
String value;
public KeyVal(String k, String v)
{
key=k;
value=v;
}
}
String resDir = "";
ArrayList<File> listaJęzyków = new ArrayList<File>();
HashMap<String, String> wzorcowaMapa = new HashMap<String, String>();
HashMap<String, String> obrabianaMapa = new HashMap<String, String>();
private static String trKey="!#---TRANSLATE---#!";
public AndroidStringsHelper(String resourceDir) {
String[] listaPlików;
resDir = resourceDir;
File katalog = new File(resDir);
listaPlików = katalog.list();
for (int i = 0; i < listaPlików.length; i++) {
File obr = new File(resourceDir,listaPlików[i]);
if (obr.getName().startsWith("values")) {
File plik=new File(obr, "strings.xml");
if (plik.exists()) {
System.out.println("Dodaję:" + obr.getName());
if (obr.getName().equals("values"))
{
}
else
listaJęzyków.add(plik);
}
}
}
obróbJęzyki();
}
private void obróbJęzyki() {
zaczytajPlik(new File(resDir,"values\\strings.xml"),wzorcowaMapa);
List<KeyVal> sortowanaMapa = new ArrayList<KeyVal>();
for(File plik:listaJęzyków) {
sortowanaMapa.clear();
System.out.println("==================================");
System.out.println("Obrabiam:"+plik.getPath());
obrabianaMapa.clear();
zaczytajPlik(plik,obrabianaMapa);
SortedSet<String> sorted=new TreeSet<String>(wzorcowaMapa.keySet());
Iterator<String> it = sorted.iterator();
while(it.hasNext()) {
String klucz=it.next();
if(obrabianaMapa.containsKey(klucz))
{
sortowanaMapa.add(new KeyVal(klucz, obrabianaMapa.get(klucz)));
}
else
{
System.out.println("Brak ["+klucz+"]");
sortowanaMapa.add(new KeyVal(klucz, trKey+wzorcowaMapa.get(klucz)));
}
}
zapiszPlik(new File(plik.getPath()+"_obr"),sortowanaMapa);
}
}
private void zapiszPlik(File plik, List<KeyVal> docel) {
FileOutputStream os;
Document profileDoc = new Document();
Element root=new Element("resources");
Iterator<KeyVal> it = docel.iterator();
while(it.hasNext()) {
KeyVal nast=it.next();
String klucz=(String) nast.key;
String wart=(String) nast.value;
Element nowy=new Element("string");
if(wart.startsWith(trKey))
{
wart=wart.substring(trKey.length());
root.addContent(new Comment("PLEASE TRANSLATE!"));
}
nowy.addContent(wart);
nowy.setAttribute("name", klucz);
root.addContent(nowy);
}
profileDoc.addContent(root);
try {
os = new FileOutputStream(plik);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(profileDoc, os);
os.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void zaczytajPlik(File plik, HashMap<String, String> docel) {
SAXBuilder builder = new SAXBuilder();
try {
Document strings = builder.build(plik);
Element spis = strings.getRootElement();
List<Element> wszystkie = spis.getChildren();
for (Element e : wszystkie) {
docel.put(e.getAttributeValue("name"), e.getText());
}
} catch (JDOMException | IOException e) {
e.printStackTrace();
}
System.out.println("Zaczytane:"+docel.size());
}
}
To run it just pass a path to your resource directory:
Code:
public class Main {
public static void main(String arg[]) {
new AndroidStringsHelper("/path/to/your/workspace/project/res");
}
}

[Q] rmtp / mms player

hi friends
i can't play rtmp or mss protocol in android project (just audio live stream )
my code :
Code:
package sample.media.player;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
public class SampleMediaPlayerActivity extends Activity implements OnErrorListener, OnPreparedListener {
private MediaPlayer player;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("rtmp://199.103.63.202/live&file=irib3"); // rtmp link
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
[user=439709]@override[/user]
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
[user=439709]@override[/user]
public void onPrepared(MediaPlayer play) {
play.start();
}
[user=439709]@override[/user]
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
}
please help me / thanks:good:
Is it crashing or does it do nothing? Logcat?
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
help me plzzzzzzzzzzzz
nobodyyyyyy ????
takname said:
LogCat:
Level : E
PID : 222
Application : Simple.Media.Player
Tag : MediaPlayer
Text : Error(1,-1)
Click to expand...
Click to collapse
There should be more log code which is important. In every case there should be an Exception which is thrown.
I just found this library: http://www.aftek.com/afteklab/aftek-RTMP-library.shtml
Might be helpful.
(Both formats are not natively supported by the Android platform: http://developer.android.com/guide/appendix/media-formats.html)

One button 4 songs

Hey Guys...
Im working on an app used for handball matches.
I have a problem with a button where i cant get it to set a random source
mpbtn1click = mediaplayer
if(mpbtn1click.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@override
public void onCompletion(MediaPlayer mpbtn1click) {
// TODO Auto-generated method stub
try {
mpbtn1click.setDataSource(R.raw.call);
//I would have a guess that the random has to be here, but how?
mpbtn1click.prepare();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mpbtn1click.seekTo(0);
mpbtn1click.start();;
}
}));
zimzux said:
Hey Guys...
Im working on an app used for handball matches.
I have a problem with a button where i cant get it to set a random source
mpbtn1click = mediaplayer
if(mpbtn1click.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@override
public void onCompletion(MediaPlayer mpbtn1click) {
// TODO Auto-generated method stub
try {
mpbtn1click.setDataSource(R.raw.call);
//I would have a guess that the random has to be here, but how?
mpbtn1click.prepare();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mpbtn1click.seekTo(0);
mpbtn1click.start();;
}
}));
Click to expand...
Click to collapse
Code:
mpbtn1click = mediaplayer
if(mpbtn1click.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
[user=439709]@override[/user]
public void onCompletion(MediaPlayer mpbtn1click) {
// TODO Auto-generated method stub
try {
//I would have a guess that the random has to be here, but how?
double rand = Math.random();
if (rand <= 0.25) {
mpbtn1click.setDataSource(R.raw.callA);
} else if (rand <= 0.5) {
mpbtn1click.setDataSource(R.raw.callB);
} else if (rand <= 0.75) {
mpbtn1click.setDataSource(R.raw.callC);
} else {
mpbtn1click.setDataSource(R.raw.callD);
}
mpbtn1click.prepare();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mpbtn1click.seekTo(0);
mpbtn1click.start();;
}
}));
(Please put your code into code tags. )
This should work.

[Q] Copy Image from Gallery Share (Send To) menu

Moderators... It says I am breaking the rules by asking a question and to ask in the Q&A... But the title of this is "Coding Discussion, Q&A, and Educational Resources" I am not breaking the rules intentionally, I just don't know where else to put this. This is a Coding Question, not a General Question that I would think would get buried and or lost in the General Q&A forum. Please move if you feel I am incorrect.
Hello All, I was hoping someone could help me.
I am trying to create an app that will hide pictures. I want to be able to Pick my App from the Share (Send To) menu from the Users Gallery and have it copy the file to a Directory I have created on my SDCard and then ultimately delete the file from the current location.
Here is what I have so far, but when I pick my app from the Share menu, it crashes the Gallery app. So... I can't even see any errors in my LogCat to even try and troubleshoot my issue.
Can someone point me to a working example of how to do this (I have searched the internet until I am blue in the face) or... I hate to say it... Fix my Code?
Any Help would be appreciated... Thanks!!
Code:
package com.company.privitegallery;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class SendToDo extends Activity {
File sdCardLoc = Environment.getExternalStorageDirectory();
File intImagesDir = new File(sdCardLoc,"/DCIM/privgal/.nomedia");
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
try {
GetPhotoPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
//...
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
public void GetPhotoPath() throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
copy(fileName, intImagesDir);
}
[user=439709]@override[/user]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
try {
copy(selectedImagePath, intImagesDir);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copy(String scr, File dst) throws IOException {
InputStream in = new FileInputStream(scr);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void deleteLatest() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
//Log.i("Log", "file name in delete folder : "+f.toString());
File [] files = f.listFiles();
//Log.i("Log", "List of files is: " +files.toString());
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
// Log.i("Log", "Going -1");
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
// Log.i("Log", "Going +1");
return 1;
} else {
// Log.i("Log", "Going 0");
return 0;
}
}
});
//Log.i("Log", "Count of the FILES AFTER DELETING ::"+files[0].length());
files[0].delete();
}
}
What's the gallery log output?
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
nikwen said:
What's the gallery log output?
Click to expand...
Click to collapse
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
nikwen said:
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
Click to expand...
Click to collapse
Great, Thanks!!
StEVO_M said:
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
Great, Thanks!!
Click to expand...
Click to collapse
Do you view the logs on your computer?
There should be an error message in the logs.
nikwen said:
Do you view the logs on your computer?
There should be an error message in the logs.
Click to expand...
Click to collapse
Which Logs?? As I said before. LogCat does not give any errors.

Categories

Resources