I have on mainactivty 7 radio buttons each button want to be different time (1min , 5 min , 10 min ,.....) and I have asynctask there i'm calling pictures from server (php) so I want when the user selects the first radio button (1 min) the the asynctask execute every 1 min i tried radiobutton.ischecked and puttet handler it didn't worked out
my server working and I'm receiving response but I cant execute the asynctask with this settings to setwallpaper it took a look a my code
TextView txt;
Button btn;
ImageView imageView;
String forecastJsonStr;
RadioButton rd1,rd2,rd3,rd4,rd5,rd6,rd7;
Runnable mHandlerTask;
Handler mHandler;
RadioGroup radioGroup;
private final static int INTERVAL = 4000 ; //1 min
private final static int INTERVAL2 = 1000 * 60 * 5; // 5 min
private final static int INTERVAL3 = 1000 * 60 * 10; // 10 min
private final static int INTERVAL4 = 1000 * 60 * 15; // 15 min
private final static int INTERVAL5 = 1000 * 60 * 30 ; // 30 min
private final static int INTERVAL6 = 1000 * 60 * 60; // 1 hour
private final static int INTERVAL7 = 1000 * 60 * 1440; // 1 day
private final String hostName = "http://555.555.555.555";
private final String hostRequestName = "/yay.php";
private final String hostWallpaperName = "/wallpaper/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.textView);
imageView = (ImageView) findViewById(R.id.imageView);
rd1 = (RadioButton)findViewById(R.id.radioButton) ;
rd2 = (RadioButton)findViewById(R.id.radioButton2) ;
rd3 = (RadioButton)findViewById(R.id.radioButton3) ;
rd4 = (RadioButton)findViewById(R.id.radioButton4) ;
rd5 = (RadioButton)findViewById(R.id.radioButton5) ;
rd6 = (RadioButton)findViewById(R.id.radioButton6) ;
rd7 = (RadioButton)findViewById(R.id.radioButton7) ;
radioGroup = (RadioGroup)findViewById(R.id.radiogroup) ;
mHandler = new Handler();
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(rd1.isChecked()) {
mHandlerTask = new Runnable() {
#Override
public void run() {
new WallpaperData().execute();
mHandler.postDelayed(mHandlerTask, INTERVAL);
startRepeatingTask();
}
};
}
}
void startRepeatingTask()
{
mHandlerTask.run();
}
});
}
private class WallpaperData extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://555.555.555.555/yay.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
DataOutputStream wr = new DataOutputStream(
urlConnection.getOutputStream());
wr.write("method=get_random_wallpaper".getBytes());
wr.flush();
wr.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("hey", buffer.toString());
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
return forecastJsonStr;
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(final String forecastJsonStr) {
txt.setText(forecastJsonStr);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap result = Picasso.with(getBaseContext())
.load(hostName + hostWallpaperName + forecastJsonStr)
.get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
thread.start();
super.onPostExecute(forecastJsonStr);
}
}
}
Create a variable to store the select interval. Move the mHandlerTask and startRepeatingTask method outside onCreate. Inside the onClick call startRepeatingTask method.
See the code below,
private final static int SELECTED_INTERVAL = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(rd1.isChecked()) {
SELECTED_INTERVAL = INTERVAL;
} else if (rd2.isChecked()) {
SELECTED_INTERVAL = INTERVAL2;
}
stopRepeatingTask();
startRepeatingTask();
}
});
}
void startRepeatingTask() {
mHandlerTask.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(null);
}
Runnable mHandlerTask = new Runnable() {
#Override
public void run() {
new WallpaperData().execute();
mHandler.postDelayed(mHandlerTask, SELECTED_INTERVAL);
}
};
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Related
This is my AsyncTask that is being executed when I click an item in a ListView. I display a ProgressDialog while the task is running and dismiss it at the end of onPostExecute() as shown below. This works and the spinner displays in my Nexus 5X emulator. On any other emulator or my real device (Galaxy S7 Edge Nougat) however, the dialog shows but without a spinner or with the spinner but it instantly freezes. I HAVE turned on all transitions/animations to 1x in the developer options by the way and all my other animations work so I know that is not the issue.
public class LoadHunt extends AsyncTask<String, Void, String> {
private static final String TAG = LoadHunt.class.getSimpleName();
private PostLoginFragment listener;
private String hunt;
private int item;
private ProgressDialog pd;
public LoadHunt(PostLoginFragment listener, int item) {
this.listener = listener;
this.item = item;
}
#Override
public void onPreExecute() {
pd = new ProgressDialog(listener.getActivity());
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(false);
pd.show();
//((PostLoginFragment)listener).getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
#Override
protected String doInBackground(String... huntname) {
try {
hunt = huntname[0];
String link = "https://cniekirk.com/gethunt3.php?huntname=" + huntname[0];
URL url = new URL(link);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setDoInput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
StringBuffer sb = new StringBuffer("");
String s = "";
while((s = in.readLine()) != null){
sb.append(s);
}
in.close();
return sb.toString();
}catch (Exception e) {
Log.e(TAG, "Connection error!");
return null;
}
}
#Override
protected void onPostExecute(String result){
List<String> resultSplit = Arrays.asList(result.substring(0, result.length() - 5).split(" xxxx"));
List<List<String>> clueDetailsSplit = new ArrayList<>();
for(String clueStuff: resultSplit) {
clueDetailsSplit.add(Arrays.asList(clueStuff.split("\\s+")));
}
final List<Clue> clues = new ArrayList<>();
for(List<String> clueDetails : clueDetailsSplit) {
final StringBuilder stringBuilder = new StringBuilder();
for(int i = 1; i <= clueDetails.size() - 5; i++) {
if(stringBuilder.length() > 0) {
stringBuilder.append(" ");
}
stringBuilder.append(clueDetails.get(i));
}
final Clue clue;
if(!(clueDetails.get(clueDetails.size() - 1).equals("noimage"))) {
clue = new Clue(clueDetails.get(0), stringBuilder.toString(), com.ploetz.dev.treasurehunt.Data.Status.LOCKED,
Double.parseDouble(clueDetails.get(clueDetails.size() - 3)), Double.parseDouble(clueDetails.get(clueDetails.size() - 2)),
getBitmapFromUrl("https://cniekirk.com/" + clueDetails.get(clueDetails.size() - 1)));
} else {
clue = new Clue(clueDetails.get(0), stringBuilder.toString(), com.ploetz.dev.treasurehunt.Data.Status.LOCKED,
Double.parseDouble(clueDetails.get(clueDetails.size() - 3)), Double.parseDouble(clueDetails.get(clueDetails.size() - 2)));
}
clues.add(clue);
}
//((PostLoginFragment)listener).getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
GlobalResources.setHuntClues(clues);
GlobalResources.setHuntname(hunt);
GlobalResources.organiseClues();
GlobalResources.setItemClicked(item);
//System.gc();
pd.dismiss();
listener.onTaskCompleted();
}
public Bitmap getBitmapFromUrl(final String src) {
final CountDownLatch latch = new CountDownLatch(1);
final Bitmap[] bmp = new Bitmap[1];
Thread thread = new Thread(){
#Override
public void run(){
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
bmp[0] = BitmapFactory.decodeStream(input, null, options);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
// Causes latch.await() to stop blocking and carry on execution
latch.countDown();
}
};
thread.start();
try {
latch.await();
}catch (InterruptedException e) {
Log.e(TAG, "Thread error!");
}
return bmp[0];
}
}
How is it possible to change my asyncTask into service because everytime i close the app or the restart the device my aysncTask not working .
I have aysnc that sends Post request to php server and i got back an image on every request so i putted setting option to the user he can choose to the picture of wallpaper to change on every 1,5,10,..... min but like i said i want to be service so when the user choose the timing to change the wallpaper and closes (destroy) the application the server still countinue to change here is my code
public class MainActivity extends AppCompatActivity {
TextView txt;
Button btn;
String forecastJsonStr;
RadioButton rd1, rd2, rd3, rd4, rd5, rd6, rd7;
Handler mHandler;
RadioGroup radioGroup;
private final static int INTERVAL = 1000*60 * 1; //1 min
private final static int INTERVAL2 = 1000*60*5; // 5 min
private final static int INTERVAL3 = 1000 * 60 * 10; // 10 min
private final static int INTERVAL4 = 1000 * 60 * 15; // 15 min
private final static int INTERVAL5 = 1000 * 60 * 30; // 30 min
private final static int INTERVAL6 = 1000 * 60 * 60; // 1 hour
private final static int INTERVAL7 = 1000 * 60 * 1440; // 1 day
private final String hostName = "http://555.555.555.555";
private final String hostRequestName = "/yay.php";
private final String hostWallpaperName = "/wallpaper/";
private static int SELECTED_INTERVAL = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.textView);
rd1 = (RadioButton) findViewById(R.id.radioButton);
rd2 = (RadioButton) findViewById(R.id.radioButton2);
rd3 = (RadioButton) findViewById(R.id.radioButton3);
rd4 = (RadioButton) findViewById(R.id.radioButton4);
rd5 = (RadioButton) findViewById(R.id.radioButton5);
rd6 = (RadioButton) findViewById(R.id.radioButton6);
rd7 = (RadioButton) findViewById(R.id.radioButton7);
radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
mHandler = new Handler();
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(rd1.isChecked()) {
SELECTED_INTERVAL = INTERVAL;
} else if (rd2.isChecked()) {
SELECTED_INTERVAL = INTERVAL2;
}
startRepeatingTask();
}
});
}
void startRepeatingTask() {
mHandlerTask.run();
}
Runnable mHandlerTask = new Runnable() {
#Override
public void run() {
new WallpaperData().execute();
mHandler.postDelayed(mHandlerTask, SELECTED_INTERVAL);
}
};
private class WallpaperData extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://555.555.555.555/yay.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
DataOutputStream wr = new DataOutputStream(
urlConnection.getOutputStream());
wr.write("method=get_random_wallpaper".getBytes());
wr.flush();
wr.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("hey", buffer.toString());
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
return forecastJsonStr;
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(final String forecastJsonStr) {
txt.setText(forecastJsonStr);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap result = Picasso.with(getBaseContext())
.load(hostName + hostWallpaperName + forecastJsonStr)
.get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
thread.start();
super.onPostExecute(forecastJsonStr);
}
}
}
For time intervals larger than 30 secs you should use AlarmManager instead of Handler's .postDelayed method. See these tutorials: https://developer.android.com/training/scheduling/alarms.html, http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/ . There is a JonScheduler for scheduling repeating tasks, Vogella has tutorial on it: http://www.vogella.com/tutorials/AndroidTaskScheduling/article.html .
In a few words: you create Service (InteneService), create PendingIntent, pointing to that service and schedule AlarmManager, which will be sending that intent, which, in turn, sill be launcing your IntentService.
I am working on an android chat application based on sockets. I am using the following code to implement this:
NetClient.java
public class NetClient {
/**
* Maximum size of buffer
*/
public static final int BUFFER_SIZE = 2048;
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String host = null;
private int port = 3000;
// private int port;
/**
* Constructor with Host, Port
*
* #param host
* #param port
*/
public NetClient(String host, int port) {
this.host = host;
this.port = port;
}
private void connectWithServer() {
Log.e("Server", "Connecting with server");
try {
if (socket == null) {
System.out.println("Socket is null");
socket = new Socket(this.host, this.port);
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void disConnectWithServer() {
Log.e("Server", "Disconnecting with server");
if (socket != null) {
if (socket.isConnected()) {
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendDataWithString(String message) {
Log.e("Send data", "Sendind data to server");
if (message != null) {
connectWithServer();
out.write(message);
out.flush();
}
}
public String receiveDataFromServer() {
Log.e("Receive data", "Receivind data from the server");
try {
String message = "";
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
//Log.e("ServerResponse", message);
disConnectWithServer(); // disconnect server
return message;
} catch (IOException e) {
return "Error receiving response: " + e.getMessage();
}
}
}
ChatActivity.java
public class ChatActivity extends Activity {
private EditText edtMsg;
private Button btnSend;
private String serverIpAddress = "192.168.2.250";
private int port = 3000;
private boolean connected = false;
private Handler handler = new Handler();
private BufferedReader in = null;
private PrintWriter out = null;
public static final int BUFFER_SIZE = 2048; // Max. size of buffer
private Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
edtMsg = (EditText) findViewById(R.id.edtMessage);
btnSend = (Button) findViewById(R.id.btnSendMessage);
btnSend.setOnClickListener(connectListener);
}
private View.OnClickListener connectListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"clicked",Toast.LENGTH_LONG).show();
Log.e("Button", "Button clicked");
if (!connected) {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
NetClient nc = new NetClient(serverIpAddress, port);
String message = edtMsg.getText().toString().trim();
Log.e("Msg", message);
nc.sendDataWithString(message);
String response = nc.receiveDataFromServer();
Log.e("Server Response ", response);
}
}
}
I am not able to verify whether the data has been posted to server or not as i am getting unexpected result from the server.
Logcat
E/Server Response﹕ [ 12-01 14:56:01.313 302: 1017 V/qcbassboost ]
I think i am doing some mistake in the use of socket.Please help me to resolve the issue.
I have a process in a button (large process). I want to update the TextView with diferents values. Like:
Connecting...
Receiving Files...
Complete...
etc..
I'm using setText(); void, but I'm getting only the last value of setText();, in that case:
estatEdit.setText("Tareas completadas!");
Here is my code...
public class sincroGeneral extends Activity implements OnClickListener {
private static final String CATEGORIA = "libro";
private static final String HOST = "192.168.1.165";
private static final int PORT = 9889;
private static final int PORTDATOS = 9888;
int filesize=6022386;
int bytesRead;
int current = 0;
byte [] mybytearray = new byte [filesize];
byte buffer[] = new byte[1024];
byte buffer2[] = new byte[1024];
byte bufferArxiu[] = new byte[2048];
int s;
int s2;
String Benvinguda;
String compra;
EditText estatEdit;
EditText editInflated;
File myfile;
SQLiteDatabase baseDatos;
LinearLayout mainLayout;
View view2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.sincrolayout);
Button b = (Button) findViewById(R.id.BotoEnviarSincro);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Button b = (Button) findViewById(R.id.BotoEnviarSincro);
estatEdit = (EditText) findViewById(R.id.editSincro);
estatEdit.setText("Enviando petición...");
b.setClickable(false);
b.setFocusable(false);
b.setEnabled(false);
ProcesRebre();
b.setClickable(true);
b.setFocusable(true);
b.setEnabled(true);
}
});
}
private void mostrarMensaje(String mensaje)
{
Toast.makeText(this, mensaje, 500).show();
}
private void ProcesRebre()
{
Socket sockDatos = null;
Socket clientSocket = null;
DataOutputStream sortida;
DataInputStream entrada;
BufferedReader inFromServer;
DataOutputStream sortidaDatos;
DataInputStream entradaDatos;
BufferedReader inFromServerDatos;
try {
estatEdit.setText("Conectando...");
clientSocket = new Socket(HOST, PORT);
sortida = new DataOutputStream(clientSocket.getOutputStream());
entrada = new DataInputStream(clientSocket.getInputStream());
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sortida.writeBytes("FAS4-F#S-1-F#S- 1.0.152-F#S-");
Log.i("Enviat","OK");
clientSocket.setSoTimeout(30000);
s = entrada.read(buffer);
String str = new String(buffer, "UTF8");
clientSocket.setSoTimeout(0);
Log.i("Rebut","OK");
if(str.contains("PDA1-F#S-"))
{
sockDatos = new Socket(HOST, PORTDATOS);
estatEdit.setText("Esperando archivo....");
sortidaDatos = new DataOutputStream(sockDatos.getOutputStream());
entradaDatos = new DataInputStream(sockDatos.getInputStream());
inFromServerDatos = new BufferedReader(new InputStreamReader(sockDatos.getInputStream()));
sortidaDatos.writeBytes("FAS4-F#S-1-F#S- 1.0.150-F#S-");
if(sockDatos.isConnected())
{
System.out.println("Conectat amb port 9888");
}
File carpetaSincro = new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/");
carpetaSincro.mkdirs();
File ArxiuSincro = new File (Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip");
if(ArxiuSincro.exists())
{
ArxiuSincro.delete();
}
File ArxiuSincro2 = new File (Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip");
ArxiuSincro2.createNewFile();
sortida.writeBytes("FAS2-F#S-");
String str2= "";
clientSocket.setSoTimeout(30000);
while(true && (!str2.contains("PDA7-F#S-") && !str2.contains("PDAERR1-F#S-")))
{
s2 = entrada.read(buffer2);
str2 = new String(buffer2, "UTF8");
}
clientSocket.setSoTimeout(0);
String replace1 = str2.replace("PDA7-F#S-", "");
String replace2 = replace1.replace(" ", "");
String tamanyArxiu = replace2.replace("-F#S-ZIP","");
int bufferZip = Integer.parseInt(tamanyArxiu);
boolean in;
s2 = 0;
sockDatos.setSoTimeout(30000);
RandomAccessFile archivo = new RandomAccessFile(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip", "rw");
long tamArxActual = 0;
while(bufferZip>=tamArxActual)
{
sockDatos.setSoTimeout(10000);
s2 = entradaDatos.read(bufferArxiu);
estatEdit.setText("Recibiendo archivo....");
archivo.write(bufferArxiu);
tamArxActual = archivo.length();
Thread.sleep(2);
}
sockDatos.setSoTimeout(0);
estatEdit.setText("Archivo recibido");
str2 = "";
clientSocket.setSoTimeout(30000);
while(true && (!str2.contains("PDA3-F#S-") && !str2.contains("PDAERR1-F#S-")))
{
s2 = entrada.read(buffer2);
str2 = new String(buffer2, "UTF8");
}
clientSocket.setSoTimeout(0);
if(str2.contains("PDA3-F#S-"))
{
sortida.writeBytes("FAS7-F#S-");
Thread.sleep(2000);
sortida.writeBytes("FAS6-F#S-");
}
sockDatos.close();
clientSocket.close();
String pathZip = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/sincroorders.zip";
String directoriExtraccio = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/";
String pathTxt = Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt";
UnzipUtility unzipper = new UnzipUtility();
try {
unzipper.unzip(pathZip, directoriExtraccio);
} catch (Exception ex) {
System.out.print("No s'ha pogut descomprimir l'arxiu");
ex.printStackTrace();
}
File f = new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.dll");
f.renameTo(new File(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt"));
importarSincro();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void importarSincro() throws SQLException, IOException
{
int contador = 0;
String LiniaSQL;
FileInputStream fstream = new FileInputStream(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt");
DataInputStream DataInFile = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(Environment.getExternalStorageDirectory()+"/OrdersCE/Syncro/SincrofitPC.txt"), "Latin-1"));
String FinalSQL = "";
baseDatos = openOrCreateDatabase("BBDD", MODE_WORLD_WRITEABLE, null);
baseDatos.execSQL("BEGIN");
while ((LiniaSQL = br.readLine()) != null) {
if(contador > 0)
{
FinalSQL = LiniaSQL.replace("***** ", "");
if(FinalSQL.contains("DELETE") && !FinalSQL.contains("DELETE FROM"))
{
FinalSQL = FinalSQL.replace("DELETE", "DELETE FROM");
try{
baseDatos.execSQL(FinalSQL);
}catch(SQLiteException e){
}
}
else
{
try{
baseDatos.execSQL(FinalSQL);
}catch(SQLiteException e){
}
}
LiniaSQL = "";
}
contador++;
}
baseDatos.execSQL("COMMIT");
estatEdit.setText("Tareas completadas!");
baseDatos.close();
}
/////////////////////////////////////////
public static String deserializeString(File file)
throws IOException {
int len;
char[] chr = new char[4096];
final StringBuffer buffer = new StringBuffer();
final FileReader reader = new FileReader(file);
try {
while ((len = reader.read(chr)) > 0) {
buffer.append(chr, 0, len);
}
} finally {
reader.close();
}
return buffer.toString();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Thanks in advance!
David.
Internet connection is a blocking action, i.e. it blocks the UI until the action is complete (this is why only the last update is seen). You have to move it to a Thread (or even better to an AsyncTask). But then you get another problem, you cannot update UI from outside the main Thread. So, you have to use a Handler to update the UI.
You are executing a network operation on main thread, point to understand here is Android operates upon single main thread so if you do any time consuming operation on Service/Activity/Content Providers etc, it will block your main thread and hence all the stuff will look like they are blocked/un-responsive infact you will receive an ANR message after few seconds.
to conclude, follow this approach
Move your network extensive code to a separate thread
Implement a Mesasge handling mechanism to update your UI on main thread (Handler/Looper)
to help out things further Android provides you a class AsynTask for this purpose. You can do your operation in doInBackground() and upon condition you can update you UI through onProcessUpdate()
hope this helps.
If you run this process on UI thread it may cause to prompt a dialog saying "Applicaiton
not responding".So I recommend this task must be done either in AsyncTask or Service
U can update your text view in
onPreExecute()
onProgressUpdate()
onPostExecute() functions in AsyncTask.
Eg.for downloading file
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
This is my Activity class where i use AsyncTask to get data from a server:
public class UserProfileActivity extends Activity {
private ImageView userImage;
private TextView userName;
private TextView userLocation;
private TextView editInfo;
private TextView chnageImage;
private TextView userScore;
private ListView friendsList;
public ArrayAdapter<String> adapter;
public int score;
public int level;
public String image;
public String fname;
public String lname;
public String city;
public int id;
public String email;
protected Activity activity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
chnageImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsList = (ListView) findViewById(R.id.friendsList);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
#Override
protected String doInBackground(String... params) {
try {
HttpPost httppost = new HttpPost(
"http://www.xxxxxxxxx.com/mobile/getProfileInfo");
HttpResponse response = SignUpActivity.httpclient
.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
id = jObj.getInt("user_id");
email = jObj.getString("email");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
int size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
String[] friendsIds = new String[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
}
adapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
}
} catch (Exception e) {
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
userImage.setImageBitmap(bitmap);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
when this activity is loaded it shows all the default values and images and then changes when background code execution is competed(as excepted), but this takes 2-3 secs for which user will be seeing default values, which i dont want to. So how can i keep a spinner like this:
for 2-3 secs and then when the spinner disappears the activity must show the actual values.
Thank you
Refer the below code
private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected Boolean doInBackground(final String... args) {
try {
Utilities.arrayRSS = objRSSFeed
.FetchRSSFeeds(Constants.Feed_URL);
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
// Setting data to list adapter
setListData();
}
Do This:-
Declare the ProgressDialog at the Top.
ProgressDialog pd;
Start it in onPreExecute Method of Async Task.
pd=ProgressDialog.show(ActivityName.this,"","Please Wait",false);
Stop it in the onPostExecute Method.
pd.dismiss();
In onCreate method call some like below
mdialog=new Dialog(this);
new LongOperation().execute("");
Then override onPostExecute of AyncTask
#Override
protected void onPostExecute() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mdialog.dismiss();
}
});
}