Error message having no message . and data is not being updated - java

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");
}
}
}

Related

Race condition with UI thread issue.

This is the code i am working on. Here I cant update the UI until myOnResponse is finished.Because we are doing a doInBackgrnd, so my textresponse is empty. And Since onPostExecute is happening right after.
For his I think PublicProgres should help.
How to Call PublishProgress at AsyncTask ?
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
action5(textResponse);
System.out.println(textResponse);
}
#Override
public void onFailure(Exception e) {
}
});
return textResponse;
}#Override protected void onPostExecute(String result) {
reply.setText(textResponse);
}
}
Please help.
I don't think that you have to use AsyncTask.
You can do something like this :
YourTask.java
public class YourTask implements Runnable {
private Handler handler;
private TextView textView;
public YourTask(TextView textView){
this.textView = textView;
handler = new Handler();
}
#Override
public void run() {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
#Override
public void run() {
if(textView != null){
textView.setText(textResponse);
}
}
});
}
#Override
public void onFailure(Exception e) {
}
});
}
}
And now how to use it :
SomeActivity.java
...
textView = (TextView) findViewById(R.id.textView);
...
Thread thread = new Thread(new YourTask(textView));
thread.start();
...
Nevertheless if you want to do this action in Asynktask just try this
private class ConversationTask extends AsyncTask<String, Void, Void> {
private Handler handler;
public ConversationTask(){
handler = new Handler();
}
#Override
protected Void doInBackground(String... params) {
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
GLS_service.message("xxxxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
final String textResponse = response.getText().get(0);
handler.post(new Runnable() {
#Override
public void run() {
if(reply != null){
reply.setText(textResponse);
}
}
});
}
#Override
public void onFailure(Exception e) {
}
});
return null;
}
}
Hope it helps

how to change AsyncTask to #background and #UiThread

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);
}

Make two Views visible simultaneously in Android

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.

Asynctask w/ ProgressDialog

I know that have a lot of answers about this, but I can't find exactly what I need:
1) When users click on the button, shows a progress Dialog;
2) Executes a class AsyncTask and wait for the answer (it's a response using HTTPUrlConnection);
3) Dismiss Progress Dialog;
I tried a lot of things, but the progress dialog is not "appearing". My code:
public class MainActivity extends Activity implements OnTaskCompleted{
..
private ProgressDialog progressDialog;
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Scanning Please Wait", true);
try {
String param1 = "testParam1";
String param2 = "testParam2";
String response = new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2).get(); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public void onTaskCompleted()
{
progressDialog.dismiss();
}
public class SyncHelper extends AsyncTask<Object, Void, String>
{
..
private OnTaskCompleted listener;
..
protected String doInBackground(Object... url) {
String response = "";
try {
response = getRequest((String) url[0],(String) url[1], (String) url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPreExecute() {
}
protected void onPostExecute(String result) {
listener.onTaskCompleted();
}
}
public interface OnTaskCompleted{
void onTaskCompleted();
}
public class MainActivity extends Activity{
..
private Button btnLogin;
..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String param1 = "testParam1";
String param2 = "testParam2";
new SyncHelper(MainActivity.this).execute("http://server.example.com/api", param1, param2); //this way, my activity waits of the answer
Log.d(TAG, "Finished: " + response);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
});
}
public class SyncHelper extends AsyncTask<String, Void, String>
{
..
Context context;
private ProgressDialog pd;
..
public SyncHelper (Context c)
{
context = c;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
protected String doInBackground(String... url) {
String response = "";
try {
response = getRequest(url[0], url[1], url[2]); //Here I make a HttpURLConnection
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result) {
// here you will be getting the response in String result.
if (pd.isShowing())
pd.dismiss();
}
}
When you are using get, using AsyncTask doesn't make any sense. Because get() will block the UI Thread, maybe thats why are not able to see the progress dialog. If you want to send the response back to the MainActivity then use the callback interface as you were using beofre.

Make Online Radio app faster in streaming

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?

Categories

Resources