My activity changes orientation on screen lock - android

I have set orientation of my activity to landscape and it remains in that state except one case.and the case is screen lock .when my activity is running and i lock my screen it changes orientation from landscape to portrait for little bit of time and causes my app to restart and which I don't want.any solution...?
package com.example.hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity{
VideoView vv;
public ArrayList<String> list = new ArrayList<String>();
int n,positio = 0;
String file = null;
Spinner spin;
MediaPlayer mp;
Intent intent;
File fl;
boolean isPlaying = true;
boolean screenOn = false;
PowerManager pm;
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
Log.d("zaid iqbal", "in onCreate");
requestFullScreen();
setContentView(R.layout.activity_main);
vv = (VideoView)findViewById(R.id.video);
spin = (Spinner)findViewById(R.id.spinner);
MediaController mc = new MediaController(this);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
vv.setMediaController(mc);
setupSpin();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onPause");
isPlaying = vv.isPlaying();
screenOn = pm.isScreenOn();
if (screenOn && isPlaying) {
// Screen is still on, so do your thing here
n++;
positio = vv.getCurrentPosition();
vv.pause();
//Toast.makeText(this, file, Toast.LENGTH_LONG).show();
intent = new Intent(this,playBack.class);
intent.putExtra("file", file);
intent.putExtra("position", positio);
intent.putExtra("n", n);
startService(intent);
}
if(!isPlaying){
positio = vv.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
//Log.d("zaid iqbal", "in onResume");
if(!isPlaying){
vv.setVideoPath(file);
vv.seekTo(positio);
}else{
async aa = new async();
aa.execute();
}
super.onResume();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
}
public void requestFullScreen(){
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
,WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public void setupSpin(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/");
listFiles(root);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//Log.d("zaid iqbal","in onclick of spin");
if(n == 0){
file = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/" + list.get(position);
Log.d("zaid", file);
//Toast.makeText(MainActivity.this, "original" + file, Toast.LENGTH_SHORT).show();
vv.setVideoPath(file);
vv.start();
}
//n = 0;
/*File fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
position = Integer.parseInt(reader.readLine());
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file);
writer.write(position);
writer.write(n);
position = Integer.parseInt(reader.readLine());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void listFiles(File f){
try{
File[] files = f.listFiles();
for(File file : files){
if(file.isFile()){
String filenameArray[] = file.toString().split("\\.");
String extension = filenameArray[filenameArray.length-1];
//if(extension == "mp4" || extension == "3gp")
list.add(file.getName());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
class async extends AsyncTask<String,Long,Long>{
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
if(intent != null){
stopService(intent);
//Reading file
}
return null;
}
#Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
fl = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video/","settings.txt");
try {
//Log.d("zaid iqbal", "getted file");
BufferedReader reader = new BufferedReader(new FileReader(fl));
file = reader.readLine();
//Toast.makeText(MainActivity.this, "getted file" + file, Toast.LENGTH_SHORT).show();
positio = Integer.parseInt(reader.readLine());
n = Integer.parseInt(reader.readLine());
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(n != 0){
n=0;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fl));
writer.write(file + "\n" + positio + "\n" + n);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vv.setVideoPath(file);
vv.seekTo(positio);
vv.start();
}
super.onPostExecute(result);
}
}
}

First, I would read up on Android activity lifecycle. Personally I think this is the way begin to address the issue -
http://developer.android.com/training/basics/activity-lifecycle/index.html
Another option to investigate -
android:configChanges="orientation|keyboardHidden|screenSize"
how to stop activity recreation on screen orientation?

Try this in your Activity Tag of Manifest file :
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Here Orientation refers to Configuration changes which you want to handle by your own.
To declare that your activity handles a configuration change, edit the appropriate <activity> element in your manifest file to include the android:configChanges attribute with a value that represents the configuration you want to handle.
Use onSaveInstanceState() and onRestoreInstanceState() if you want to restore your previous state of an activity.
Refer this also

You may try to call setRequestedOrientation() in you activity so the orientation is forced.

Related

Uploading xml file to server using Android Service

I am developing an application in android wrein I call a service that will upload a xml file to the server on click of a button.Problem is when I click the button first time it dosent get uploaded but when I click the button second time its gets uploaded...so let me know if there is any solution..pls help me.
Here is code below which extends service
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
public class Uploader extends Service
{
String info;
String phot_loc;
int category;
String phonenumber = null,profile_name=null,email_id=null;
double longi;
double latti;
Runnable runner;
//UIhandler to display the status of upload on response from server
Handler uiHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
if(intent!=null)
{
info=intent.getStringExtra("info");
phot_loc=intent.getStringExtra("photo_loc");
category=intent.getIntExtra("category",0);
phonenumber=intent.getStringExtra("phone_number");
profile_name=intent.getStringExtra("profile_name");
email_id=intent.getStringExtra("email_id");
longi=intent.getDoubleExtra("longitude",0);
latti=intent.getDoubleExtra("latitude",0);
phonenumber=intent.getStringExtra("phone_number");
Log.d("UploadService","Indide upload Activity");
Thread t=new Thread(runner);
t.start();
}
//this will perform the uploading process
runner=new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try
{
Log.d("UploadService","Indide upload Activity RIUNNER");
String xml = createXml();
RestClient client = new RestClient("http://3pixelart.com/complaint_process.php",xml);
//Log.d("UploadService", xml);
try {
client.Execute();
MyRunnable r = new MyRunnable("Complaint Uploaded Successfully");
uiHandler.post(r);
}
catch(Exception e)
{
Log.e("UploadService", "Exception in uploading :"+e.getMessage());
MyRunnable r = new MyRunnable("There was an error while registering complaint. Pls try again "+ e.getMessage());
uiHandler.post(r);
}
}
catch(Exception e)
{
Log.e("UploadService", "Exception:"+e.getMessage());
MyRunnable r=new MyRunnable("Error in uploading the complaint..");
uiHandler.post(r);
}
}
};
}
public String createXml() {
Log.d("UploadService","Indide upload Activity create xml 1");
Log.d("UploadService","Indide upload Activity create xml 2");
Date d = new Date();
//SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
//String time = formatter.format(d);
Log.d("UploadService","Indide upload Activity create xml 3");
String imageData = getBase64ImageData();
SimpleDateFormat fileNameFormatter = new SimpleDateFormat("ddMMyyHHmm");
Log.d("UploadService","Indide upload Activity create xml 5");
String filename = "image"+fileNameFormatter.format(d)+".png";
String finaldata="<?xml version=\"1.0\"?>";
finaldata+="<ClientRequest><MobileNumber>"+phonenumber+"</MobileNumber><Longitude>";
finaldata+=longi+"</Longitude><Lattitude>"+latti+"</Lattitude>";
finaldata+="<Category>"+category+"</Category>";
finaldata+="<Profilename>"+profile_name+"</Profilename><Email>"+email_id+"</Email>";
finaldata+="<FileName>"+filename+"</FileName><Image>"+imageData+"</Image><Info>";
finaldata+=info+"</Info></ClientRequest>";
Log.d("UploadService","The DATA IS : "+finaldata);
return finaldata;
}
private String getBase64ImageData() {
// TODO Auto-generated method stub
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapOrg = BitmapFactory.decodeFile(phot_loc,options);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String encodedImage = Base64.encodeToString(ba, Base64.DEFAULT);
//Log.d("UploadService", encodedImage);
bitmapOrg=null;
System.gc();
return encodedImage;
}
//this is used to display the status of uploading for this u require UIHandler
public class MyRunnable implements Runnable{
private String message=null;
public MyRunnable(String message) {
// TODO Auto-generated constructor stub
this.message=message;
}
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
};
}
and this is my activity which strats that service
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class ComplaintActivity extends Activity implements OnClickListener
{
boolean pic_taken=false;
Button bpicture,bregister;
EditText description;
ImageView iv1;
int category=0;
private static final int TAKE_PICTURE = 1;
String Provider_name="";
Location currentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint);
bpicture=(Button) findViewById(R.id.button1);
bregister=(Button) findViewById(R.id.button2);
iv1=(ImageView) findViewById(R.id.taken_pic);
description=(EditText)findViewById(R.id.editText1);
bpicture.setOnClickListener(ComplaintActivity.this);
bregister.setOnClickListener(ComplaintActivity.this);
LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
List <String> l1=manager.getProviders(true);
if(l1.contains(LocationManager.GPS_PROVIDER))
{
Provider_name=LocationManager.GPS_PROVIDER;
}
if(l1.contains(LocationManager.NETWORK_PROVIDER))
{
Provider_name=LocationManager.NETWORK_PROVIDER;
}
currentLocation=manager.getLastKnownLocation(Provider_name);
Toast.makeText(ComplaintActivity.this, "GPS PROVIDERS "+Provider_name+"Lattti:"+currentLocation.getLatitude()+"Long:"+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
LocationListener listener=new MyLocationListener();
manager.requestLocationUpdates(Provider_name, 0, 0, listener);
}
class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentLocation=location;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0==bpicture)
take_picture();
if(arg0==bregister)
register_complaint();
}
private void take_picture() {
// TODO Auto-generated method stub
Intent int_cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri Outputfile=Uri.parse("file:///sdcard/temppic.jpg");
int_cam.putExtra(MediaStore.EXTRA_OUTPUT,Outputfile);
startActivityForResult(int_cam,TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//Log.d("BAKRA","INSIDE CAMEra Activity>>>>>>>>>>>");
if(requestCode==1)
{
//Log.d("BAKRA","INSIDE FIRST IF >>>>>>>>>>>");
if(resultCode==RESULT_OK)
{
// Log.d("BAKRA","INSIDE SECONG IF >>>>>>>>>>>");
if(data==null)
{
// Log.d("BAKRA","INSIDE THIRD IF >>>>>>>>>>>");
pic_taken=true;
BitmapFactory.Options opt=new BitmapFactory.Options();
opt.inSampleSize=8;
Bitmap bitorg=BitmapFactory.decodeFile("sdcard/temppic.jpg", opt);
// Log.d("BAKRA","INSIDE CAME>>>>>>>>>>>");
iv1.setImageBitmap(bitorg);
}
}
}
}
private void register_complaint() {
// TODO Auto-generated method stub
if(!pic_taken)
{
Toast.makeText(ComplaintActivity.this, "Please Take the Picture Related to the Query", Toast.LENGTH_LONG).show();
return;
}
if(description.getText().toString().equals(""))
{
Toast.makeText(ComplaintActivity.this, "Please Enter Details About the Complaint",Toast.LENGTH_LONG).show();
return;
}
else
{
Intent up=new Intent(ComplaintActivity.this,Uploader.class);
up.putExtra("category",getIntent().getIntExtra("Selected",1));
up.putExtra("info", description.getText().toString());
up.putExtra("photo_loc", "/sdcard/temppic.jpg");
up.putExtra("latitude", currentLocation.getLatitude());
up.putExtra("longitude", currentLocation.getLongitude());
SQLiteDatabase db=openOrCreateDatabase("LBA", MODE_PRIVATE, null);
Cursor c=db.rawQuery("select * from users", null);
String phonenumber = null,profile_name=null,email_id=null;
if(c.moveToFirst())
{
profile_name=c.getString(c.getColumnIndex("profilename"));
email_id=c.getString(c.getColumnIndex("emailid"));
phonenumber=c.getString(c.getColumnIndex("phonenumber"));
}
up.putExtra("phone_number", phonenumber);
up.putExtra("profile_name", profile_name);
up.putExtra("email_id", email_id);
startService(up);
Toast.makeText(ComplaintActivity.this, "Uploading to Server...",Toast.LENGTH_LONG).show();
finish();
}
}
}
onStartCommand intent:
This may be null if the service is being restarted after its process
has gone away, and it had previously returned anything except
START_STICKY_COMPATIBILITY.
http://developer.android.com/reference/android/app/Service.html
So try use:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
rather than finish();

Don't know if it is safe to implement Asynctask like that

I made a code on android and i would like to receive some opinions from stackoverflow people.
It is about a code which i used the AsyncTask class... But i don't know if it is coded good or not ...
Here it is the code:
package com.example.basicmaponline;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.mlab.android.basicoverlays.PostgreSQL;
import com.mlab.android.basicoverlays.SQLloja;
public class Intro extends Activity{
//SQLlistLoja listaLoja;
HashMap<String, SQLloja> listaLoja;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
//Intent openMainActivity = new Intent("com.example.basicmaponline.MAINACTIVITY"); //isto vem do ficheiro AndroidManifest.xml o "com.example....."
//startActivity(openMainActivity);
try {
listaLoja = new loadDatabase().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(listaLoja !=null){
for(SQLloja loja : listaLoja.values()){
Log.d("ASYNC25", loja.getNome() );
}
}
else{
Log.d("ASYNC25", "NAO GUARDOU!" );
}
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
Intent openMenu = new Intent("com.example.basicmaponline.MENU"); //isto vem do ficheiro AndroidManifest.xml o "com.example....."
openMenu.putExtra("listaLoja",listaLoja);
startActivity(openMenu);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//ourSong.release(); //release the music and we are done with you
finish();
}
//#SuppressWarnings("rawtypes")
public class loadDatabase extends AsyncTask<Void, Void, HashMap<String,SQLloja>>{
#Override
protected HashMap<String,SQLloja> doInBackground(Void... params) {
// TODO Auto-generated method stub
HashMap<String,SQLloja>listaLojas = new HashMap<String, SQLloja>();
try{
PostgreSQL pSQL = new PostgreSQL(host,db, username, password);
String sql = pSQL.getLojasCidadao();
Statement st = pSQL.getConnection().createStatement();
ResultSet rs = st.executeQuery(sql);
Log.d("ASYNC2","Entrei na thread ASYNCTASK");
while(rs.next()){
int lcId = Integer.parseInt(rs.getString(1));
String lcNome=rs.getString(2);
String lcCP = rs.getString(3);
int lcDistrito = Integer.parseInt(rs.getString(4));
int lcConselho = Integer.parseInt(rs.getString(5));
double lcAltitude = Double.parseDouble(rs.getString(6));
double lcLongitude = Double.parseDouble(rs.getString(7));
String lcTelefone = rs.getString(8);
boolean lcEstado = Boolean.parseBoolean(rs.getString(9));
String lcRua = rs.getString(10);
SQLloja loja = new SQLloja(lcId,lcNome,lcCP,lcDistrito,lcConselho,lcAltitude,lcLongitude,lcTelefone,lcEstado,lcRua);
listaLojas.put(loja.getNome(),loja.clone());
String informacoesLoja = "Rua : "+lcRua+"\nC.P. : "+lcCP+"\nTel. : "+lcTelefone;
Log.d("ASYNC",lcNome+" Altitude = "+lcAltitude+" Longitude = "+lcLongitude+" Rua = "+lcRua);
}
//listaLoja = new SQLlistLoja(listaLojas);
rs.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if(listaLojas!=null){
Log.d("ASYNC","entrei no if da listaLojas");
for(SQLloja loja : listaLojas.values()){
Log.d("ASYNC", loja.getNome() );
}
}
else Log.d("ASYNC","listaLoja nula ! PQP !");
return listaLojas;
}
#Override
protected void onPostExecute(HashMap<String,SQLloja> listaLojas){
listaLoja = listaLojas;
for(SQLloja loja : listaLoja.values()){
Log.d("ASYNC24", loja.getNome() );
}
}
}
}
I'm not sure but, i think that the return value from AsyncTask isn't made by the right way although its working on my android application.
Some opinions will be welcomed.
Thank you ! :)
When you use the AsyncTask its good create a class instance to implement the methods, and then when you want to use, create a variable asynctask with the method .start(); if i'm no mistaken.
And its good too create a ProgressDialog.

strings over udp android

I can receive data on c# UDP server i have written through this code but instead of string i have typed in the editText box ... i receive android.widget.EditText#xxxxxx on the server. Some Help would be much appreciated.
package com.winmote.pro;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String cmd= editText1.toString();
new nwcomm().execute(cmd);
}
});
}
private class nwcomm extends AsyncTask<String,Void,Void>{
#Override
protected Void doInBackground(String... text) {
// TODO Auto-generated method stub
String msg=text[0].toString();
InetAddress to = null;
try {
to = InetAddress.getByName("192.168.0.105");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int port=55505;
DatagramSocket soc = null;
try {
soc = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = msg.getBytes();
DatagramPacket pac = new DatagramPacket(data, data.length, to, port);
try {
soc.send(pac);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You need to ask for the contents of the EditText, not the String representation of the variable... Change this line:
String cmd= editText1.toString();
To:
String cmd = editText1.getText().toString();

onProgressUpdate() not called during downloading file from dropbox

I have been stucking from last 2 days.. In my case the onProgressUpdate() is not called.. So it is not updating the progress bar.. can any one please have a look and suggest.. Thanks. here is my code
package com.example.downloadupload;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.ProgressListener;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.exception.DropboxException;
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private final ProgressDialog uDialog;
private long dFileLen;
long bytess;
public DownloadFile(Context context,
DropboxAPI<AndroidAuthSession> mDBApi) {
dDBApi=mDBApi;
dContext=context.getApplicationContext();
uDialog = new ProgressDialog(context);
uDialog.setMax(100);
uDialog.setMessage("Downloading Image");
uDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
uDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String path1= Environment.getExternalStorageDirectory()+"/log.txt";
BufferedOutputStream out=null;
try {
File file = new File(path1);
out = new BufferedOutputStream(new FileOutputStream(file));
dDBApi.getFile("/log.txt", null,out,new ProgressListener() {
/* #Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}*/
#Override
public void onProgress(long bytes, long total) {
// TODO Auto-generated method stub
bytess=bytes;
publishProgress(bytes);
}
});
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while downloading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {}
}
}
return null;
}
#Override
protected void onProgressUpdate(Long... progress) {
// TODO Auto-generated method stub
super.onProgressUpdate(progress);
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
uDialog.setProgress(percent);
System.out.println("Hi progressing");
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
uDialog.dismiss();
System.out.println("calling post execute");
}
}
Instead of this
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
Use this
int percent = (int)(100.0*(double)progress[0]/TotalsizeOfFile + 0.5);
And you can uncomment
#Override
public long progressInterval()
{
// Update the progress bar every half-second or so
return 500;
}
It's working for me.
I think the mistake is this
bytess=bytes;
publishProgress(bytes);
and then,
int percent = (int)(100.0*(double)progress[0]/bytess + 0.5);
here, progress[0] = bytess -> everytime, hence progress might not be getting updated.
Make onProgress() something like this
public void onProgress(long bytes, long total) {
// TODO Auto-generated method stub
long[2] bytess = {bytes, total};
publishProgress(bytess);
}
and calculate percentage
int percent = (int)(100.0*(double)progress[0]/progress[1]+ 0.5);

