Sending audio file from android to servlet - android

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");
}
}

Related

Parse JSON And Show In Listview Retrieve/Fetch URL Server " No Data "

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".

Android Async Task Freezes UI Completely

I have an Async task that loads information from the server and displays data on the UI. Suddenly the async task downloads the data and formats the JSON data fine but it would freeze the UI completely.
Here is the base download class
public class GetRawData {
private static String LOG_TAG = GetRawData.class.getSimpleName();
private String mRawURL;
private List<NameValuePair> mRawParams = null;
private String mRawData;
private DownloadStatus mDownloadStatus;
public GetRawData(String mRawURL) {
this.mRawURL = mRawURL;
this.mRawParams = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public String getRawData() {
return mRawData;
}
public void setRawURL(String mRawURL) {
this.mRawURL = mRawURL;
}
public List<NameValuePair> getRawParams() {
return mRawParams;
}
public void setRawParams(List<NameValuePair> mParams) {
this.mRawParams = mParams;
}
public DownloadStatus getDownloadStatus() {
return mDownloadStatus;
}
public void reset() {
this.mRawURL = null;
this.mRawData = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public void execute() {
this.mDownloadStatus = DownloadStatus.PROCESSING;
DownloadRawData mDownloadRawData = new DownloadRawData();
mDownloadRawData.execute(mRawURL);
}
public class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Create URL and Reader instances.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//If no parameter has been provided, return null.
if (params == null)
return null;
try {
// Get URL entered by the user.
URL mURL = new URL(params[0]);
urlConnection = (HttpURLConnection) mURL.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
//urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.connect();
// validate and add parameters if available.
if (mRawParams != null && mRawParams.size()>0){
JSONObject jsonParam = new JSONObject();
for (NameValuePair pair : mRawParams) {
jsonParam.put(pair.getName().toString(), pair.getValue().toString());
}
String jsonparams = jsonParam.toString();
// Send POST output.
DataOutputStream printout;
printout = new DataOutputStream(urlConnection.getOutputStream());
printout.writeBytes(jsonparams);
printout.flush();
printout.close();
}
int HttpResult =urlConnection.getResponseCode();
StringBuffer buffer = new StringBuffer();
if(HttpResult ==HttpURLConnection.HTTP_OK){
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(""+buffer.toString());
}else{
InputStream errorStream = urlConnection.getErrorStream();
if (errorStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(errorStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(urlConnection.getResponseMessage());
}
return buffer.toString();
} catch (IOException e) {
Log.d("IOException", e.toString());
return null;
} catch (JSONException j) {
Log.d("JSONException", j.toString());
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.d("IOException", "unable to close the reader");
}
}
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mRawData = result;
//Log.d("onPostExecute", result);
if (mRawData == null) {
if (mRawURL == null) {
mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
} else {
mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
}
} else {
mDownloadStatus = DownloadStatus.PROCESSED;
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
}
enum DownloadStatus {
IDLE,
PROCESSING,
NOT_INITIALIZED,
FAILED_OR_EMPTY,
PROCESSED
}
Here is the specific data formatting class the extends above class
public class GetJobCardJsonData extends GetRawData {
private static String LOG_TAG = GetAuthenticationJsonData.class.getSimpleName();
private static String JOBCARD_SERVICE_URL = "http://www.appservice.com/appservice/jobcardinfoservice.asmx/GetJobCardInfo";
private List<JobCard> mJobCardList;
private CarcalDownloadListener mListener;
public GetJobCardJsonData(String CurrentDate, int DealershipID) {
super(null);
List<NameValuePair> mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("JobCardDate", CurrentDate));
mParams.add(new BasicNameValuePair("DealershipID", String.valueOf(DealershipID)));
this.setRawParams(mParams);
}
public List<JobCard> getJobCardList() {
return mJobCardList;
}
public void getjobcards() {
super.setRawURL(JOBCARD_SERVICE_URL);
DownloadJobCardJsonData mDownloadJobCardJsonData = new DownloadJobCardJsonData();
mDownloadJobCardJsonData.execute(JOBCARD_SERVICE_URL);
}
public void setOnCarcalDownloadListener(CarcalDownloadListener onCarcalDownloadListener) {
this.mListener = onCarcalDownloadListener;
}
private void processResult() {
if (getDownloadStatus() != DownloadStatus.PROCESSED) {
Log.e(LOG_TAG, "Error Downloading the raw file.");
return;
}
if (mJobCardList == null){
mJobCardList = new ArrayList<JobCard>();
}
final String JOBCARD_JOBCARDID = "JobCardID";
final String JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME = "StockNumberWithDeliveryTime";
final String JOBCARD_CUSTOMERNAME = "CustomerName";
final String JOBCARD_MODELNUMBER = "ModelNumber";
final String JOBCARD_COLOR = "Color";
final String JOBCARD_SALEEXECUTIVE = "SaleExecutive";
final String JOBCARD_ORDERSTATUS = "OrderStatus";
final String JOBCARD_SHOWROOMSTATUS = "ShowRoomStatus";
try {
JSONArray jsonArray = new JSONArray(getRawData());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobcarditem = jsonArray.optJSONObject(i);
Long JOBCARDID = jobcarditem.getLong(JOBCARD_JOBCARDID);
String STOCKWITHDELIVERY = jobcarditem.getString(JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME);
String CUSTOMERNAME = jobcarditem.getString(JOBCARD_CUSTOMERNAME);
String MODELNUMBER = jobcarditem.getString(JOBCARD_MODELNUMBER);
String COLOR = jobcarditem.getString(JOBCARD_COLOR);
String SALEEXECUTIVE = jobcarditem.getString(JOBCARD_SALEEXECUTIVE);
int ORDERSTATUS = jobcarditem.getInt(JOBCARD_ORDERSTATUS);
int SHOWROOMSTATUS = jobcarditem.getInt(JOBCARD_SHOWROOMSTATUS);
JobCard mJobCard = new JobCard(JOBCARDID, STOCKWITHDELIVERY, CUSTOMERNAME, MODELNUMBER, COLOR, SALEEXECUTIVE, ORDERSTATUS, SHOWROOMSTATUS);
mJobCardList.add(mJobCard);
}
} catch (JSONException jsone) {
jsone.printStackTrace();
Log.e(LOG_TAG, "Error processing json data.");
}
}
public class DownloadJobCardJsonData extends DownloadRawData {
#Override
protected String doInBackground(String... params) {
return super.doInBackground(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
processResult();
mListener.OnDownloadCompleted();
}
}
}
Here is the code that is called on the activity
private JobCardRecyclerViewAdapter mJobCardRecyclerViewAdapter;
private GetJobCardJsonData mGetJobCardJsonData;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_card_calender);
activateToolbarWithHomeEnabled();
String formattedDate="";
if (session.getCurrentDate() == ""){
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = df.format(c.getTime());
currentDateTextView.setText(formattedDate);
}else {
formattedDate = session.getCurrentDate();
currentDateTextView.setText(formattedDate);
}
// Fetch data for current date.
mGetJobCardJsonData = new GetJobCardJsonData(formattedDate, session.getDealershipID());
mGetJobCardJsonData.getjobcards();
mGetJobCardJsonData.setOnCarcalDownloadListener(new CarcalDownloadListener() {
#Override
public void OnDownloadCompleted() {
List<JobCard> mJobCards = mGetJobCardJsonData.getJobCardList();
mJobCardRecyclerViewAdapter = new JobCardRecyclerViewAdapter(mJobCards, JobCardCalenderActivity.this);
mRecyclerView.setAdapter(mJobCardRecyclerViewAdapter);
}
});
}
Can anyone help on what i am doing wrong that is freezing the UI. It was working fine before and has started to freeze the UI suddenly.
I was able to fix the issue, the problem was not with Async task but with the layout. I accidently wrapped the recycler view with scroll view. which was causing the UI to freeze. Looks weird that a scroll view caused the whole UI thread to freeze. but here is my solution
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
</ScrollView>
Changed it to
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
hope it will be helpful for others facing same problem.

How to view the Intents a BroadcastReceiver is receiving?

I have an infinite loop somewhere in my code, indicative of my group messaging BroadcastReceiver continually accepting only the first message in the database, over and over again, until I stop running the application. Note that the repeating of the message only occurs in the client app and not in the server database.
Is there way to trace what intent the BroadcastReceiver is receiving? ie. be able to view the intents the BroadcastReceiver is acting on to locate the source of these actions?
My code for both sending and receiving a group message if it helps: (BroadcastReceiver is near the bottom)
public class GroupMessaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
public String groupname;
private EditText messageText;
private EditText messageHistoryText;
private Button sendMessageButton;
private Manager imService;
private InfoOfGroup group = new InfoOfGroup();
private StorageManipulater localstoragehandler;
private Cursor dbCursor;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message); // messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
group.groupName = extras.getString(InfoOfGroup.GROUPNAME);
group.groupId = extras.getString(InfoOfGroup.GROUPID);
String msg = extras.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
setTitle("Group: " + group.groupName);
// Retrieve the information
localstoragehandler = new StorageManipulater(this);
dbCursor = localstoragehandler.groupGet(group.groupId);
if (dbCursor.getCount() > 0) {
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
// String 2: Username
// String 3: Message
this.appendToMessageHistory(dbCursor.getString(2),
dbCursor.getString(3));
dbCursor.moveToNext();
}
}
localstoragehandler.close();
if (msg != null) {
// Then friends username and message, not equal to null
this.appendToMessageHistory(group.groupId, msg);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel((group.groupId + msg).hashCode());
}
// The send button
sendMessageButton.setOnClickListener(new OnClickListener() {
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = messageText.getText();
if (message.length() > 0) {
appendToMessageHistory(imService.getUsername(),
message.toString());
// *****************PROBLEM MAY BE
// HERE******************************
localstoragehandler.groupInsert(imService.getUsername(),
group.groupId, message.toString());
messageText.setText("");
Thread thread = new Thread() {
public void run() {
try {
if (imService.sendGroupMessage(group.groupId,
group.groupName, message.toString()) == null) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
// showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}
});
messageText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == 66) {
sendMessageButton.performClick();
return true;
}
return false;
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id) {
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1) {
return null;
} else {
return new AlertDialog.Builder(GroupMessaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked OK so do some stuff */
}
}).create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(groupMessageReceiver);
unbindService(mConnection);
ControllerOfGroup.setActiveGroup(null);
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(MessagingService.TAKE_GROUP_MESSAGE);
registerReceiver(groupMessageReceiver, i);
ControllerOfGroup.setActiveGroup(group.groupName);
}
// For receiving messages from other users...
public class GroupMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = intent.getExtras();
String username = extra.getString(InfoOfGroupMessage.FROM_USER);
String groupId = extra.getString(InfoOfGroupMessage.TO_GROUP_ID);
String message = extra
.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
// *************************OR HERE******************************
if (username != null && message != null) {
if (group.groupId.equals(groupId)) {
appendToMessageHistory(username, message);
localstoragehandler.groupInsert(username, groupId, message);
} else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(GroupMessaging.this,
username + " says '" + message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
};
// Build receiver object to accept messages
private GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
// Setting username and message to the message box
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
messageHistoryText.append(username + ":\n");
messageHistoryText.append(message + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
MessagingService Class:
public class MessagingService extends Service implements Manager, Updater {
// private NotificationManager mNM;
public static String USERNAME;
public static final String TAKE_MESSAGE = "Take_Message";
public static final String FRIEND_LIST_UPDATED = "Take Friend List";
public static final String MESSAGE_LIST_UPDATED = "Take Message List";
public static final String TAKE_GROUP_MESSAGE = "Take_Group_Message";
public static final String GROUP_LIST_UPDATED = "Take Group List";
public static final String GROUP_MESSAGE_LIST_UPDATED = "Take Group Message List";
public ConnectivityManager conManager = null;
private final int UPDATE_TIME_PERIOD = 15000;
private String rawFriendList = new String();
private String rawMessageList = new String();
private String rawGroupList = new String();
private String rawGroupMessageList = new String();
SocketerInterface socketOperator = new Socketer(this);
private final IBinder mBinder = new IMBinder();
private String username;
private String password;
private String groupname;
private boolean authenticatedUser = false;
// timer to take the updated data from server
private Timer timer;
private StorageManipulater localstoragehandler;
private NotificationManager mNM;
public class IMBinder extends Binder {
public Manager getService() {
return MessagingService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
localstoragehandler = new StorageManipulater(this);
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
new StorageManipulater(this);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread() {
#Override
public void run() {
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random
.nextInt(20000)) == 0) {
tryCount++;
if (tryCount > 10) {
// if it can't listen a port after trying 10 times, give
// up...
break;
}
}
}
};
thread.start();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private void showNotification(String username, String msg) {
// Set the icon, scrolling text and TIMESTAMP
String title = "AndroidIM: You got a new Message! (" + username + ")";
String text = username + ": "
+ ((msg.length() < 5) ? msg : msg.substring(0, 5) + "...");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.notification)
.setContentTitle(title).setContentText(text);
Intent i = new Intent(this, IndividualMessaging.class);
i.putExtra(InfoOfFriend.USERNAME, username);
i.putExtra(InfoOfMessage.MESSAGETEXT, msg);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0);
mBuilder.setContentIntent(contentIntent);
mBuilder.setContentText("New message from " + username + ": " + msg);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to
// cancel.
mNM.notify((username + msg).hashCode(), mBuilder.build());
}
public String getUsername() {
return this.username;
}
public String sendMessage(String username, String tousername, String message)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8") + "&message="
+ URLEncoder.encode(message, "UTF-8") + "&action="
+ URLEncoder.encode("sendMessage", "UTF-8") + "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
private String getFriendList() throws UnsupportedEncodingException {
// after authentication, server replies with friendList xml
// Has the friend and group and message(s) xml
rawFriendList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawFriendList != null) {
this.parseFriendInfo(rawFriendList);
}
return rawFriendList;
}
private String getMessageList() throws UnsupportedEncodingException {
rawMessageList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawMessageList != null) {
this.parseMessageInfo(rawMessageList);
}
return rawMessageList;
}
private String getGroupList() throws UnsupportedEncodingException {
rawGroupList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawGroupList != null) {
this.parseGroupInfo(rawGroupList);
}
return rawGroupList;
}
private String getGroupMessageList() throws UnsupportedEncodingException {
rawGroupMessageList = socketOperator
.sendHttpRequest(getAuthenticateUserParams(username, password));
if (rawGroupMessageList != null) {
this.parseGroupInfo(rawGroupMessageList);
}
return rawGroupMessageList;
}
public String authenticateUser(String usernameText, String passwordText)
throws UnsupportedEncodingException {
this.username = usernameText;
this.password = passwordText;
this.authenticatedUser = false;
String result = null;
result = this.getFriendList(); // socketOperator.sendHttpRequest(getAuthenticateUserParams(username,
// password));
if (result != null && !result.equals(LoggingIn.AUTHENTICATION_FAILED)) {
// if user is authenticated then return string from server is not
// equal to AUTHENTICATION_FAILED
this.authenticatedUser = true;
rawFriendList = result;
USERNAME = this.username;
// For Friends
Intent i = new Intent(FRIEND_LIST_UPDATED);
i.putExtra(InfoOfFriend.FRIEND_LIST, rawFriendList);
sendBroadcast(i);
// For Groups
Intent iG = new Intent(GROUP_LIST_UPDATED);
i.putExtra(InfoOfGroup.GROUP_LIST, rawGroupList);
sendBroadcast(iG);
timer.schedule(new TimerTask() {
public void run() {
try {
// rawFriendList = IMService.this.getFriendList();
// sending friend list
Intent i = new Intent(FRIEND_LIST_UPDATED);
Intent i2 = new Intent(MESSAGE_LIST_UPDATED);
Intent i3 = new Intent(GROUP_LIST_UPDATED);
Intent i4 = new Intent(GROUP_MESSAGE_LIST_UPDATED);
String tmp = MessagingService.this.getFriendList();
String tmp2 = MessagingService.this.getMessageList();
String tmp3 = MessagingService.this.getGroupList();
String tmp4 = MessagingService.this
.getGroupMessageList();
// For friends
if (tmp != null) {
i.putExtra(InfoOfFriend.FRIEND_LIST, tmp);
sendBroadcast(i);
Log.i("friend list broadcast sent ", "");
if (tmp2 != null) {
i2.putExtra(InfoOfMessage.MESSAGE_LIST, tmp2);
sendBroadcast(i2);
Log.i("friend list broadcast sent ", "");
}
} else {
Log.i("friend list returned null", "");
}
// Changed to i3 and i4 for the intents created...
if (tmp3 != null) {
i3.putExtra(InfoOfGroup.GROUP_LIST, tmp3);
sendBroadcast(i3);
Log.i("group list broadcast sent ", "");
if (tmp4 != null) {
i4.putExtra(
InfoOfGroupMessage.GROUP_MESSAGE_LIST,
tmp4);
sendBroadcast(i4);
Log.i("group list broadcast sent ", "");
}
} else {
Log.i("group list returned null", "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, UPDATE_TIME_PERIOD, UPDATE_TIME_PERIOD);
}
return result;
}
public void messageReceived(String username, String message) {
// FriendInfo friend = FriendController.getFriendInfo(username);
InfoOfMessage msg = IndividualMessageController.checkMessage(username);
if (msg != null) {
Intent i = new Intent(TAKE_MESSAGE);
i.putExtra(InfoOfMessage.USERID, msg.userid);
i.putExtra(InfoOfMessage.MESSAGETEXT, msg.messagetext);
sendBroadcast(i);
String activeFriend = ControllerOfFriend.getActiveFriend();
if (activeFriend == null || activeFriend.equals(username) == false) {
localstoragehandler.insert(username, this.getUsername(),
message.toString());
showNotification(username, message);
}
Log.i("TAKE_MESSAGE broadcast sent by im service", "");
}
}
#Override
public void groupMessageReceived(String username, String groupId,
String message) {
// FriendInfo friend = FriendController.getFriendInfo(username);
InfoOfGroupMessage msg = GroupMessageController.checkMessage(username);
if (msg != null) {
Intent i = new Intent(TAKE_GROUP_MESSAGE);
i.putExtra(InfoOfGroupMessage.FROM_USER, msg.fromUser);
i.putExtra(InfoOfGroupMessage.TO_GROUP_ID, msg.toGroupId);
i.putExtra(InfoOfGroupMessage.GROUP_MESSAGE_TEXT, msg.messageText);
sendBroadcast(i);
}
Log.i("TAKE_GROUP_MESSAGE broadcast sent by im service", "");
}
private String getAuthenticateUserParams(String usernameText,
String passwordText) throws UnsupportedEncodingException {
String params = "username="
+ URLEncoder.encode(usernameText, "UTF-8")
+ "&password="
+ URLEncoder.encode(passwordText, "UTF-8")
+ "&action="
+ URLEncoder.encode("authenticateUser", "UTF-8")
+ "&port="
+ URLEncoder.encode(
Integer.toString(socketOperator.getListeningPort()),
"UTF-8") + "&";
return params;
}
public void setUserKey(String value) {
}
public boolean isNetworkConnected() {
return conManager.getActiveNetworkInfo().isConnected();
}
public boolean isUserAuthenticated() {
return authenticatedUser;
}
public String getLastRawFriendList() {
return this.rawFriendList;
}
#Override
public void onDestroy() {
Log.i("IMService is being destroyed", "...");
super.onDestroy();
}
public void exit() {
timer.cancel();
socketOperator.exit();
socketOperator = null;
this.stopSelf();
}
public String signUpUser(String usernameText, String passwordText,
String emailText) {
String params = "username=" + usernameText + "&password="
+ passwordText + "&action=" + "signUpUser" + "&email="
+ emailText + "&";
String result = socketOperator.sendHttpRequest(params);
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
return result;
}
public String addNewFriendRequest(String friendUsername) {
String params = "username=" + this.username + "&password="
+ this.password + "&action=" + "addNewFriend"
+ "&friendUserName=" + friendUsername + "&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
public String sendFriendsReqsResponse(String approvedFriendNames,
String discardedFriendNames) {
String params = "username=" + this.username + "&password="
+ this.password + "&action=" + "responseOfFriendReqs"
+ "&approvedFriends=" + approvedFriendNames
+ "&discardedFriends=" + discardedFriendNames + "&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
private void parseFriendInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseMessageInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseGroupInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void parseGroupMessageInfo(String xml) {
try {
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
sp.parse(new ByteArrayInputStream(xml.getBytes()), new HandlerXML(
MessagingService.this));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateData(InfoOfMessage[] messages, InfoOfFriend[] friends,
InfoOfGroup[] groups, InfoOfGroupMessage[] groupMessages,
InfoOfFriend[] unApprovedFriends, String userKey) {
this.setUserKey(userKey);
// FriendController.
IndividualMessageController.setMessagesInfo(messages);
// Log.i("MESSAGEIMSERVICE","messages.length="+messages.length);
GroupMessageController.setMessagesInfo(groupMessages);
int i = 0;
while (i < messages.length) {
messageReceived(messages[i].userid, messages[i].messagetext);
i++;
}
int j = 0;
while (j < groupMessages.length) {
groupMessageReceived(groupMessages[i].fromUser,
groupMessages[i].toGroupId, groupMessages[i].messageText);
j++;
}
// For individual chat
ControllerOfFriend.setFriendsInfo(friends);
ControllerOfFriend.setUnapprovedFriendsInfo(unApprovedFriends);
// For group chat
ControllerOfGroup.setGroupsInfo(groups);
// ControllerOfGroup.setUnapprovedGroupsInfo(unapprovedGroups);
}
// ************GENERAL METHODS FOR THE GROUP CHAT************
#Override
public String createNewGroup(String userName, String groupName)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&action=" + "createGroup" + "&groupName=" + groupName + "&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
#Override
public String addGroupMember() {
// TODO Auto-generated method stub
return null;
}
#Override
public String sendGroupMessage(String toGroupId, String toGroupName,
String messageText) throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&toGroupId=" + URLEncoder.encode(toGroupId, "UTF-8")
+ "&messageText=" + URLEncoder.encode(messageText, "UTF-8")
+ "&action=" + URLEncoder.encode("sendGroupMessage", "UTF-8")
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
#Override
public String getGroupName() {
// TODO Auto-generated method stub
return this.groupname;
}
}
Websocket Class
public class Socketer implements SocketerInterface
{
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://" + ipAddress.getIpAddress() + ":PRIVATE"; // change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false) // as long as have noted exited yet, will continuing reading in
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data> (bunch of data...etc) </data>
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}

Exception in AsyncTask downloading image

Refer my question on IllegalStateException in AsyncTask.
I am invoked the following AsyncTask from onPostExecute() of this task(Referred in this link).
public class SaveImageAsync extends AsyncTask<Context, Integer, String> {
private Bitmap bitmap = null;
private ArrayList<String> imageUrls = null;
private ArrayList<ImageView> imageViews = null;
int index = 0;
public SaveImageAsync(ArrayList<ImageView> imageViews,
ArrayList<String> imageUrls) {
this.imageUrls = imageUrls;
this.imageViews = imageViews;
}
#Override
protected String doInBackground(Context... params) {
boolean bRC;
String imageName, imageLocalPath, imageURL;
try {
for (int i = 0; i < imageUrls.size(); i++) {
imageURL = imageUrls.get(i);
String[] strSplittedImagePath = imageURL
.split("/");
if ((strSplittedImagePath != null)
&& (strSplittedImagePath.length >= 1)) {
imageName = strSplittedImagePath[(strSplittedImagePath.length - 1)];
} else {
imageName = imageURL;
}
imageLocalPath = path + imageName;
bRC = doesFileExists(imageLocalPath);
if (bRC == false) {
getImageFromServer(CommonSettings.mSTstrBaseURL
+ imageURL, imageLocalPath);
}
try {
bitmap = BitmapFactory
.decodeFile(imageLocalPath);
} catch (Exception e) {
}
if (bitmap == null) {
try {
new File(imageLocalPath).delete();
} catch (Exception e1) {
}
getImageFromServer(CommonSettings.mSTstrBaseURL
+ imageURL, imageLocalPath);
bitmap = BitmapFactory
.decodeFile(imageLocalPath);
}
Thread.sleep(300);
publishProgress();
}
} catch (InterruptedException e) {
e.printStackTrace();
Log.w(LOG_TAG,
"Got InterruptedException inside AsyncTask SaveImageAsync : "
+ e);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
ImageView imageView = imageViews.get(index);
while (imageView == null) {
index = index + 1;
imageView = imageViews.get(index);
}
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
index = index + 1;
//bitmap.recycle();
}
public boolean getImageFromServer(String url, String localPath) {
boolean bReturn = false;
File objNewFile;
try {
objNewFile = new File(localPath);
if (!objNewFile.exists()) {
objNewFile.createNewFile();
}
BufferedInputStream objBufferedInput = new BufferedInputStream(
new java.net.URL(url).openStream());
FileOutputStream objFileOutput = new FileOutputStream(objNewFile);
BufferedOutputStream objBufferOutput = new BufferedOutputStream(
objFileOutput, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = objBufferedInput.read(data, 0, 1024)) >= 0) {
objBufferOutput.write(data, 0, x);
}
objFileOutput.flush();
objBufferOutput.flush();
objFileOutput.close();
objBufferOutput.close();
objBufferedInput.close();
bReturn = true;
} catch (IOException e) {
} catch (Exception ex) {
}
return bReturn;
}
}
When pressing back button and loading this task it throws OutOfMemoryException at decodeFile(). Why this happen and how to fix this?
Thanks

how retrieve metadata from shoutcast on android?

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);
}

Categories

Resources