I am developing a player that plays a url of the form
shoucast http://292.3.23.23:8000 is, as I can restore the
metadata? artist name mediaplayer use the title etc.
play no problem, but I can not retrieve metadata
anyone know how I can do it and display it in a text
titulo.settext (title);
check this out http://developer.android.com/reference/android/media/MediaMetadataRetriever.html but it is on API LEVEL 10
Thank you.
I have done using the thread,not the great solution but it works
public class IcyStreamMeta {
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* #return String
* #throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* #return String
* #throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put((String)m.group(1), (String)m.group(2));
}
}
return metadata;
}
}
make thread call each 10 sec
public void startThread(){
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
URL url;
Message msg = handler.obtainMessage();
try {
url = new URL(URL);
IcyStreamMeta icy = new IcyStreamMeta(url);
Log.d("SONG",icy.getTitle());
msg.obj = icy.getTitle();
Log.d("ARTITSi",icy.getArtist());
handler.sendMessage(msg);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 10000);
}
Related
I have a problem while parsing from JSON to Listview in Android. This is an example of data from JSON:
{
"status": {
"statusCode": 200,
"success": true,
"message": "Success"
},
"demandes": [{
"id": "1",
"dateCreation": "21/01/2014",
"tagDemand": "xxxxxxxxxxxx",
"descDemande": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"imageUrl": "https://picsum.photos/3800/50/?image=1"
},
{
"id": "2",
"dateCreation": "15/01/2017",
"tagDemand": "yyyyyyyyyyyyyyyyyyyy",
"descDemande": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"imageUrl": "https://picsum.photos/3500/5200/?image=221"
}
]
}
This is the main activity:
public class MyRequests extends AppCompatActivity {
private String jsonURL = "https://26ae7d0d-62b2-4cc4-8ff7-009bee255089.mock.pstmn.io/demands";
private final int jsoncode = 1;
private ListView listView;
ArrayList<DemandeModel> demandeModelArrayList;
private DemandeAdapter demandeAdapter;
String response = "";
private static ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_requests);
listView = findViewById(R.id.lv);
fetchJSON();
}
#SuppressLint("StaticFieldLeak")
private void fetchJSON() {
showSimpleProgressDialog(this, "Chargement...", "Récupération des données", false);
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void[] params) {
// String response="";
HashMap<String, String> map = new HashMap<>();
try {
HttpRequest req = new HttpRequest(jsonURL);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response = e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss", result);
onTaskCompleted(result, jsoncode);
}
}.execute();
}
public void onTaskCompleted(String response, int serviceCode) {
Log.d("responsejson", response.toString());
switch (serviceCode) {
case jsoncode:
if (isSuccess(response)) {
removeSimpleProgressDialog(); //will remove progress dialog
demandeModelArrayList = getInfo(response);
demandeAdapter = new DemandeAdapter(this, demandeModelArrayList);
listView.setAdapter(demandeAdapter);
} else {
Toast.makeText(MyRequests.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
}
}
}
public ArrayList<DemandeModel> getInfo(String response) {
ArrayList<DemandeModel> demandeModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getJSONObject("status").optString("success").equals("true")) {
JSONArray dataArray = jsonObject.getJSONArray("demandes");
for (int i = 0; i < dataArray.length(); i++) {
DemandeModel playersModel = new DemandeModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playersModel.setId(dataobj.getString("id"));
playersModel.setDate(dataobj.getString("dateCreation"));
playersModel.setNom(dataobj.getString("tagDemand"));
playersModel.setDescription(dataobj.getString("descDemande"));
playersModel.setImgURL(dataobj.getString("imageUrl"));
demandeModelArrayList.add(playersModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return demandeModelArrayList;
}
public boolean isSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getJSONObject("status").optString("success").equals("true")) {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
public String getErrorCode(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getJSONObject("status").optString("message");
} catch (JSONException e) {
e.printStackTrace();
}
return "No data";
}
public static void removeSimpleProgressDialog() {
try {
if (mProgressDialog != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
} catch (IllegalArgumentException ie) {
ie.printStackTrace();
} catch (RuntimeException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showSimpleProgressDialog(Context context, String title,
String msg, boolean isCancelable) {
try {
if (mProgressDialog == null) {
mProgressDialog = ProgressDialog.show(context, title, msg);
mProgressDialog.setCancelable(isCancelable);
}
if (!mProgressDialog.isShowing()) {
mProgressDialog.show();
}
} catch (IllegalArgumentException ie) {
ie.printStackTrace();
} catch (RuntimeException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
so, I had like a response "no data" so I think that there is a problem here " if (isSuccess(response)) "
This is my Adapter:
public class DemandeAdapter extends BaseAdapter {
private Context context;
private ArrayList<DemandeModel> demandeModelArrayList;
public DemandeAdapter(Context context, ArrayList<DemandeModel> demandeModelArrayList) {
this.context = context;
this.demandeModelArrayList = demandeModelArrayList;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return demandeModelArrayList.size();
}
#Override
public Object getItem(int position) {
return demandeModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.demande, null, true);
holder.iv = (ImageView) convertView.findViewById(R.id.iv);
holder.id = (TextView) convertView.findViewById(R.id.id);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.desc = (TextView) convertView.findViewById(R.id.desc);
holder.date = (TextView) convertView.findViewById(R.id.date);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
Picasso.get().load(demandeModelArrayList.get(position).getImgURL()).into(holder.iv);
holder.id.setText("ID : "+demandeModelArrayList.get(position).getId());
holder.date.setText("Date : "+demandeModelArrayList.get(position).getDate());
holder.name.setText("Name : "+demandeModelArrayList.get(position).getNom());
holder.desc.setText("Description : "+demandeModelArrayList.get(position).getDescription());
return convertView;
}
private class ViewHolder {
protected TextView id,name,desc,date;
protected ImageView iv;
}
}
and this is my Model:
public class DemandeModel {
private String id;
private String nom;
private String description;
private String date;
private String imgURL;
public DemandeModel() {
}
public DemandeModel(String id, String nom, String description, String date, String imgURL) {
this.id = id;
this.nom = nom;
this.description = description;
this.date = date;
this.imgURL = imgURL;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getImgURL() {
return imgURL;
}
public void setImgURL(String imgURL) {
this.imgURL = imgURL;
}
}
And this is the HttpRequest :
public class HttpRequest {
public static enum Method {
POST, PUT, DELETE, GET;
}
private URL url;
private HttpURLConnection con;
private OutputStream os;
//After instantiation, when opening connection - IOException can occur
public HttpRequest(URL url) throws IOException {
this.url = url;
con = (HttpURLConnection) this.url.openConnection();
}
//Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
public HttpRequest(String url) throws IOException {
this(new URL(url));
Log.d("parameters", url);
}
/**
* Sending connection and opening an output stream to server by pre-defined instance variable url
*
* #param //isPost boolean - indicates whether this request should be sent in POST method
* #throws IOException - should be checked by caller
*/
private void prepareAll(Method method) throws IOException {
con.setDoInput(true);
con.setRequestMethod(method.name());
if (method == Method.POST || method == Method.PUT) {
con.setDoOutput(true);
os = con.getOutputStream();
}
}
//prepare request in GET method
//#return HttpRequest this instance -> for chaining method #see line 22
public HttpRequest prepare() throws IOException {
prepareAll(Method.GET);
return this;
}
/**
* Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
* HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
*
* #param method HttpRequest.Method - nested enum HttpRequest.Method constant
* #return HttpRequest this instance -> for chaining method #see line 22
* #throws IOException - should be checked by caller
*/
public HttpRequest prepare(Method method) throws IOException {
prepareAll(method);
return this;
}
/**
* Adding request headers (standard format "Key":"Value")
*
* #param headers String variadic params in standard format "Key":"Value"
* #return HttpRequest this instance -> for chaining method #see line 22
*/
public HttpRequest withHeaders(String... headers) {
for (int i = 0, last = headers.length; i < last; i++) {
String[] h = headers[i].split("[:]");
con.setRequestProperty(h[0], h[1]);
}
return this;
}
/**
* Writes query to open stream to server
*
* #param query String params in format of key1=v1&key2=v2 to open stream to server
* #return HttpRequest this instance -> for chaining method #see line 22
* #throws IOException - should be checked by caller
*/
public HttpRequest withData(String query) throws IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.close();
return this;
}
/**
* Builds query on format of key1=v1&key2=v2 from given hashMap structure
* for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
* for map: {Iam=Groot} -> builds "Iam=Groot"
*
* #param params HashMap consists of key-> value pairs to build query from
* #return HttpRequest this instance -> for chaining method #see line 22
* #throws IOException - should be checked by caller
*/
public HttpRequest withData(HashMap<String, String> params) throws IOException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append((result.length() > 0 ? "&" : "") + entry.getKey() + "=" + entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
Log.d("parameters", entry.getKey() + " ===> " + entry.getValue());
}
withData(result.toString());
return this;
}
//When caller only need to send, and don't need String response from server
public int send() throws IOException {
return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
}
/**
* Sending request to the server and pass to caller String as it received in response from server
*
* #return String printed from server's response
* #throws IOException - should be checked by caller
*/
public String sendAndReadString() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
for (String line; (line = br.readLine()) != null; ) response.append(line + "\n");
Log.d("ressss", response.toString());
return response.toString();
}
/**
* Sending request to the server and pass to caller its raw contents in bytes as it received from server.
*
* #return byte[] from server's response
* #throws IOException - should be checked by caller
*/
public byte[] sendAndReadBytes() throws IOException {
byte[] buffer = new byte[8192];
InputStream is = con.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
for (int bytesRead; (bytesRead = is.read(buffer)) >= 0; ) output.write(buffer, 0, bytesRead);
return output.toByteArray();
}
//JSONObject representation of String response from server
public JSONObject sendAndReadJSON() throws JSONException, IOException {
return new JSONObject(sendAndReadString());
}
}
if someone could hepl to solve this problem it will be with a pleasure
I have updated the parsing method. Check below
public ArrayList<DemandeModel> getInfo(String response) {
ArrayList<DemandeModel> demandeModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getJSONObject("status").optString("success").equals("true")) {
JSONArray dataArray = jsonObject.getJSONArray("demandes");
for (int i = 0; i < dataArray.length(); i++) {
DemandeModel playersModel = new DemandeModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playersModel.setId(dataobj.getString("id"));
playersModel.setDate(dataobj.getString("dateCreation"));
playersModel.setNom(dataobj.getString("tagDemand"));
playersModel.setDescription(dataobj.getString("descDemande"));
playersModel.setImgURL(dataobj.getString("imageUrl"));
demandeModelArrayList.add(playersModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return demandeModelArrayList;
}
EDIT below method is updated a bit
public boolean isSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getJSONObject("status").optString("success").equals("true")) {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
EDIT 2
change below line
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
to
response = req.prepare().sendAndReadString();
It looks like you are reading wrong data:
jsonObject.getString("status").equals("true")
There is no "status" in your json respose example. There is "success".
hello i want to get string from activity and set it to the another non activity class please help me i am adding my code.and i need to set the edittext value in non activity class url. help me
my activity.
public class AlertForIp extends AppCompatActivity {
String value;
private Button mButton;
final Context c = this;
static String urlString;
private static AlertForIp instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
instance = this;
final EditText input = new EditText(AlertForIp.this);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertForIp.this);
//AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
/* SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(AlertForIp.this);
final SharedPreferences.Editor editor = prefss.edit();*/
value = input.getText().toString();
// Setting Dialog Title
String urlsss="http://";
String urls=":1219/Json/Handler.ashx";
// This above url string i need to set in that class
urlString = urlsss+value+urls;
/* editor.putString("stringid", urlString); //InputString: from the EditText
editor.commit();
*/
alertDialog.setTitle("WELCOME TO RESTROSOFT");
// Setting Dialog Message
alertDialog.setMessage("ENTER YOUR IP");
//final EditText input = new EditText(this);
//alertDialog.setView(input);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
//input.setText("http://");
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
android.text.Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart)
+ source.subSequence(start, end)
+ destTxt.substring(dend);
if (!resultingTxt
.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i = 0; i < splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
Toast.makeText(AlertForIp.this, "Please enter valid ip", Toast.LENGTH_SHORT).show();
return "";
}
}
}
}
return null;
}
};
input.setFilters(filters);
//input.setText(ip);
alertDialog.setView(input); //
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.waiting);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/*if(input.getText().length()==0)
{
input.setError("Field cannot be left blank.");
dialog.dismiss();
}*/
String validation="^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?";
if (value.matches(validation))
{
Toast.makeText(getApplicationContext(),"enter valid IP address",Toast.LENGTH_SHORT).show();
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
// or
}
else if(!input.getText().toString().equals(""))
{
Intent intent = new Intent(AlertForIp.this, Sample.class);
startActivity(intent);
//Toast.makeText(AlertDialogForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else
{
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
Toast.makeText(AlertForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
//dialog.cancel();
finish();
}
});
// closed
// Showing Alert Message
alertDialog.show();
}
public static Context getContext() {
RestAPI rss=new RestAPI();
rss.persistItems(urlString);
return instance.getApplicationContext();
}
}
And here is my no activity class
public class RestAPI {
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
This is my another Activity i have created the instance of restApi
public class UserDetailsActivity extends Activity {
TextView tvFisrtName, tvLastName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
// Show the Up button in the action bar.
//setupActionBar();
tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
tvLastName=(TextView)findViewById(R.id.tv_lastname);
Intent i=getIntent();
String username=i.getStringExtra("User_Name");
new AsyncUserDetails().execute(username);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
protected class AsyncUserDetails extends AsyncTask<String,Void,JSONObject>
{
String str1;
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonObj = null;
//here i have error
RestAPI api = new RestAPI();
try {
jsonObj = api.GetUserDetails(params[0]);
//JSONParser parser = new JSONParser();
//userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
try {
JSONObject jsonObj=result.getJSONArray("Value").getJSONObject(0);
str1=jsonObj.getString("user_id").toString();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(UserDetailsActivity.this, str1, Toast.LENGTH_SHORT).show();
tvFisrtName.setText(str1);
}
}
public class RestAPI {
String url;
// create constructor here
public RestAPI(String url){
this.url=url;
}
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
now you can use here url directly
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
use here
RestAPI rss=new RestAPI(urlString );
I want to get an Number from a String.
My Code for this Class is:
The XML is download correct, it founds my Value String but i get not the number from the String.
public class XMLProcessor extends AsyncTask<String, Void, String> {
private String rssURL;
private PostParserDelegate delegate;
private ArrayList<Post> posts;
String euro;
private StringBuilder buffer;
TextView mxntoeur;
TextView eurtomxn;
public XMLProcessor(String rssURL, PostParserDelegate delegate) {
this.rssURL = rssURL;
this.delegate = delegate;
posts = new ArrayList<Post>();
}
#Override
protected String doInBackground(String... strings) {
buffer = new StringBuilder();
try {
URL url = new URL(rssURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// HTTP Status "OK" -> HTTPCODE 200
int httpResponse = httpURLConnection.getResponseCode();
if ( httpResponse != 200) {
throw new Exception("Fehlercode: " + httpResponse);
}
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int charactersRead;
char[] tmpChars = new char[400];
while (true) {
charactersRead = reader.read(tmpChars);
if (charactersRead <= 0) {
break;
}
buffer.append(String.copyValueOf(tmpChars, 0, charactersRead));
}
return buffer.toString();
} catch (Exception e) {
Log.e("XMLProcessor", e.getMessage());
Log.e("XMLProcessor", e.getStackTrace().toString());
}
return String.valueOf(0);
}
#Override
protected void onPostExecute(String aDouble) {
super.onPostExecute(aDouble);
parse();
}
protected void parse()
{
String rawXML = buffer.toString();
Post aPost = null;
boolean isProcessingItem = false;
String innerValue ="";
try {
XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
parser.setInput(new StringReader(rawXML));
int event = parser.getEventType();
while (event !=XmlPullParser.END_DOCUMENT)
{
String tag = parser.getName();
switch ( event) {
case XmlPullParser.START_TAG:
if (tag == "item" ) {
Log.d("XMLProcessor", "Neuer Post!");
isProcessingItem = true;
aPost = new Post();
}
break;
case XmlPullParser.TEXT:
innerValue = parser.getText();
break;
case XmlPullParser.END_TAG:
if (isProcessingItem){
if (tag == "item") {
posts.add(aPost);
isProcessingItem = false;
}
} else if ( tag == "description") {
aPost.setPesoInEuro(innerValue);
euro = new String(innerValue.substring(13,21));
//euro = innerValue.substring(13,21);
eurtomxn.setText(euro);
}
break;
}
event = parser.next();
}
delegate.xmlFeedParsed(posts);
} catch (Exception e) {
Log.e("XMLProcess", e.getStackTrace().toString());
}
}
}
In innerValue i get the Correct Sting what i need
/n 1.00 EUR = 21.90612 MXN<br/>\n 1.00 MXN = 0.04565 EUR<br/>\n
Converter--\n
<a href="http://eur.de.fxexchangerate.com/mxn-exchange-rates-history.html">Historische
</a>
\n.
But my problem is, that i need this Number 21.90612. I have try it with substring(13,21), but it was no working.
Have you a idea, how i can fix my problem?
Thank you
It's not very clear what exactly is the Problem, it would be useful if you show the Exception!
Have you checked if the String innerValue has a valid lenght?
if(innerValue.lenght() >= 21){euro = innerValue.substring(13,21);} else {/* Do something here!*/}
}
How to send an audio file from android phone to servlet. i have surfed so many sites but not getting the proper solution. Can anyone please help me.How many ways are there for sending an audio file from android to server.
HttpRequestWithEntity.java
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
public class HttpRequestWithEntity extends HttpEntityEnclosingRequestBase {
private String method;
public HttpRequestWithEntity(String url, String method) {
if (method == null || (method != null && method.isEmpty())) {
this.method = HttpMethod.GET;
} else {
this.method = method;
}
try {
setURI(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
public String getMethod() {
return this.method;
}
}
And here if you want to upload photo or video and you can show progressbar if you want.
public static class UploadPhoto extends AsyncTask<String, Void, InputStream> {
private static final String TAG = "UploadImage";
byte[] buffer;
byte[] data;
//private long dataLength = 0;
private INotifyProgressBar iNotifyProgressBar;
private int user_id;
private IAddNewItemOnGridView mAddNewItemOnGridView;
public UploadPhoto(INotifyProgressBar iNotifyProgressBar,
IAddNewItemOnGridView mAddNewItemOnGridView, int user_id) {
this.iNotifyProgressBar = iNotifyProgressBar;
this.user_id = user_id;
this.mAddNewItemOnGridView = mAddNewItemOnGridView;
}
#Override
protected InputStream doInBackground(String... names) {
File mFile = null;
FileBody mBody = null;
File dcimDir = null;
try {
String fileName = names[0];
dcimDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
mFile = new File(dcimDir, Def.PHOTO_TEMP_DIR + fileName);
if (!mFile.isFile()) {
iNotifyProgressBar.notify(0, UploadStatus.FAILED);
return null;
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(Def.BASE_URL
+ String.format("/%d/list", this.user_id));
final int maxBufferSize = 10 * 1024;
mBody = new FileBody(mFile, fileName, "image/jpeg", "UTF-8"){
int bytesRead, bytesAvailable, bufferSize;
InputStream mInputStream = super.getInputStream();
int dataLength = mInputStream.available();
#Override
public void writeTo(OutputStream out) throws IOException {
bytesAvailable = mInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = mInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
out.write(buffer, 0, bufferSize);
bytesAvailable = mInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = mInputStream.read(buffer, 0, bufferSize);
int progress = (int) (100 - ((bytesAvailable * 1.0) / dataLength) * 100);
Log.d(TAG, "Result: " + progress + "%");
if (progress == 100) {
iNotifyProgressBar.notify(progress, UploadStatus.SUCCESS);
} else {
iNotifyProgressBar.notify(progress, UploadStatus.UPLOADING);
}
}
}
#Override
protected void finalize() throws Throwable {
super.finalize();
if (mInputStream != null) {
mInputStream.close();
}
}
};
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("photo", mBody);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
InputStream mInputStream = response.getEntity().getContent();
return mInputStream == null ? null : mInputStream;
} catch (IOException e) {
Log.e(TAG, "Error causes during upload image: " + e.getMessage());
e.printStackTrace();
iNotifyProgressBar.notify(0, UploadStatus.FAILED);
} finally {
Log.v(TAG, "Close file");
if (mFile != null) {
mFile = null;
}
if (mBody != null) {
mBody = null;
}
if (dcimDir != null) {
dcimDir = null;
}
}
return null;
}
#Override
protected void onPostExecute(InputStream result) {
if (result == null) {
iNotifyProgressBar.notify(0, UploadStatus.FAILED);
} else {
PhotoInfo mPhotoInfo = ApiUtils.convertStreamToPhotoInfo(result);
if (mAddNewItemOnGridView != null && mPhotoInfo != null) {
mAddNewItemOnGridView.notifyAdded(mPhotoInfo);
Log.d(TAG, "Upload completed!!");
} else {
Log.d(TAG, "Upload is failed!!");
iNotifyProgressBar.notify(0, UploadStatus.FAILED);
}
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Servlet
package jp.co.bits.cpa.controller;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
#ParentPackage(value="json-default")
#Namespace("/api/users/{user_id}")
#Result(
name=MyAction.GETDATA, type="json",
params={
"excludeNullProperties", "true",
"excludeProperties", "list.*\\.owner_id"
})
public class ListController implements Status, MyAction { //ModelDriven<Object>,
private static int STATUS = REQUEST_INVALID;
private File file;
private String contentType;
private String filename;
private String contentDisposition = "inline";
private String user_id;
private String sort; // asc || desc
private String type; // thumbnail || full
private String photo_id;
private PhotoHandler photoHandler = new PhotoHandler();
private HttpServletRequest request = ServletActionContext.getRequest();
private InputStream fileInputStream;
private String photoUrl;
private List<Photo> list = new ArrayList<Photo>();
private Photo photo;
#Actions(
value={
#Action(results={
#Result(name=SUCCESS, type="stream",
params={
"contentType", "image/jpeg",
"inputName", "fileInputStream",
"contentDisposition", "filename=\"photo.jpg\"",
"bufferSize", "1024",
"allowCaching", "false"
}),
#Result(name=UPLOAD, type="json", params={
"excludeNullProperties", "true",
"allowCaching", "false",
"excludeProperties", "contentType,photoFilename"
})
})
}
)
public HttpHeaders execute() throws FileNotFoundException {
HttpMethod method = HttpMethod.valueOf(request.getMethod());
String action = GETDATA;
switch (method) {
case GET: {
System.out.println("GET...");
if (this.sort != null && this.type == null) {
System.out.println(this.user_id);
STATUS = photoList();
} else if (this.type != null){
STATUS = download();
if (STATUS == CREATED) {
fileInputStream = new FileInputStream(new File(photoUrl));
if (fileInputStream != null) {
System.out.println("FileInputStream: " + fileInputStream.toString());
}
}
return new DefaultHttpHeaders(STATUS == CREATED ? SUCCESS : GETDATA).withStatus(STATUS);
} else {
STATUS = REQUEST_INVALID;
}
break;
}
case POST: {
System.out.println("Upload file...");
STATUS = saveFile();
System.out.println("Status: " + STATUS);
action = UPLOAD;
break;
}
default:
break;
}
System.out.println("Status: " + STATUS);
return new DefaultHttpHeaders(action).withStatus(STATUS);
}
public InputStream getFileInputStream() {
if (this.fileInputStream != null) {
return this.fileInputStream;
} else {
return null;
}
}
/**
*
* Get list photo by user_id and sort type (asc || desc)
* #return status code
*/
public int photoList() {
System.out.println("Get list...");
list.clear();
if (user_id == null || this.sort == null) {
return REQUEST_INVALID;
} else {
if (sort.equalsIgnoreCase(Def.SORT_ASC) ||
sort.equalsIgnoreCase(Def.SORT_DESC)) {
List<Photo> mPhotos = photoHandler.getList(user_id, this.sort);
if (mPhotos.size() == 0) {
return NO_PHOTO;
} else {
list.addAll(mPhotos);
return OK;
}
} else {
return REQUEST_INVALID;
}
}
}
/**
* using download image by using photo_id and type of photo (thumbnail || full)
* #return status code
*/
public int download() {
list.clear();
System.out.println("Download...");
if (type == null) {
type = Def.PHOTO_THUMBNAIL;
} else {
if (photo_id == null) {
return REQUEST_INVALID;
}
}
if (type.equalsIgnoreCase(Def.PHOTO_THUMBNAIL) ||
type.equalsIgnoreCase(Def.PHOTO_FULL)) {
String url = photoHandler.getUrl(this.photo_id, this.type);
if (url == null) {
return NO_PHOTO;
} else {
request = ServletActionContext.getRequest();
#SuppressWarnings("deprecation")
String path = request.getRealPath("/images/files/");
photoUrl = path + "/" + url;
return CREATED;
}
} else {
return REQUEST_INVALID;
}
}
/**
*
* #param pathImage
* #return true or false
*/
private boolean cropImage(String pathImage) {
Image originalImage;
BufferedImage thumbImage;
try {
originalImage = ImageIO.read(this.file);
thumbImage = Utils.makeThumbnail(originalImage, 100, 100, true);
File thumbFile = new File(pathImage);
System.out.println("Crop... " + pathImage);
return ImageIO.write(thumbImage, Def.DEFAULT_PHOTO_TYPE,
thumbFile);
} catch (Exception e) {
System.out.println("Error at CropIMAGE: " + e.getMessage());
return false;
}
}
private int saveFile() {
try {
int userId = Integer.parseInt(this.user_id); // Parse user_id can be failed
if (file != null && new UserHandler().isExisted(userId)) { // user_id always != null, please change to check user_id existed
System.out.println("Save File...");
request = ServletActionContext.getRequest();
#SuppressWarnings("deprecation")
String path = request.getRealPath("/images/files/");
System.out.println("Path-->: " + path);
System.out.println(this.filename); // Save file name to database
File fileToCreate = new File(path, this.filename);
String thumb_url = Def.THUMBNAIL_PREFIX + this.filename;
try {
FileUtils.copyFile(this.file, fileToCreate);
if (fileToCreate.isFile()) {
// int photoId = photoHandler.insertGetId(new Photo(
// Integer.parseInt(this.user_id), this.filename,
// this.filename, thumb_url));
if (cropImage(path + "/" + thumb_url)) {
this.photo = photoHandler.insertGetPhoto(new Photo(
Integer.parseInt(this.user_id), this.filename,
this.filename, thumb_url));
if (photo != null) {
return CREATED;
} else {
return REQUEST_INVALID;
}
} else {
System.out.println("Crop failed");
return REQUEST_INVALID;
}
} else {
System.out.println("create failed");
return REQUEST_INVALID;
}
} catch (IOException e) {
System.out.println("Error at Save file: " + e.getMessage());
if (fileToCreate.isFile()) { // Sometime, we upload fail but the filename or file still created.
fileToCreate.delete();
}
return REQUEST_INVALID;
}
} else {
System.out.println("File not found");
return REQUEST_INVALID;
}
} catch (Exception e) {
return REQUEST_INVALID;
}
}
public void setPhoto(File file) {
System.out.println("Set Photo File...");
this.file = file;
}
public void setPhotoContentType(String contentType) {
this.setContentType(contentType);
}
public void setPhotoFileName(String filename) {
this.filename = filename;
}
/**
*
* Get list for parse json
* #return list for parse json
*/
public List<Photo> getList() {
if (list.size() > 0) {
return list;
} else {
return null;
}
}
public String getPhotoFilename() {
if (this.filename == null) {
return null;
}
if (this.filename.isEmpty()) {
return null;
}
return this.filename;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.request = servletRequest;
}
public void setPhotoContentDisposition(String contentDisposition) {
this.setContentDisposition(contentDisposition);
}
public void setContentDisposition(String contentDisposition) {
this.contentDisposition = contentDisposition;
}
public String getContentDisposition() {
if (this.contentDisposition == null) {
return null;
}
if (this.contentDisposition.isEmpty()) {
return null;
}
if (this.contentDisposition.equals("inline")) {
return null;
}
return this.contentDisposition;
}
public String getContentType() {
if (this.contentType == null) {
return null;
}
if (this.contentType.isEmpty()) {
return null;
}
return this.contentType;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public void setSort(String sort) {
this.sort = sort.trim();
}
public void setPhoto_id(String photo_id) {
this.photo_id = photo_id.trim();
}
public void setType(String type) {
this.type = type.trim();
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Photo getPhoto() {
return photo;
}
public void setPhoto(Photo detail) {
this.photo = detail;
}
}
Finally i have succeed in sending audio file from android to servlet. Following is my client side code
public class MainActivity extends Activity {
// static final String UPLOAD_URL = "http://192.168.223.1:8080/ReceiveFileServlet/RecFileServlet";
static final int BUFFER_SIZE = 4096;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new sendFile().execute(new String[] { "http://10.0.2.2:8080/ReceiveFileServlet/RecFileServlet" });
}
private class sendFile extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
HttpURLConnection httpConn=null;
try
{
String file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Tdt.aac";
File uploadFile = new File(file);
FileInputStream inputStream = new FileInputStream(uploadFile);
System.out.println("File to upload: " + file);
// creates a HTTP connection
URL url1 = new URL(urls[0]);
httpConn = (HttpURLConnection) url1.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("fileName", uploadFile.getName());
httpConn.connect();
// sets file name as a HTTP header
Log.i("fileName", uploadFile.getName());
// opens output stream of the HTTP connection for writing data
OutputStream outputStream = httpConn.getOutputStream();
// Opens input stream of the file for reading data
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Start writing data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data was written.");
outputStream.close();
inputStream.close();
}
catch(SocketTimeoutException e)
{
Log.e("Debug", "error: " + e.getMessage(), e);
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
try
{
// always check HTTP response code from server
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String response = reader.readLine();
System.out.println("Server's response: " + response);
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
here is my servlet code
public class RecFileServlet extends HttpServlet {
static final String SAVE_DIR = "D:/temp/";
static final int BUFFER_SIZE = 4096;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Gets file name for HTTP header
String fileName = request.getHeader("fileName");
File saveFile = new File(SAVE_DIR + fileName);
// prints out all header values
System.out.println("===== Begin headers =====");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String headerName = names.nextElement();
System.out.println(headerName + " = " + request.getHeader(headerName));
}
System.out.println("===== End headers =====\n");
// opens input stream of the request for reading data
InputStream inputStream = request.getInputStream();
// opens an output stream for writing file
FileOutputStream outputStream = new FileOutputStream(saveFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
System.out.println("File written to: " + saveFile.getAbsolutePath());
// sends response to client
response.getWriter().print("UPLOAD DONE");
}
}
I am making the radio app.I have using the android media for playing radio working fine.
Can possible to know song title?
I have play same url in vlc player on desktop it show me the song title.
If there is anyway then please help me.
I also want to implement in 2.1
Thank you.
You'd use the MetaDataRetriever class for this. If you want the song title you'd use the METADATA_KEY_TITLE key. So for instance, you could write some code like this:
MetadataRetriever myRetriever = new MetadataRetriever();
myRetriever.setDataSource(/*specify you data source here*/);
String songName = myRetriever.extractMetadata(MetadataRetriever.METADATA_KEY_TITLE);
If you're developing for less than API level 10, you're going to have to use something else to get the metadata. The MyID3 library will probably do the trick in this case.
I have the solution for 2.2
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* #return String
* #throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* #return String
* #throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put((String)m.group(1), (String)m.group(2));
}
}
return metadata;
}
Using the thread
public void startThread(){
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
URL url;
Message msg = handler.obtainMessage();
try {
url = new URL(URL);
IcyStreamMeta icy = new IcyStreamMeta(url);
Log.d("SONG",icy.getTitle());
msg.obj = icy.getTitle();
Log.d("ARTITSi",icy.getArtist());
handler.sendMessage(msg);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 10000);
}