Android Activity Asynctask error - android

I have an application with two activies. First one is reading serial data from arduino using asynctask. When button is clicked on first activity it should start second activity. But when I click that button it's going to android launcher everytime. Meanwhile second activity also opened in background.
I don't understand why android launcher is opening but not showing second activity on screen.
Any suggestions? Thanks.
private class AdkReadTask extends AsyncTask<Void, String, Void> {
public void pause() {
degisken = false;
}
#Override
protected Void doInBackground(Void... arg0) {
while (degisken) {
publishProgress(mAdkManager.readSerial());
SystemClock.sleep(50);
}
return null;
}
protected void onProgressUpdate(String... progress) {
kapak2 = (int) progress[0].charAt(2);
kapak1 = (int) progress[0].charAt(1);
limit = (int) progress[0].charAt(0);
tx5.setText("kapak1 : " + (int) progress[0].charAt(1)
+ " kapak2 : " + (int) progress[0].charAt(2) + " limit : "
+ (int) progress[0].charAt(0));
}
}
public void butonClick(View v) {
Intent intent = new Intent(UDOOBlinkLEDActivity.this,
shortcuts.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("dil", dil);
startActivity(intent);
}

Change this.
Intent intent = new Intent(UDOOBlinkLEDActivity.this,
shortcuts.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(intent); remove this line
intent.putExtra("dil", dil);
startActivity(intent);
Because twice you are calling startActivity(intent); and after that you are sending data and again startActivity. So problem occurs.

Related

How to pass a calculated variable to another activity in android studio

I want to calculate the total in the mainActivity and pass it to the second Activity using explicit intent,
i tried this way but id doesn't work, i want to know how to pass the calculated total to the secondActivity
and this is the code:
TextView result_total_Last;
public void calculateTotal(View view) {
EditText number = findViewById(R.id.number_user);
int num = Integer.parseInt(number.getText().toString());
String result_total;
if (radio_days.isChecked()) {
result_total = (""+ (num * 50) );
} else {
result_total = (""+ (num * 1000) );
}
result_total_Last.setText("the total is" + result_total);
}
// and this is the on click method that used to pass to second activity
book_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ValidateEmailAddress(email)) {
//create intent to pass the values//
String result_intent = result_total_Last.getText().toString();
Intent intent = new Intent(MainActivity.this, Confirmation_interface.class);
intent.putExtra("total", result_intent);
startActivity(intent);
}
}
});
//code of second activity
Intent intent = getIntent();
String total = intent.getStringExtra("total");
TextView Total_result = findViewById(R.id.Total_ET);
Total_result.setText(total);
}
}
Try receiving like this
String total = getIntent().getExtras().getString("total","defaultIfNotPassed");

Setting a timeout and finishing an ActivityforResult activity

