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.
Related
I used this method, it works when data is in database, and it's not working when database is empty.
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(String.valueOf(dataBase), null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
Intent i = new Intent(getApplicationContext(), Next.class);
startActivity(i);
}
return checkDB != null;
}
I am new to Android development, this is my first android application.
The application contains three Activities(splashscreen, login, main_activity).
My question is:
How to launch MAIN_ACTIVITY if database contains value(login value), if not launch Login activity?
What is the condition?
Where do I use it?
use this method to query your database.
public boolean login(String username, String password) throws SQLException {
Cursor mCursor = db.rawQuery(
"SELECT * FROM YOUR_TABLE WHERE USERNAME=? AND PASSWORD=?",
new String[] { username, password });
if (mCursor != null) {
if (mCursor.getCount() > 0) {
return true;
}
}
return false;
}
I suggest that you do not use the SQLite database to store the login value. If you want to store the login value rather use Shared Preferences. You can read up about the Shared Preferences here.
SplashScreen.java
public class SplashScreen extends Activity {
private final int SPLASH_TIME_OUT = 3000; // Splash screen timer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen_layout);
// This method call delays the execution of the activity
// by 3 seconds (3000 milliseconds)
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
Intent intent;
SharedPreferences sharedPrefs = getSharedPreferences("LOGINPREFS", 0);
/* Checks if the user has ever logged in
* If not, a login screen is displayed.
* LOGGED_IN would be the name of the shared preference key,
* which would have been set on the login activity,
* only if the login is successful
*/
if (sharedPrefs.contains("LOGGED_IN")) {
intent = new Intent(SplashScreen.this, MainActivity.class);
intent.putExtra("student", student);
} else {
intent = new Intent(SplashScreen.this, LoginActivity.class);
}
startActivity(intent); // Starts a new activity
finish(); // Close this activity
}
}, SPLASH_TIME_OUT);
}
#Override
public void onBackPressed() {
} // Disables the back button
}
I have three activites A,B and C,now what i am doing is,From Activity A i am sending one data to B
Activity B
Intent intent=getIntent();
userids= intent.getStringExtra("userid");
System.out.println("USERID BC"+userids);
pname = intent.getStringExtra("names");
occasions = intent.getStringExtra("oca");
System.out.println("OC BC"+occasions);
pics = intent.getStringExtra("photo");
dates = intent.getStringExtra("datess");
realtions = intent.getStringExtra("realations");
friendid = intent.getStringExtra("friendid");
System.out.println("Frnd BC"+friendid+userids);
sendgift=(ImageView)findViewById(R.id.wishfriend_sendgift);
ImageView propic=(ImageView)findViewById(R.id.wishfriend_propic);
username=(TextView)findViewById(R.id.wishfriend_name);
ocasions=(TextView)findViewById(R.id.wishfriend_occasion);
datess=(TextView)findViewById(R.id.wishfriend_dates);
pointshori=(HorizontalScrollView)findViewById(R.id.pointshori);
yourLayout = (LinearLayout)findViewById(R.id.linearhori);
selectedpoints=(TextView)findViewById(R.id.wishfrindselectdpoints);
username.setText(pname);
ocasions.setText(occasions);
datess.setText("Date: " + dates);
aQuery.id(propic).image(pics, true, true, 0, R.drawable.male);
PLACE_URL = "http:///webservices/wish_friend.php?user_id="+userids+"&det="+friendid+"&occ="+ URLEncoder.encode(realtions);
WISHU_URL = "http:///webservices/wish_friend.php?user_id="+userids;
sendgift.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtmessages.getText().toString().trim().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter Message",Toast.LENGTH_SHORT).show();
}
else if(giftpointss.toString().equals("0"))
{
Toast.makeText(getApplicationContext(),"Sorry you can not gift with 0 points",Toast.LENGTH_SHORT).show();
}
else
{
new AttemptLogin().execute();
}
}
});
new LoadAllPreset().execute();
new LoadPlacestatus().execute();
that is working fine,now i am going to B to C,but when i come back from C to B my app got crash,,getting null pointer exception
here
PLACE_URL = "http:///webservices/wish_friend.php?user_id="+userids+"&det="+friendid+"&occ="+ URLEncoder.encode(realtions);
Just check before accessing intent data
if( getIntent().getExtras() != null){
// intent has data
Intent intent=getIntent();
userids= intent.getStringExtra("userid");
...
}
else
{
//probably you are from C->B after back press
}
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;
}
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.
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.