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.
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];
}
}
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();
}
Code first:
public class MyActivity extends Activity {
Button send;
TextView textv;
String answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
send = (Button)findViewById(R.id.sendButton);
textv = (TextView)findViewById(R.id.textViewv);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MyClientTask myClientTask = new MyClientTask("localhost", 1234, "QUESTION");
myClientTask.execute();
}
});
}
void processAnswer() {
Log.i("DEBUG", "in processAnswer - before setting text");
Log.i("DEBUG", "ANSWER");
textv.setText("ANSWER\n"); // <-------- H E R E -----------
Log.i("DEBUG", "in processAnswer - after setting text");
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String message;
String response;
MyClientTask(String addr, int port, String msg){
dstAddress = addr;
dstPort = port;
message = msg;
response = "";
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
InetAddress serverAddr = InetAddress.getByName(dstAddress);
socket = new Socket(serverAddr, dstPort);
OutputStream out = socket.getOutputStream();
out.write(message.getBytes());
out.flush();
String msgrc = "";
int charsRead = 0;
char[] inputBuf = new char[4096];
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
while ((charsRead = in.read(inputBuf)) != -1) {
msgrc += new String(inputBuf).substring(0, charsRead);
}
// outer class variable
MyActivity.this.answer = msgrc;
out.close();
is.close();
socket.close();
Log.i("DEBUG", "before processing answer");
MyActivity.this.processAnswer();
Log.i("DEBUG", "after processing answer");
} catch (Exception e) {
}
return null;
}
}
}
The code above simply sends some message to a server and receives an answer. This answer should then be displayed in the TextView (see marked line). However, the app hangs at that line, i.e, LogCat displays
[...]
before processing answer
in processAnswer - before setting text
ANSWER
Then no more lines are written to LogCat. Has anybody an explanation for that? If the marked line is commented out, LogCat looks like
[...]
before processing answer
in processAnswer - before setting text
ANSWER
in processAnswer - after setting text
after processing answer
If you move your call to MyActivity.this.processAnswer() to onPostExecute() instead, perhaps that might work - IIRC, items on the UI thread should only be updated from the UI thread.
First inialize your text view by following , then add onPostExecute method bellow the doInBackground
method . And set your text there . Bellow is code which i change.
public class MyActivity extends Activity {
Button send;
TextView textv;
String answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
send = (Button)findViewById(R.id.sendButton);
textv = (TextView)findViewById(R.id.textview);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MyClientTask myClientTask = new MyClientTask("localhost", 1234, "QUESTION");
myClientTask.execute();
}
});
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String message;
String response;
MyClientTask(String addr, int port, String msg){
dstAddress = addr;
dstPort = port;
message = msg;
response = "";
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
InetAddress serverAddr = InetAddress.getByName(dstAddress);
socket = new Socket(serverAddr, dstPort);
OutputStream out = socket.getOutputStream();
out.write(message.getBytes());
out.flush();
String msgrc = "";
int charsRead = 0;
char[] inputBuf = new char[4096];
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
while ((charsRead = in.read(inputBuf)) != -1) {
msgrc += new String(inputBuf).substring(0, charsRead);
}
// outer class variable
MyActivity.this.answer = msgrc;
out.close();
is.close();
socket.close();
Log.i("DEBUG", "before processing answer");
MyActivity.this.processAnswer();
Log.i("DEBUG", "after processing answer");
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
textv.setText(msgrc);
}
}
}
I'm developing an application which pulls weather data from a MySQL database by using PHP and JSON. It checks wether the user has an internet connection, if not then it will look for a file stored locally. If that file doesn't exists then it will display a message. To refresh the list, the user has to restart the application. I found this not really user-friendly so I decided to add a button which refreshes the data.
I have two classes, my ListActivity class (called WeerActivity.java in the code below) and a class which gathers all the data from the internet in a new thread (called InternetWeerThread.java). My onClickListener, for the refresh button, is set up in the ListActivity class. This tries to post a runnable to the other class, containing the refresh code. However when I do this. I get an exception because the code is still executed on the UI-Thread.
WeerActivity.java
public class WeerActivity extends ListActivity{
private static Thread internetWeerThread;
private InternetWeerThread internetWeerThreadInstance;
public static Handler activityHandler;
public static Handler internetHandler;
public static ListView listView;
public static Context context;
public static LinearLayout weerContainer;
public static Button refreshButton;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.weer);
refreshButton = (Button) findViewById(R.id.weer_refresh_button);
listView = (ListView)findViewById(android.R.id.list);
weerContainer = (LinearLayout) findViewById(R.id.weer_container);
context = this;
activityHandler = new Handler();
internetWeerThreadInstance = new InternetWeerThread(activityHandler);
internetWeerThread = internetWeerThreadInstance;
internetHandler = InternetWeerThread.getHandler();
internetWeerThread.start();
refreshButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
internetHandler.post(internetWeerThreadInstance.new Refresh());
}
});
}
}
InternetWeerThread.java
class InternetWeerThread extends Thread{
private Handler activityHandler;
private static String html;
private static JSONArray weerItems;
private static ArrayList<WeerData> weerData = new ArrayList<WeerData>();
private static WeerAdapter adapter;
private static String JSONString;
private static final String timeoutString = "Unable to connect with the server, check your internet connection";
private static final Handler internetWeerThread = new Handler();
// CONSTRUCTOR
public InternetWeerThread(Handler activityHandler){
this.activityHandler = activityHandler;
}
public static Handler getHandler(){
return internetWeerThread;
}
#Override
public void run(){
onRefresh();
}
// method that gets called by the Runnable Refresh (and onCreate)
private void onRefresh(){
try{
weerItems = getWeerItems("http://192.168.178.14/weer.php");
JSONString = weerItems.toString();
FileAccess.createFile(WeerActivity.context, "weer.txt", JSONString);
displayData(weerItems);
}catch(IOException e){
e.printStackTrace();
System.out.println(WeerActivity.context);
if(FileAccess.fileExists(WeerActivity.context, "weer.txt")){ // read data from file
JSONArray JSONData;
try {
if(FileAccess.readFile(WeerActivity.context, "weer.txt") != null){
JSONData = new JSONArray(FileAccess.readFile(WeerActivity.context, "weer.txt"));
displayData(JSONData);
activityHandler.post(new Updater());
}else{
activityHandler.post(new TimeOut());
}
} catch (JSONException je) {
je.printStackTrace();
activityHandler.post(new TimeOut());
}
}else{ // display message that there is no internet connection and no file present
activityHandler.post(new TimeOut());
}
}
}
private JSONArray getWeerItems(String link) throws IOException{
HttpUriRequest request = new HttpGet(link.toString());
BasicHttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
ConnManagerParams.setTimeout(httpParameters, timeoutConnection);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode() == 200){
JSONArray jArray = new JSONArray();
try {
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
try {
jArray = new JSONArray(html);
} catch (JSONException e) {
e.printStackTrace();
}
return jArray;
}catch (Exception e) {
e.printStackTrace();
}
return jArray;
}else{
activityHandler.post(new TimeOut());
JSONArray jArray = new JSONArray();
return jArray;
}
}
private void readStream(InputStream in){
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
html = "";
while ((line = reader.readLine()) != null) {
html += line;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void displayData(JSONArray jArray){
try{
int length;
if(jArray.length() < 7){
length = jArray.length();
}else if (jArray.length() > 7){
length = 7;
}else{
length = 7;
}
for(int i = 0; i < length; i++){
JSONObject row = jArray.getJSONObject(i);
int temperatureDay = row.getInt("temperature_day");
int temperatureNight = row.getInt("temperature_night");
String date = row.getString("date");
int weatherType = row.getInt("weather_type");
WeerData singleWeerData = new WeerData();
singleWeerData.setTemperatureDay(temperatureDay);
singleWeerData.setTemperatureNight(temperatureNight);
singleWeerData.setDate(date);
singleWeerData.setWeatherType(weatherType);
weerData.add(i, singleWeerData);
}
activityHandler.post(new Updater());
}catch(JSONException e){
e.printStackTrace();
}
}
// update the listView
public class Updater implements Runnable{
public void run(){
adapter = new WeerAdapter(WeerActivity.context, R.layout.weer_row, weerData);
WeerActivity.listView.setAdapter(adapter);
}
}
Threads and Runnables are new to me. This is the first Android application I'm creating. So hopefully someone can help me solve this problem.
Any help will be appreciated !
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");
}
}