I have a little problem. In my android app, i have to connect to an online server.
The connection should be called with an click-button an as an backround service. I know that I must put the network connection in a thread, but i don't know how it works.
I put the call in a own method wich creates a thread but at compilation i got a error message.
here is my code:
Button:
ImageView refresher = (ImageView)findViewById(R.id.imgRefresh);
refresher.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
httpThread();
}
});
thread method:
private void httpThread(){
final Handler h = new Handler();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
h.post(new Runnable(){
#Override
public void run() {
try{
vomServerholenUndSpeichern();
FileInputStream inStream = null;
try {
inStream = openFileInput("test.xml");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
leseDatei(inStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
createListView("test.xml");
System.out.println(inStream);
drawListView();
} catch (Exception e){
e.printStackTrace();
}
}
});
}
});
thread.start();
}
Can someone help me to fix the problem?
You have to use AsyncTask, is not difficult.
AsyncTask are necessary to avoid block UI during your connection operation, the method doInbackGround of AsyncTask is used for this kind of operations (it runs in a thread different from the UI), while int the onPostExecute (this run on the UI) of the task you will manage your httpResult;)
Related
I am new in Android development. I am trying to show a ProgressDialog. I see lots of tutorial that say for showing dialog must use thread. As you can see snippet code is using thread.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
refreshFromFeed();
} catch (InterruptedException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
}
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
dialog.dismiss();
}
protected void onRefresh(View view) throws InterruptedException {
refreshFromFeed();
}
The log shows it took 5 second, however, I cannot see any dialog on my screen and I can do anything on the screen. Even I use on a physical device. I've used debugging mode. There is no exception.
onRefresh is an event by onClick that declared on it's xml.
I've made a little bit changes of your code read it carefully.
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo",String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
}
private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"Loading","Wake up after some sleep");
Thread th = new Thread() {
public void run() {
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis() / 1000));
try {
Thread.sleep(5000);
dialog.dismiss(); // dismiss your dialog here
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis() / 1000));
}
};
th.start();
}
You still run the ProgressDialog in your UI thread.
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
New thread created after this line, not before this line!
You are dismissing your dialog just right after showing it.
Maybe you want to move your "dialog.dismiss();" to inside the thread. Remember that you need to dismiss the dialog on UI Thread, otherwise it will crash your app:
private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
});
}
};
th.start();
}
I see lots of tutorial that say for showing dialog must use thread.
You don't explicitly need a thread to show a ProgressDialog, this is just an example to dismiss it after 5000 ms
I'm trying to get advertising ID from Google Play services API. Here is a sample code:
...
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
...
public class MyActivity extends Activity {
#Override
protected void onStart() {
super.onStart();
Thread thr = new Thread(new Runnable() {
#Override
public void run() {
try {
Context ctx = MyActivity.this.getApplicationContext();
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
});
thr.start();
synchronized (thr) {
try {
thr.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
When I'm calling getAdvertisingIdInfo method, application hangs forever (no matter with debugger or not).
I'm using Windows ADT 22.3, Android SDK API 19, Google Play SDK rev. 16, Android 4.4.2 Nexus devices. I'm integrating API as described here: https://developer.android.com/google/play-services/id.html
What could be a reason?
I found the reason. It shouldn't block onStart() handler because blocked context blocks Play API in ID settings obtaining. Fixed code looks like this:
#Override
protected void onStart() {
super.onStart();
Thread thr = new Thread(new Runnable() {
#Override
public void run() {
try {
Context ctx = MyActivity.this.getApplicationContext();
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);
finished(adInfo);
} catch (...) {
// All exceptions blocks
}
finished(null);
}
});
thr.start();
}
private void finished(final AdvertisingIdClient.Info adInfo){
if(adInfo!=null){
// In case you need to use adInfo in UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do some stuff with adInfo
}
});
}
}
It would be helpful if official instructions had such usage comments.
Unfortunately the getAdvertisingIdInfo call needs to be done from a background thread, you should not block the main thread while invoking it. Seems like there is no option to get the AdId synchronously.
---- EDIT----
I could achieve this by running on a new thread. Here is what finally work for me. It is not hanging anymore (May not be an ideal)
getGAIDSync(){
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable() {
#Override
public void run() {
getGoogleAdsIDAsyncTask.execute().get(5000, TimeUnit.MilliSecond);
latch.countDown();
}}).start();
try {
latch.await(5000,TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
import android.widget.Toast;
public class Security extends MainActivity {
Socket sock,sock1;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.security);
new Thread(new Runnable()
{
public void run()
{
try{
sock=new Socket(ip,port1);
BufferedReader br=new BufferedReader(new InputStreamReader(sock.getInputStream()));
String a=br.readLine();
Thread.sleep(2500);
Toast.makeText(getApplicationContext(),"Please Enter the result of operation for no "+a,Toast.LENGTH_LONG).show();
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
}
}
Not able to view toast when Security started. I dont know why? it is like that it should be wit in oncliklistener.?
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Please Enter the result of operation for no "+a,Toast.LENGTH_LONG).show();
}
});
You can only show toasts in the main UI thread.
If you need to do things on the UI thread from a background thread, have a look at runOnUiThread().
I have a BroadcastReceiver.
There I create a new Thread.
How can I show a toast in that thread?
Thanks
Use below code for perform UI operation from non-UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Try This code
public void start_insert() {
pDialog.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
// Do Something in Background
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
handler22.sendMessage(handler22.obtainMessage(what));
}
}.start();
}
private Handler handler22 = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "SuccessFull",
10).show();
}
};
Activity_Name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Use this code to update UI thread or execute any UI related operation.
I have this code in android. But when the Thread begging the loading in freezing. How can I prevent this freezing happens. Here is the code related the issue:
private void reload(final String criteria) {
try {
myProgressDialog = ProgressDialog.show(myfiles.this,
"Please wait...", "Loading Your Photos... Please Wait",
false);
new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// Fetch the fact
try {
/* here my code */
} catch (Exception e) {
myProgressDialog.dismiss();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Dismiss the Dialog
myProgressDialog.dismiss();
}
}.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It would be great if someone can check
By using runOnUiThread you are doing your intensive load task on the UI thread which will freeze the UI. You want to run your task in a background thread, and then on task completion update the ui.
Thread task = new Thread(new Runnable() {
void run() {
//load some data.
// notify UI thread using Handler
}
});
task.start();