I'd like to know if there's some way to set a timeout for an Intent started via startActivityForResult, so when the time is passed some actions can be performed with the activity of the mentioned intent (in my case finishing it).
There doesn't seem to be any direct way to set a timeout directly to the Intent, but this doesn't look too much to worry about, as I guess I could create a CountDownTimer that in onFinish() would call the code to finish the intent.
Problem is I don't see a way to finish that ActivityForResult.
Is there any way to do this?
Well, I finally got to solve the problem, indeed it wasn't very difficult.
For my particular case of INTENT_PICK the following code is valid to stop the activity after 2 minutes:
final int RQS_PICKCONTACT = 1;
[...]
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
mcd = new CountDownTimer(120000, 10000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try
{
finishActivity(RQS_PICKCONTACT);
}
catch (Exception ex)
{
}
}
}.start();
In my case I wanted to limit the time a user was doing a task so I created my own timer class.
public class Timer {
private static final String TAG = "Timer" ;
int timeout;
Context mContext;
boolean compleatedTask;
String timeoutKey;
CountDownTimer countDown;
public Timer(Context mContext, int timeout, String timeoutKey){
this.timeout = timeout;
this.mContext = mContext;
this.timeoutKey = timeoutKey;
}
public void startTimer() {
this.countDown = new CountDownTimer(this.timeout, 1000) {
public void onTick(long millisUntilFinished) {
Log.i(TAG, "OnTick, context: " + mContext + ", milisUntilFinished: " + millisUntilFinished + ", compleatedTask: " + compleatedTask);
if(compleatedTask)
cancel();
}
public void onFinish() {
Log.i(TAG, "OnFinish, context: " + mContext + ", compleatedTask: " + compleatedTask);
try
{
if(!compleatedTask){
Intent intent = new Intent(mContext, UnsuccessfullPosTaskActivity.class);
intent.putExtra("error", StateMachine.databaseAccess.getDictionaryTranslation(timeoutKey, StateMachine.language));
mContext.startActivity(intent);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
};
countDown.start();
}
public void setCompleatedTask(boolean compleatedTask){
this.compleatedTask = compleatedTask;
if(compleatedTask)
countDown.onFinish();
}
}
Then in your activity
int timeout = 1000;
Timer timer = new Timer(Activity.this, timeout);
timer.startTimer();
//do stuff
if(conditionToStop)
timer.setCompleatedTask(true);
And if you are using recycle views and you want to stop the counter when they click an option just send the timer object to your custom recycle view adapter.

how to work with on onResume() in Android?

I have 2 activities .First time I run the application I have to open the popup in Activity 1 when I first to start the application. After that I want to go activity 2 and make some changes there. Again i come back to Activity 2 and i don't want to open the popup. But the problem is whenever i comeback to 1st Activity the popup is open.How to solve this issues?
Here is my code.
db = dbhelper.getReadableDatabase();
String query = "SELECT * FROM Inspector where ActiveStatus= '1' AND FollowFlag ='1'";
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst())
{
do
{
String strInspectoreName = cursor.getString(cursor.getColumnIndex("Inspector_name"));
String strInspectorId = cursor.getString(cursor.getColumnIndex("Inspector_Id"));
if(!strInspectorId.equals(str_LoginUserId))
{
inspector_ArrayList.add(strInspectoreName);
Log.e("Post ", " Total FollowUp Users !!!" + strInspectoreName);
}
} while (cursor.moveToNext());
}
cursor.close();
db.close();
int countFollowUp = inspector_ArrayList.size();
Log.e("Post ", " Total countFollowUp Users !!!" + countFollowUp);
if( countFollowUp == 0)
{
final Dialog dialog = new Dialog(CustomActionActivity.this);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
dialog.setContentView(R.layout.custom_dialog_layout);
Button followStart = (Button) dialog.findViewById(R.id.button_FollowStart);
followStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(CustomActionActivity.this, Filter_Screen.class);
startActivity(i);
}
});
Button dismissButton = (Button) dialog.findViewById(R.id.button_Dissmiss);
dismissButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
Here is my onResume() in Activity 1st
#Override
protected void onResume()
{
super.onResume();
Log.e(" Activity ", " Resume !!! ");
Log.e("From ", " Filter 222");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
booleanValue_one = sharedPreferences.getBoolean("LISTVIEW_EVENT_ONE", false);
booleanValue_two = sharedPreferences.getBoolean("LISTVIEW_EVENT_TWO", false);
Log.e("", "booleanValue_one=" + booleanValue_one + " booleanValue_two=" + booleanValue_two);
if (booleanValue_one == true || booleanValue_two == true)
{
GetAllActivityDetails task = new GetAllActivityDetails();
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Log.e(" booleanValue_one "," = " + booleanValue_one +" After completing async task !!!!");
updatedDownLoadStatus();
}
if (booleanValue_one == false && booleanValue_two == false)
{
populateList();
}
}
Here is my 2nd activity onBackPressed() -> go to 1st Activity
#Override
public void onBackPressed() {
super.onBackPressed();
Intent a = new Intent(Filter_Screen.this, CustomActionActivity.class);
a.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(a);
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
}
Make A boolean Key boolean key=true; and use that boolean key to display the Popup in onResume() and in onCreate() make that boolean false
onResume() also call when activity start and when you come back it call again
Your onResume() is called everytime you go back to the running activity and also the first time you create the activity thats why it wil run the code evrytime you go back to the activity.
To resolve this problem you should put the code from your onResume in your onCreate that way it only runs when the activity is first created.
For more info and to fully understand the lifecycle of an activity check : http://developer.android.com/training/basics/activity-lifecycle/starting.html#lifecycle-states
It this is a fist time running thing like an introduction of collect some user information, Save the state to shared preferences and use that to check and allow or disallow the pop-ups accordingly.

Dont open second activity if android back button is pressed

i am trying to implement below code every thing works fine how ever
here is the situation i am facing
mainactivity just has a button to open splashactivity
splash activity does the parsing part then opens the listactvity
my workflow is if user has clicked on the button in main activity
it opens the splash activity and redirects to listactivty the
problem occurs when on the splash activity if a user clicks the
andorid back button it does go back to the mainactivity however the
parsing in splashactivity continues and user is redirected to
listactivty this thing should not happen, when user on splash
activity has clicked backbutton it should go back to mainactivity
and stay there itself
how can this be done
package com.site.name;
public class SplashActivity extends Activity {
RSSFeed feed;
String fileName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
// //public String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity!",
Toast.LENGTH_LONG);
toast.show();
//feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//feed = myParser.parseXml(RSSFEEDURL);
//feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss");
feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
//Include the code here
return;
}
}
You can cancel parsing the feed in MainActivity's onRestart() as this is one method of MainActivity that will be called when you press back from your Parsing Activity.
You can read more about Activity Life Cycle here.
For detecting the Back button press event use the following method
#Override
public void onBackPressed() {
// do something on back.
// Change your activity by calling intent
return;
}
If you want to do anything with your back button then you have to override it manually.
#Override
Public void onBackPressed() {
//do whatever you want to do as your question is quite confusing.
return;
}

IntentService runs through a list, which can be reordered concurrently via onHandleIntent

