So I have two methods. The intent works as a "Night mode" filter for screen. It is called out when button is pressed in 1 method. But I can't figure out how can I finish the intent under the other method when the off button is clicked. Any help is appriciated! I wanna finish the overlay intent which acts as a filter under the "turnNightOff" method.
Heres the code:
private void turnNightOn() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonbutton);
Intent filter = new Intent(this,NightmodeFilter.class);
startActivity(filter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void turnNightOff() {
try {
modeOnOffButton.setImageResource(R.drawable.nightmodeonoffbutton);
} catch (Exception e) {
e.printStackTrace();
}
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
I am working on a project to control lights using arduino + ethernet shield + android app. I am using android studio for app development purpose. The issue is, try-catch block has been implemented inside the OnClickListener() which doesnt seem to work. I am new to android app development and cant think of a solution for the same. The app does get installed but the buttons do not perform their function. i.e. the server doesnt receive any package. Actually, initially the targetSdkVersion was set to 8, hence the holo theme and the buttons worked properly. Once i set it to 22 (lollipop) the material theme gets applied by default and the buttons no longer work. Thanking you in advance.
public void led(String s) throws Exception
{
byte[] b=(s.getBytes());
if(isOnline())
{
serverHostname1 = new String ("192.168.1.177");
ip = InetAddress.getByName(serverHostname1);
d1 = new DatagramSocket();//}
try{
send = new DatagramPacket(b,b.length, ip, 8032);
}catch(Exception e){
}
d1.send(send);
d1.setSoTimeout(10000);
d1.receive(rec);
modifiedSentence = new String(rec.getData());
InetAddress returnIPAddress = rec.getAddress();
Toast.makeText(getApplicationContext(),"Reply from Server:"+returnIPAddress,Toast.LENGTH_LONG).show();
d1.close();
}
else
{
Toast.makeText(getApplicationContext(),"No network",Toast.LENGTH_LONG).show();
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button on= (Button)findViewById(R.id.on);
Button off= (Button)findViewById(R.id.off);
on.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
//ArduinoActivity a=new ArduinoActivity();
led("1");
Toast.makeText(getApplicationContext(),"ON",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Error::"+e);
}
}
});
off.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
//ArduinoActivity b=new ArduinoActivity();
led("2");
Toast.makeText(getApplicationContext(), "OFF",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
//TODO Auto-generated catch block
System.out.println("Error::"+e);
}
}
});
}
}
The issue was not with the try-catch block but the networking operations being carried out inside UI thread (sending of packet) which is not allowed in android versions 3.0+ . The solution is to make use of Asynctask for the same. Thank you :)
I'm using a thread to set an image as background and in this thread i have a dialog. The dialog starts and should be close when the wallpaper will be set. This is the code so far
setWallbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog myPd_ring=ProgressDialog.show(SingleWall.this, "Setting wallpaper", "", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
WallpaperManager wallManager = WallpaperManager.getInstance(getApplicationContext());
try {
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
wallManager.setBitmap(image);
Toast.makeText(SingleWall.this, "Wallpaper Set Successfully!!", Toast.LENGTH_SHORT).show();
myPd_ring.dismiss();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(SingleWall.this, "Setting WallPaper Failed!!", Toast.LENGTH_SHORT).show();
myPd_ring.dismiss();
}
}
}, 4000);
}
});
So, on click in a button starts the thread and for 4 seconds the dialog should be visible with the progress icon. But it is not correct! the time to set the background could be more or less than 4 seconds! So the 4000 should be calculates in base of the time to set the image as wallpaper. Is it possible?
ps. I can't use a AsyncTask because i get many NullPointerExceptions
Note that you are not using a separate Thread with the code in your question, you are running a Runnable on the main UI thread.
If you look at the documentation, it's recommended to use an AsyncTask for decoding Bitmaps, and it's also the best way to achieve your desired result, where the ProgressDialog is dismissed only after the process is complete, which can take an unpredictable amount of time.
You just need to put the code in it's correct place, and give it what it needs through the varargs passed in.
Here is how you should start the AsyncTask:
setWallbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoadImage().execute(url);
}
});
Then, create the AsyncTask as a sub-class of the SingleWall Activity.
Put the network code in doInBackground() which will download and decode the Bitmap, and then put the UI related code in onPostExecute(), which runs on the UI thread.
Note that you can also use a WeakReference to the WallpaperManager instance, as outlined in the link above, but I'll keep it simple here and just access wallManager directly, which you can do if the AsyncTask is a sub-class of your Activity.
class LoadImage extends AsyncTask<URL, Void, Bitmap> {
ProgressDialog myPd_ring;
#Override
protected void onPreExecute() {
//Start Progress Dialog here
myPd_ring = ProgressDialog.show(SingleWall.this, "Setting wallpaper", "", true);
}
//Runs in a background Thread
#Override
protected Bitmap doInBackground(URL... params) {
URL url = params[0];
Bitmap image = null;
try {
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
//Runs on the UI Thread
#Override
protected void onPostExecute(Bitmap image) {
myPd_ring.dismiss();
if (image == null){
Toast.makeText(SingleWall.this, "Setting WallPaper Failed!!", Toast.LENGTH_LONG).show();
}
else{
//set image here
try {
SingleWall.this.wallManager.setBitmap(image);
Toast.makeText(SingleWall.this, "Wallpaper Set Successfully!!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(SingleWall.this, "Setting WallPaper Failed!!", Toast.LENGTH_LONG).show();
}
}
}
}
Use the AsyncTask, the null pointers are probably coming because you are trying to update the UI during the task's processing. You might need to use something like this from inside the AsyncTask:
activity.runOnUiThread(new Runnable() {
public void run() {
activity.doSomeSpecialUIWork();
}
});
}
Hope that works - that's what solved it for me when I was getting strange null pointers during an AsyncTask.
Here's an example from another post: how to use runOnUiThread
For your specific code, maybe this:
setWallbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
activity.runOnUiThread(new Runnable() {
public void run() {
final ProgressDialog myPd_ring=ProgressDialog.show(SingleWall.this, "Setting wallpaper", "", true);
// TODO Auto-generated method stub
WallpaperManager wallManager = WallpaperManager.getInstance(getApplicationContext());
try {
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
wallManager.setBitmap(image);
Toast.makeText(SingleWall.this, "Wallpaper Set Successfully!!", Toast.LENGTH_SHORT).show();
myPd_ring.dismiss();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(SingleWall.this, "Setting WallPaper Failed!!", Toast.LENGTH_SHORT).show();
myPd_ring.dismiss();
}
}
});
}
}
});
I am new one in android development. I have a mp3 audio player code which play mp3 from url. I want to show loading dialog box when media player is buffering on prepare
Here is my Code I show a dialog on prepare but it continuous run and cannot play mp3.
I have no idea where i define smp.setOnPreparedListener. Please tell me that can i define this in play function or outside play function. Please Help Me here is my code. Thanks in Advance please
//Play MP3 Function
public void playSong(int naatindex){
// Play song
try {
mp.reset();
mp.setDataSource(naatpaths[naatindex]);
tv = (TextView) this.findViewById(R.id.mywidget);
tv.setSelected(true); // Set focus to the textview
tv.setText(naattitles[naatindex]);
mp.prepare();
mp.start();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and here is my mp.setOnPreparedListener code
ProgressDialog progressDialog = ProgressDialog.show(this,
"Loading Title", "Loading Message");
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss();
}
mp.start();
}
});
In playSong(), you call :
mp.prepare();
mp.start();
If you directly start the player it would crash because it may be not ready to play. Try this:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(naatpaths[naatindex]);
mp.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
});
mp.prepareAsync(); //this will prepare file a.k.a buffering
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
If it still fails to play, check the stream url. It might be dead. Also try logging the state of the player. Check the stacktrace for any exceptions too.
I have searching for days to resolved my issue..
I want my apk to call a number when i click on a button and while calling (after few seconds)I want my app to add automatically another number(like if we open keyboard of the default dialer view and type a number manually)..
Exemple : when I have a call card to call another country, We have to put some specific number to continue ( put 1 to call to France, put 2 to call to Italia...etc )I want to put AUTOMATICALLY number few seconds after the first ring !
There is my code for now :
public void onClick(View v) {
switch (v.getId()) {
case R.id.num5: // When I click on this button
Intent localIntent5 = new Intent(Intent.ACTION_CALL);
localIntent5.setData(Uri.parse("tel:0153204255"));
startActivity(localIntent5);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent localIntent6= new Intent(Intent.ACTION_CALL);
localIntent6.setData(Uri.parse("tel:71-0609472130%23"));
startActivity(localIntent6);
break;
}
}
Thanks for help..
please help me I'm looking for a days !
Use this code on button Click:-
num5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent localIntent5 = new Intent(Intent.ACTION_CALL);
localIntent5.setData(Uri.parse("tel:*****"));
startActivity(localIntent5);
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent localIntent6= new Intent(Intent.ACTION_CALL);
localIntent6.setData(Uri.parse("tel:*******"));
startActivity(localIntent6);
}
});