Why is this app running slow?

Why does this app stop answering then I press play? It sometimes show a "the application is not responding" but it works if I wait.
It works nice on my emulator, but not on my phone (or any other phone I tried).
All it does is streaming sound.
package comunicera.se;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Godnattsaga extends ListActivity {
/** Called when the activity is first created. */
ListView list;
TextView spelandesSagqa;
//private ProgressDialog mProgressDialog;
ProgressBar myProgressBar;
int myProgress = 0;
MediaPlayer mp = new MediaPlayer();
String BASEURL = "http://godnattsaga.nu/sagor";
public static long glCurrentSaga = 0;
public static String giCode = null;
int giAntalSagor = 0;
int possWhenPaused = 0;
ProgressBar myBufferProgressBar;
TextView buffrarText;
int progress;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
new Thread(buffer).start();
String lsSagor = getFileFromUrl(BASEURL+"/gratisSagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
//String saga = laList[0].replaceAll("#", "\n");
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
changeSpelandesSaga(laSaga[0]);
setList (guiLaList);
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String liCode = kop(id);
glCurrentSaga = id;
String[] laSaga = laList[(int) glCurrentSaga].split("#");
changeSpelandesSaga(laSaga[0]);
}
});
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay(laList);
}
});
glCurrentSaga = 0;
changeSpelandesSaga(laSaga[0]);
}
catch (Exception e)
{
changeSpelandesSaga("Check your connection, are you in flightmode?");
}
}
public void selectDownloadOrPLay(String[] laList) {
String[] laSaga = laList[(int) glCurrentSaga].split("#");
String url = BASEURL+"/gratis/"+laSaga[0].replaceAll(" ", "_")+".mp3";
if (mp.isPlaying())
{
mp.pause();
possWhenPaused=mp.getCurrentPosition();
}
else if (possWhenPaused != 0)
{
mp.start();
}
else
{
startSaga (url);
}
}
private String kop(long id)
{
mp.pause();
return "gratis";
}
public void setList (String[] laList)
{
/*
*
final String[] lAList = new String[3];
lAList[0] = "Saga 1 \n";
lAList[1] = "Saga 2 \n";
lAList[2] = "Saga 3";
setList (lAList);
*
*/
setContentView(R.layout.main);
ArrayAdapter<String> appointmentList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, laList);
list=(ListView)findViewById(android.R.id.list);
list.setAdapter(appointmentList);
}
public void changeSpelandesSaga(String sagaRubrik)
{
possWhenPaused = 0;
TextView t = new TextView(this);
t=(TextView)findViewById(R.id.spelandesSaga);
t.setText(Html.fromHtml("<b>"+sagaRubrik+"</b>"));
}
private void startSaga(String url)
{
try {
mp.reset();
mp.setDataSource(url);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
myProgressBar=(ProgressBar)findViewById(R.id.mProgressDialog);
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
double poss = 0.0;
double sagaleng = 0.0;
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
poss = mp.getCurrentPosition();
sagaleng = mp.getDuration();
progress = (int) ((int)poss / sagaleng * 100);
myProgress = progress;
myProgressBar.setProgress(progress);
}
};
};
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
showNoConnection ();
return null;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean connected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
return connected;
}
private static void showNoConnection()
{
}
private Runnable buffer = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t)
{
}
}
}
Handler myHandle = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//SpelaPause.setImageURI("pauseicon");
myBufferProgressBar = (ProgressBar)findViewById(R.id.mBuffrar);
TextView bufferText = (TextView)findViewById(R.id.buffrarText);
if (mp.isPlaying() && progress == 0)
{
myBufferProgressBar.setVisibility(View.VISIBLE);
bufferText.setVisibility(View.VISIBLE);
}
else
{
myBufferProgressBar.setVisibility(View.INVISIBLE);
bufferText.setVisibility(View.INVISIBLE);
}
}
};
};
}
If your application uses internet, it is possible, that the phone has worse connection than your comp. For example, if they both run on the SAME WiFi, at the same point, phones are connected MUCH worse than PC. Slower connection - you have to wait...
Read http://developer.android.com/guide/practices/design/responsiveness.html and http://developer.android.com/guide/practices/design/performance.html - VERY useful. For example, you will know the name of your problem - bad responsiveness (not performance) - for better further searches. :-)
All long-lasting tasks should be run in separate thread, not in UI thread. You call getFileFromUrl(..) from onCreate(..) method. This cause hangings.
I recommend you not to do any time consuming task in onCreate(..) method. In general an activity won't be shown till onCreate(..) is finished.
You are using getFileFromUrl in your onCreate method. Your method just performs the download action, which in case could last some time. You should always move long running tasks into it's own thread and notify the UI thread only.
Consider never running big logic in the UI thread, the UI thread should only be responsible for UI stuff.
To download a file in an async manner try to use the AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html
This code works, without responsiveness problems. But the buffering takes to long time so I need another solution.
I'm posting some code if someone else have the same problem
package comunicera.se;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class GodnattsagaTest1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.SpelaPause);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
selectDownloadOrPLay();
}
});
}
public void selectDownloadOrPLay() {
Toast.makeText(getApplicationContext(), "Before ... ", Toast.LENGTH_SHORT).show();
Saga.startSaga ();
Toast.makeText(getApplicationContext(), "after ... ", Toast.LENGTH_SHORT).show();
}
}
class Saga
{
static MediaPlayer mp = new MediaPlayer();
static void startSaga()
{
new Thread(spelaSaga).start();
}
private static Runnable spelaSaga = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try {
mp.reset();
mp.setDataSource("http://godnattsaga.nu/sagor/gratis/Fisken.mp3");
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
};
}
I believe it has something to do with the progress bar you use. I use one and it slows my app. Not sure if the progress bar must slow the app or there is another way to avoid this though.

Categories

Resources