I am using IntentService to download 200 large JPGs from a list. While this is loading, the user can skip through the not-loaded JPGs and load JPG #156 for example, but after it is loaded, it should continue loading the rest. So it's like a Lazy Loader... but it continues when it's idle.
I previously used onHandleIntent and put a loop from #1 to #200... which obviously doesn't work when I try to send another IntentService call for JPG #156. So the call to #156 only happens after onHandleIntent is done with #200.
I then changed it so onHandleIntent reorders request #156 to be at the top of the list, then requests the top of the list (and downloads the JPG), then removes it from the list. It then calls the IntentService again, which sounds rather risky from a recursive/stack overflow kinda way. It works sometimes and I can see file #156 being put first... sometimes.
Is there a better way to do this? A way I could think of would be to run it all through a database.
EDIT: This is what I have come up with:
code
public class PBQDownloader extends IntentService {
int currentWeight = 0;
PriorityBlockingQueue<WeightedAsset> pbQueue = new PriorityBlockingQueue<WeightedAsset>(100, new CompareWeightedAsset());
public PBQDownloader() {
super("PBQDownloader");
}
public PBQDownloader(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
String downloadUrl = "-NULL-";
Bundle extras = intent.getExtras();
if (extras!=null) {
downloadUrl = extras.getString("url");
Log.d("onHandleIntent 1.1", "asked to download: " + downloadUrl);
} else {
Log.d("onHandleIntent 1.2", "no URL sent so let's start queueing everything");
int MAX = 10;
for (int i = 1; i <= MAX; i++) {
// should read URLs from list
WeightedAsset waToAdd = new WeightedAsset("url: " + i, MAX - i);
if (pbQueue.contains(waToAdd)) {
Log.d("onStartCommand 1", downloadUrl + " already exists, so we are removing it and adding it back with a new priority");
pbQueue.remove(waToAdd);
}
pbQueue.put(waToAdd);
}
currentWeight = MAX + 1;
}
while (!pbQueue.isEmpty()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
WeightedAsset waToProcess = pbQueue.poll();
Log.d("onHandleIntent 2 DOWNLOADED", waToProcess.url);
}
Log.d("onHandleIntent 99", "finished all IntentService calls");
}
#Override
public int onStartCommand(Intent intent, int a, int b) {
super.onStartCommand(intent, a, b);
currentWeight++;
String downloadUrl = "-NULL-";
Bundle extras = intent.getExtras();
if (extras!=null) downloadUrl = extras.getString("url");
Log.d("onStartCommand 0", "download: " + downloadUrl + " with current weight: " + currentWeight);
WeightedAsset waToAdd = new WeightedAsset(downloadUrl, currentWeight);
if (pbQueue.contains(waToAdd)) {
Log.d("onStartCommand 1", downloadUrl + " already exists, so we are removing it and adding it back with a new priority");
pbQueue.remove(waToAdd);
}
pbQueue.put(waToAdd);
return 0;
}
private class CompareWeightedAsset implements Comparator<WeightedAsset> {
#Override
public int compare(WeightedAsset a, WeightedAsset b) {
if (a.weight < b.weight) return 1;
if (a.weight > b.weight) return -1;
return 0;
}
}
private class WeightedAsset {
String url;
int weight;
public WeightedAsset(String u, int w) {
url = u;
weight = w;
}
}
}
code
Then I have this Activity:
code
public class HelloPBQ extends Activity {
int sCount = 10;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button tv01 = (Button) findViewById(R.id.tv01);
Button tv02 = (Button) findViewById(R.id.tv02);
Button tv03 = (Button) findViewById(R.id.tv03);
tv01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doPBQ();
}
});
tv02.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doInitPBQ();
}
});
tv03.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sCount = 0;
}
});
}
private void doInitPBQ() {
Intent intent = new Intent(getApplicationContext(), PBQDownloader.class);
//intent.putExtra("url", "url: " + sCount);
startService(intent);
}
private void doPBQ() {
sCount++;
Intent intent = new Intent(getApplicationContext(), PBQDownloader.class);
intent.putExtra("url", "url: " + sCount);
startService(intent);
}
}
code
Now the messy bit is that I have to keep an ever-increasing counter that runs the risk of going out of int bounds (WeightedAsset.weight) - is there a way to programmatically add to the queue and have it automatically be the head of the queue? I tried to replace WeightedAsset with a String, but it didn't poll() as I wanted, as a FIFO instead of a LIFO stack.
Here's how I'd try it first:
Step #1: Have the IntentService hold onto a PriorityBlockingQueue.
Step #2: Have onHandleIntent() iterate over the PriorityBlockingQueue, downloading each file in turn as it gets popped off the queue.
Step #3: Have onStartCommand() see if the command is the "kick off all downloads" command (in which case, chain to the superclass). If, instead, it's the "prioritize this download" command, re-prioritize that entry in the PriorityBlockingQueue, so it'll be picked up next by onHandleIntent() when the current download is finishing.

Categories

Resources