Can anyone help me a bit to change AsyncTask to #Background and #UiThread?
How should I start? What should I delete?
onPost and onPre should be converted to UiThread?
I will be very grateful for advice
Here is piece of my code.
#Click
void button1(View view)
{
ReadPic rp = new ReadPic();
rp.execute();
}
class ReadPic extends AsyncTask<Void, Void, Void>
{
ProgressBar progressBar;
boolean sukces = true;
public ReadPic()
{
progressBar = new ProgressBar(getBaseContext());
}
#Override
protected Void doInBackground(Void... arg0)
{
URL u;
InputStream is;
try
{
u = new URL( adres);
is = u.openStream();
Bitmap temp = BitmapFactory.decodeStream(is);
bmp=temp.copy(Bitmap.Config.ARGB_8888, true);
}
catch( Exception e)
{
sukces = false;
}
return null;
}
#Override
protected void onPreExecute()
{
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.INVISIBLE);
textView1.setText("DOWNLOADING...");
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result)
{
if(sukces)
{
imageView.setImageBitmap(bmp);
imageView1.setImageBitmap(bmp);
imageView2.setImageBitmap(bmp);
imageView3.setImageBitmap(bmp);
imageView4.setImageBitmap(bmp);
imageView5.setImageBitmap(bmp);
imageView6.setImageBitmap(bmp);
imageView7.setImageBitmap(bmp);
imageView8.setImageBitmap(bmp);
textView1.setText("Downloading finished");
}
else
{
textView1.setText("Error when downloading");
}
button1.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
super.onPostExecute(result);
}
You can convert it like this:
#Click
void button1(View view) {
startProcess();
}
void startProcess() {
if(progressBar !=null) // progressBar should be a field in your Activity / Fragment
progressBar.setVisibility(ProgressBar.VISIBLE);
button1.setEnabled(false);
if(progressBar !=null)
progressBar.setVisibility(ProgressBar.INVISIBLE);
textView1.setText("DOWNLOADING...");
yourBackgroundMethod();
}
#Background
void yourBackgroundMethod() {
URL u;
InputStream is;
try
{
u = new URL( adres);
is = u.openStream();
Bitmap temp = BitmapFactory.decodeStream(is);
bmp=temp.copy(Bitmap.Config.ARGB_8888, true);
onBackgroundSuccess();
onBackgroundTerminate();
}
catch( Exception e)
{
onBackgroundError();
onBackgroundTerminate();
}
}
#UiThread
void onBackgroundError() {
imageView.setImageBitmap(bmp);
imageView1.setImageBitmap(bmp);
imageView2.setImageBitmap(bmp);
imageView3.setImageBitmap(bmp);
imageView4.setImageBitmap(bmp);
imageView5.setImageBitmap(bmp);
imageView6.setImageBitmap(bmp);
imageView7.setImageBitmap(bmp);
imageView8.setImageBitmap(bmp);
textView1.setText("Downloading finished");
}
#UiThread
void onBackgroundSuccess() {
textView1.setText("Error when downloading");
}
#UiThread
void onBackgroundTerminate() {
button1.setEnabled(true);
progressBar.setVisibility(ProgressBar.INVISIBLE);
}
Related
In the following code of my MainActivity (which downloads a json I need in another activity and shows a loading progress bar), which starts before launching HomeActivity, I get a null object reference error (on the getProgress() method), but HomeActivity then starts anyway if I press back button.
I have searched for this kind of error, but the only solution that seems working is the one that let me starts the HomeActivity after some delay, changing setProgress method like this: (but it seems that the bar doesn't change and I don't think it's a real solution to the problem)
public void setProgress(ProgressBar bar, int progress) {
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if (bar.getProgress() == 100) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}, 4000);
}
}
----------------------------------------------------------------------
package ...
import ...
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView textView;
private OkHttpClient httpClient;
private String url;
private Request request;
private static boolean loaded = false;
private FileInputStream inputStream;
private FileOutputStream outputStream;
private static final String FILE_NAME = "data.txt";
private AlertDialogConnection noResponse;
private AlertDialogConnection noInternet;
private AlertDialogConnection serverError;
private AlertDialogConnection internalError;
public MainActivity(){
this.inputStream = null;
this.outputStream = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
this.httpClient = new OkHttpClient();
this.url = "my url";
this.request = new Request.Builder().url(url).build();
this.progressBar = findViewById(R.id.progressBar);
this.progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.progressBarColor), android.graphics.PorterDuff.Mode.SRC_IN);
this.textView = findViewById(R.id.textView);
this.noResponse = new AlertDialogConnection();
this.noInternet = new AlertDialogConnection();
this.serverError = new AlertDialogConnection();
this.internalError = new AlertDialogConnection();
checkConnectionStatusAndStart();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
public void checkConnectionStatusAndStart(){
if(checkConnectionStatus())
requestData();
else{
this.noInternet.setTitle("no connection!");
this.noInternet.setText("connection error!");
this.noInternet.show(getSupportFragmentManager(), "no connection!");
}
}
public boolean checkConnectionStatus(){
boolean wifiConnection = false;
boolean mobileConnection = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null)
networkInfo = connectivityManager.getActiveNetworkInfo();
if((networkInfo != null) && networkInfo.isConnected()){
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
/* Wifi On */
wifiConnection = true;
}
if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
/* Mobile data On */
mobileConnection = true;
}
return (wifiConnection || mobileConnection);
}else{
/* You are not connected */
return false;
}
}
public void requestData(){
textView.setText("waiting server...");
httpClient.connectTimeoutMillis(); //Timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if(!call.isExecuted()){
Toast.makeText(getApplicationContext(), "server error!", Toast.LENGTH_LONG).show();
}
Log.d("HTTP-Error", "HTTP error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView)).setText("Setting of suggestion variables!");
setProgress(progressBar, 10);
try {
JSONObject json = new JSONObject(body);
try {
((TextView)findViewById(R.id.textView)).setText("retrieving server infos!");
saveJSON(json, getApplicationContext());
} catch (FileNotFoundException e) {
Log.d("File Not Found!", "FileNotFoundException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
} catch (IOException e) {
Log.d("File Not Found!", "IOException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
}
setProgress(progressBar, 90);
MainActivity.loaded = true;
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON-Error", "parsing JSON error!");
internalError.setTitle("server error!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "JSON messaging error!");
}
}
});
}else{
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error");
serverError.show(getSupportFragmentManager(), "server error!");
}
}
});
}
public void setProgress(ProgressBar bar, int progress){
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if(bar.getProgress() == 100){
Intent intent = new Intent(this, HomePage.class);
startActivity(intent);
this.onDestroy();
}
}
private void saveJSON(JSONObject json, Context context) throws IOException {
outputStream = null;
try{
outputStream = context.openFileOutput(FILE_NAME, MODE_PRIVATE);
outputStream.write(json.toString().getBytes());
}finally {
if(outputStream != null){
outputStream.close();
}
}
}
public JSONObject loadJSON(Context context) throws IOException, JSONException {
inputStream = context.openFileInput(FILE_NAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(reader.readLine());
inputStream.close();
return jsonObject;
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
this.httpClient = null;
this.noResponse = null;
this.noInternet = null;
this.serverError = null;
this.internalError = null;
this.request = null;
this.textView = null;
this.progressBar = null;
this.url = null;
super.onDestroy();
}
#Override
protected void onResume() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onResume();
}
#Override
protected void onRestart() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onRestart();
}
#Override
protected void onPause() {
if(!loaded ){
checkConnectionStatusAndStart();
}
super.onPause();
}
}
I'm trying to develop an application (Radio Stream) app, I want to get the details of the song that is playing on the radio for that MediaMetadataRetriever API but when i set my URL i get this error :
java.lang.IllegalArgumentException
at
android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:71)
at
maa.myapp.MainActivity$PlayerTask.onPostExecute(MainActivity.java:447)
at
maa.myapp.MainActivity$PlayerTask.onPostExecute(MainActivity.java:419)
this my code :
MediaPlayer mediaPlayer;
String stream = "https://plaza.one/mp3";
boolean prepared =false;
boolean started =false ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attribs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
mediaPlayer.setAudioAttributes(attribs);
} else {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
new PlayerTask().execute(stream);
}
public class PlayerTask extends AsyncTask<String,Void,Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingRL.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(strings[0]);
prepared=true;
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
/*get details : */
MediaMetadataRetriever mMediaMetaDataRetriever = new MediaMetadataRetriever();
mMediaMetaDataRetriever.setDataSource(stream,new HashMap<String, String>());
String titleName = mMediaMetaDataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
Toast.makeText(MainActivity.this, "Title : "+titleName, Toast.LENGTH_SHORT).show();
}
}
}
finally it work with 'com.vodyasov:amr:0.5' library
Uri uri = Uri.parse(stream);
OnNewMetadataListener listener = new OnNewMetadataListener() {
#Override
public void onNewHeaders(String stringUri, List<String> name, List<String> desc, List<String> br, List<String> genre, List<String> info) {}
#Override
public void onNewStreamTitle(String stringUri, String streamTitle) {
songinfo.setText("Song Name : "+streamTitle);
}
};
AudiostreamMetadataManager.getInstance()
.setUri(uri)
.setOnNewMetadataListener(listener)
.setUserAgent(UserAgent.WINDOWS_MEDIA_PLAYER)
.start();
Try this:
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14){
mmr.setDataSource(stream, new HashMap<String, String>());
}else {
mmr.setDataSource(stream);
}
String titleName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE));
Toast.makeText(MainActivity.this, "Title : "+titleName, Toast.LENGTH_SHORT).show();
}
If that doesn't work then you should make sure that the link you are using actually returns a file.
Try doing the above inside onCreate, the problem could be something with your AsyncTask.
When executing the below code I get the following in my log
05-02 02:19:34.175 8796-8810/com.example.nitikamehta.testing
I/System.out: io.cloudboost.CloudException
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CloudApp.init("vuwzaiqgwytr ", "cf358f99-1bbd-4ccc-9a4e-3370b169a50f");
myAsyncTask mTask = new myAsyncTask();
mTask.execute("abc", "10", "Hello world");
}
private class myAsyncTask extends AsyncTask<String, Integer, String> {
String mTAG = "myAsyncTask";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg) {
CloudObject obj = new CloudObject("users");
try {
obj.set("name", "navneet");
Log.d("here", "also");
} catch (CloudException e) {
e.printStackTrace();
}
try {
obj.save(new CloudObjectCallback() {
#Override
public void done(CloudObject x,CloudException t) {
if (x != null) {
Log.d("first", "added");
}
if (t != null) {
System.out.println(""+t);
}
}
}
);
} catch (CloudException e) {
Log.d("hello", "world");
}
return "done";
}
#Override
protected void onPostExecute(String result) {
Log.d(mTAG, "Inside onPostExecute");
}
}
}
I have this code in my Android application:
private void showMyViews() {
mAnimation.cancel();
mAnimation.reset();
mAnimateionView.clearAnimation();
mAnimationView.setVisibility(View.GONE);
mOtherViewToHide.setVisibility(View.GONE);
mFirstViewToShow.setVisibility(View.VISIBLE);
mSecondViewToShow.setVisibility(View.VISIBLE);
}
But sometimes mSecondViewToShow appears a little bit before mFirstViewToShow. How could I easily force these Views to appear at the same time?
Some of the code is:
public class mFragment extends Fragment implements OnClickListener, com.squareup.picasso.Callback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mFragment, null);
mFirstViewToShow = (RelativeLayout) view
.findViewById(R.id.mFirstViewToShow);
mSecondViewToShow = (RelativeLayout) view
.findViewById(R.id.mSecondViewToShow);
...
...
...
if (isConnected()) {
animateMagnifier();
updateUserLocation();
} else {
}
}
private void animateMagnifier() {
Thread mThread = new Thread(new Runnable() {
#Override
public void run() {
AppLog.Log(TAG, "ver si la lupa sirve");
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mAnimationView.setVisibility(View.VISIBLE);
animeMagnifier = AnimationUtils
.loadAnimation(getActivity(),
R.anim.translate_center_amim);
mAnimationView.startAnimation(animeMagnifier);
// Code use to repeat the animation
// See
// http://stackoverflow.com/questions/4480652/android-animation-does-not-repeat
animeMagnifier
.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(
Animation animation) {
}
#Override
public void onAnimationRepeat(
Animation animation) {
}
#Override
public void onAnimationEnd(
Animation animation) {
animeMagnifier = AnimationUtils
.loadAnimation(
getActivity(),
R.anim.translate_center_amim);
animeMagnifier
.setAnimationListener(this);
mAnimationView
.startAnimation(animeMagnifier);
}
});
}
});
}
}
});
mThread.start();
try {
mThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void updateUserLocation() {
...
...
...
sendDataToServer();
}
private void sendDataToServer() {
...
...
...
findPerson();
}
private void findPerson() {
new BackGroundTaskForFindPerson().execute();
}
private class BackGroundTaskForFindMatch extends
AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
findPeopleResponse = mServices.makeHttpRequest(
Constant.find_people, Constant.methodeName,
findPeopleValuePairList);
Gson gson = new Gson();
...
...
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
if (success) {
if (mFindPeople.getErrNum() == 2) {
// no one found
mFirstViewToShow.setVisibility(View.GONE);
mSecondViewToShow.setVisibility(View.GONE);
messageTextView.setText(R.string.no_one_near);
} else if (mFindPeople.getErrNum == 3) {
...
} else {
....
}
} else {
messageTextView.setText(R.string.no_one_new);
}
} catch (Exception e) {
....
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Set them to INVISIBLE instead of GONE that way they will be attached to your layout but hidden.
At the moment they must be added to your view hierarchy before they are revealed, that's probably what's causing your delay.
Hello i have make one radio app in that streaming is done from web
my source code is
when user click on button following code will be executed
if (!NotifyService.iSserviceRunning) {
new PlayRadio().execute("");
}
// AYSNC class for start Service and create progressbar
class PlayRadio extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return "";
}
#Override
protected void onPostExecute(String result) {
try {
startService(new Intent(RadioActivity.this, NotifyService.class));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = ProgressDialog.show(RadioActivity.this, "Tuning...", "Please Wait...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Now service class will be
public class NotifyService extends Service {
private static String RADIO_STATION_URL;
public static MediaPlayer player;
public static boolean iSserviceRunning = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
RADIO_STATION_URL = getResources().getString(R.string.streamurl);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
initializeMediaPlayer();
startPlaying();
iSserviceRunning = true;
}
#Override
public void onDestroy() {
super.onDestroy();
nm.cancel(R.string.service_started);
stopPlaying();
initializeMediaPlayer();
iSserviceRunning = false;
}
private void startPlaying() {
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
new PrepareTask().execute();
}
private void stopPlaying() {
if (player.isPlaying()) {
player.pause();
player.release();
}
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class PrepareTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(Integer result) {
if(RadioActivity.PD!=null){
if(RadioActivity.PD.isShowing()){
RadioActivity.PD.dismiss();
}
}
}
#Override
protected Integer doInBackground(Integer... arg0) {
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
is there any wrong i am doing becuase my client said that application is taking tooo much time for loading.. he told me that he has many such application which is loading fastly then my app
can any body suggest me is any wrong i have done in my code so it's taking much time?