I am new to android. I have a loginActivity which validates a user number and then starts a "searchactivity".
At runtime, I see the search activity coming up (after user is validated) but then android is having problems stopping the loginActivity.
I am getting a "java.lang.runtimeexception: Unable to stop activity {com.insruance/com.insurance.LoginActivity}: android.app.SuperNotCalledException : Activity
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3413)"
I would really appreciate if someone could point to what I am doing wrong.
Code :
public class LoginActivity extends Activity{
DatabaseWrapper myDbHelper;
private String agentNumber;
private OnClickListener btnClickListner = new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
// = new DataBaseHelper();
try {
Log.d("LoginActivity->onClick", "Before findByID");
EditText editText = (EditText)findViewById(R.id.txtUserNumber);
Log.d("LoginActivity->onClick", "After findByID");
agentNumber = editText.getText().toString();
String msg = "";
AgentDbHelper agentHelper = new AgentDbHelper(myDbHelper.getDatabaseHandle());
Log.d("LoginActivity->onClick", "Before agentIDExists");
if (agentHelper.agentIDExists(agentNumber))
msg = "Login success";
else
msg = "Login failed";
Log.d("LoginActivity->onClick", "After agentByID");
myDbHelper.closeDatabase();
myDbHelper = null;
Toast.makeText(getBaseContext(),
"User " + agentNumber + " found!",
Toast.LENGTH_LONG).show();
callSearchActivity();
}
catch(SQLException sqlEx)
{
Log.d("login - onclick", sqlEx.toString());
}
catch (Exception e) {
// TODO: handle exception
Log.d("login - onclick", e.toString());
}
}
};
private void callSearchActivity()
{
Intent intent = new Intent(getBaseContext(), SearchActivity.class);
Bundle bun = new Bundle();
bun.putString("agentNumber", agentNumber);
intent.putExtras(bun);
startActivity(intent);
}
#Override
public void onStop() {
try {
Log.d("In LoginActivity->onStop", "about to close myDbHelper");
if (myDbHelper != null)
{
myDbHelper.closeDatabase();
Log.d("In LoginActivity->onStop", "after myDbHelper is closed");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("In LoginActivity->onStop exeption", e.toString());
//e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.login);
Button loginButton = (Button)this.findViewById(R.id.btnLogin);
loginButton.setOnClickListener(btnClickListner);
myDbHelper = new DatabaseWrapper(this);
myDbHelper.openDatabase();
}
catch(Exception e) {
Log.e("ERROR", "ERROR IN CODE:"+e.toString());
}
}
}
A little more digging pointed me to this.
I was not calling super.onStop() within the overriden onStop.
I would have thought that Eclipse would have scripted this line when it created the onStop for me.
Related
I've created a Textview with a null value and button in my my Mainactivity and fetched some data from sql database server using AsyncTask method on button click and stored in to my textview. Then I called an intent to another activity activity2 to show something and I returned to my Mainactivity using intent.But I can't view the previously set data in textview. It shows null value.I want to set it previously fetched data.how can I set that?
public class MainActivity extends Activity {
public ImageView prev, now, next;
String depvisitid;
public TextView display, bottom, ptname, docname;
public String tokenh,tokenext,tokennow;
public String pname,pnamenext,pnamenow;
public boolean status;
public String drname,current;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (ImageView) findViewById(R.id.previmg);
now = (ImageView) findViewById(R.id.token);
next = (ImageView) findViewById(R.id.nextimg);
display = (TextView) findViewById(R.id.textView2);
ptname = (TextView) findViewById(R.id.textView3);
bottom = (TextView) findViewById(R.id.tokennum);
docname = (TextView) findViewById(R.id.textView);
// Connect runner = new Connect();
// runner.execute();
The setOnClickListener method:
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String sleepTime = time.getText().toString();
}
});
now.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
display.setText(tokenh);
ConnectNow nw = new ConnectNow();
nw.execute();
Intent i = new Intent(getApplicationContext(), StatusUpdate.class);
i.putExtra("patientname", pname);
i.putExtra("tokenno", tokenh);
i.putExtra("depvisitid", depvisitid);
startActivity(i);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Connect runner = new Connect();
runner.execute();
}
});
}
The onBackPressed:
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
// finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
class Connect extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet reset1 = null;
try {
reset1 = stmt.executeQuery(" select a.TOKENNO,b.FNAME,a.TOKENSTATUS,e.EMPFNAME,a.DEPVISITID from DEPTVISIT a,PATIENT_MASTER b,APP_EMPLOYEE e where a.PID=b.PID and (a.TOKENSTATUS='O' or a.TOKENSTATUS='S' ) and e.EMPID=a.EMPID and a.EMPID=2 and CONVERT(date,a.OPDATE)='2016-05-09' order by TOKENNO desc;");
while (reset1.next()) {
tokenh = reset1.getString("TOKENNO");
pname = reset1.getString("FNAME");
drname = reset1.getString("EMPFNAME");
depvisitid= reset1.getString("DEPVISITID");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return tokenh;
}
protected void onPostExecute(String result) {
bottom.setText(tokenh);
ptname.setText(pname);
docname.setText(drname);
}
}
The connect now class:
class ConnectNow extends AsyncTask<String, String, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "ssssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openjjj****");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "open****");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='S' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
System.out.println("status updated to S");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return status;
}
protected void onPostExecute(Boolean result) {
bottom.setText(tokenh);
ptname.setText(pnamenext);
docname.setText(drname);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent settings=new Intent(getApplicationContext(),Settings.class);
startActivity(settings);
}
return super.onOptionsItemSelected(item);
}
}
SECOND ACTIVITY StatusUdate.java:
public class StatusUpdate extends Activity {
public String tokenstatN, tokenstatY;
Button visited, notvisited;
String pname,tokennum,depvisitid;
TextView patnam,tknum;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statusupdate);
visited = (Button) findViewById(R.id.button);
notvisited = (Button) findViewById(R.id.button2);
patnam= (TextView) findViewById(R.id.textView4);
tknum= (TextView) findViewById(R.id.textView5);
Bundle extras = getIntent().getExtras();
pname = extras.getString("patientname");
tokennum = extras.getString("tokenno");
depvisitid = extras.getString("depvisitid");
patnam.setText(pname);
tknum.setText(tokennum);
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
}
The NotVisit class:
class NotVisit extends AsyncTask<String, String, Boolean> {
boolean status = false;
#Override
protected Boolean doInBackground(String... params) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
String username = "aaaaa";
String password = "sssss";
Connection DbConn = null;
try {
DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
Log.i("Connection", "openhhhh");
} catch (SQLException e1) {
e1.printStackTrace();
}
Log.w("Connection", "openlll");
Statement stmt = null;
try {
stmt = DbConn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='N' where DEPVISITID=" + depvisitid);
if (noOfRows > 0) {
status = true;
}
try {
DbConn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
Log.d("status", String.valueOf(status));
return status;
}
}
Whenever you wish to go to previous screen, Always finish the Activity that is on top. Here in your case, You are always creating new instance of MainActivity and this is the reason for getting null when you go back. Try using this in your StatusUpdate.java.
visited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visit vt= new Visit();
vt.execute();
StatusUpdate.this.finish();
}
});
notvisited.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NotVisit n = new NotVisit();
n.execute();
StatusUpdate.this.finish();
}
});
You can store the retrieved text in a static field of your activity class, but it's better save and restore it on activity recreation.So modify your activity like:
#Override
public void onCreate(Bundle b) {
// activity initialization
// textView = ...
if (b != null) {
textView.setText(b.getString("dbtext"));
}
}
and
#Override
protected void onSaveInstanceState(Bundle b) {
super.onSaveInstanceState(b);
b.putString("dbtext", textView.getText());
}
I've been doing an application which requires user inputs. This is my code:
UserInput.java
public class UserInput extends Activity
{
String tag = "UserInput";
EditText userInput;
Uri rResult = null;
int request_Code = 1;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.userinput);
Button btn= (Button) findViewById(R.id.btnSubmit);
Button saveButton = (Button) findViewById(R.id.btnSave);
saveButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent("com.example.Summary");
Bundle extras = new Bundle();
extras.putString("amount", userInput.getText().toString());
intent.putExtras(extras);
startActivityForResult(intent, request_Code);
}
});
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
saveAsText();
Log.d(tag, "In the onPause() event");
}
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
retrieveText();
Log.d(tag, "In the onResume() event");
}
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
public void saveAsText() {
String line = userInput.getText().toString();
if (rResult != null)
line += "|" + rResult;
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter pw = null;
try {
String path = Environment.getExternalStorageDirectory().getPath();
fw = new FileWriter(path + "/UserInput.txt");
bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
pw.println(line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pw != null)
pw.close();
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}// saveAsText
public void retrieveText() {
FileReader fr = null;
BufferedReader br = null;
try {
String line;
String path = Environment.getExternalStorageDirectory().getPath();
fr = new FileReader(path + "/UserInput.txt");
br = new BufferedReader(fr);
line = br.readLine();
StringTokenizer st = new StringTokenizer(line, "|");
userInput.setText(st.nextToken());
String rResult;
if (st.hasMoreTokens())
rResult = st.nextToken();
else
rResult = "";
Log.d(tag, "readAsText: " + line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Here is my Summary Page:
public class Summary extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
Bundle bundle = getIntent().getExtras();
int amount = Integer.parseInt(bundle.getString("amount"));
TextView resultView = (TextView) findViewById(R.id.retrieveInput);
resultView.setText(amount);
}
When I run using these codes, it still runs, but when I click the User Input button, it crashed. May I know what went wrong and what I can do so that it runs perfectly? Thanks!
Logcat
When you create an Intent with the String constructor, you are actually setting the Intent's action. What you want is intent = new Intent(UserInput.this, Summary.class). Also make sure that the Summary activity is registered in your manifest.
userInput, did you initiate that edit text? when you don't initiate. Its starting value is null. In that onclick, you're getting that null pointer exception bc you're trying to dereference that null object
i'm observing a weird scenario here. I have a background android service which is running perfectly. but when I kill the process or application from my RecentApps my Application calls the onStartCommand method again. I don't know where I went wrong. I have searched alot but didn't find any appropriate solution. Could someone please mention what I did wrong? Thanks in Advance
Activity:
public class OptionSelectionActivity extends Activity implements
OnClickListener {
Timer time;
Intent serviceIntent;
private Button btn_selectionquiz, btn_alerts, btn_history;
ConnectionManager cm;
boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e("onCreate", "im Running");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
cm = new ConnectionManager(getApplicationContext());
isInternetPresent = cm.isConnected();
serviceIntent = new Intent(getApplicationContext(),MyService.class);
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// isMyServiceRunning();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
XmlView();
RegisterListenerOnXml();
}
private void XmlView() {
btn_selectionquiz = (Button) findViewById(R.id.optionselection_btn_selectquiz);
btn_alerts = (Button) findViewById(R.id.optionselection_btn_alerts);
btn_history = (Button) findViewById(R.id.optionselection_btn_history);
}
private void RegisterListenerOnXml() {
btn_selectionquiz.setOnClickListener(this);
btn_alerts.setOnClickListener(this);
btn_history.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
// TODO Auto-generated method stub
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
switch (v.getId()) {
case R.id.optionselection_btn_selectquiz:
// intent calling
i = new Intent(this, TeacherSelectionActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_history:
// intent calling
i = new Intent(this, QuizHistoryActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_alerts:
// intent calling
i = new Intent(this, GettingAlerts.class);
startActivity(i);
break;
default:
break;
}
}else
{
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(OptionSelectionActivity.this, "Internet Conncetion", "No internet Connection", false);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String temp = service.service.getClassName();
if ("com.smartclasss.alerts.MyService".equals(temp)) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onSTOP", "im calling...!!!!");
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "now im calling after onStop");
}
}
Service:
public class MyService extends Service{
private SharedPreferences prefs;
private String prefName = "userPrefs";
public static String GETTING_ALERTS_URL = "http://"
+ IPAddress.IP_Address.toString()
+ "//MyServices/Alerts/AlertService.svc/alert";
public static String TAG_NAME = "DoitResult";
public static String TAG_ALERT_TITLE = "alertTitle";
static String Serv_Response = "";
static String Serv_GettingQuiz_Response = "";
boolean flag = false;
boolean isServRun = true;
public Timer time;
ArrayList<Alerts> alertsList;
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Attendence", "Service Created");
// TODO Auto-generated method stub
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
final String currentDate = df.format(Calendar.getInstance().getTime());
// Toast.makeText(getBaseContext(), "Service Started :"+" "+currentDate, Toast.LENGTH_LONG).show();
if(flag == false)
{
try {
savingDateinPref(currentDate);
new DoInBackground().execute(currentDate);
flag = true;
isServRun = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defValue");
if(!currentDate.equals(val))
{
flag = false;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TAG_KEY");
//---saves the values---
editor.commit();
}
}
},0,5000);
return START_STICKY;
}
private class DoInBackground extends AsyncTask<String, Void, Void> {
String cellphoneDate = "";
ArrayList<Alerts> alertsList = new ArrayList<Alerts>();
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
cellphoneDate = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_ALERTS_URL + "/"
+ cellphoneDate);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (Serv_Response != null) {
////////////////////////////new code for getting list ///////////////////
JSONObject jsonObj1 = new JSONObject(Serv_Response);
JSONArray alertName = jsonObj1.getJSONArray(TAG_NAME);
for (int i = 0; i < alertName.length(); i++) {
JSONObject c = alertName.getJSONObject(i);
String alert_title = c.getString(TAG_ALERT_TITLE);
Alerts alertObject = new Alerts();
alertObject.setAlertTitle(alert_title);
alertsList.add(alertObject);
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(getBaseContext(), "From Database :" + Serv_GettingQuiz_Response, Toast.LENGTH_LONG).show();
//String array[] = new String[size];
for(int i = 0; i < alertsList.size() ; i++ )
{
showNotification(alertsList.get(i).getAlertTitle(), "TAP for More Details", i);
// savingDate(Serv_GettingQuiz_Response);
}
}
}
private void savingDateinPref(String value){
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("TAG_KEY",value);
//---saves the values---
editor.commit();
}
}
Logcat:
06-03 12:25:22.844: E/onCreate(29973): im Running
06-03 12:25:23.174: E/Attendence(29973): Service Created
06-03 12:25:30.702: E/onSTOP(29973): im calling...!!!!
06-03 12:25:32.274: E/onCreate(29973): im Running
06-03 12:25:33.655: E/onSTOP(29973): im calling...!!!!
06-03 12:25:34.366: E/onCreate(29973): im Running
06-03 12:25:35.878: E/onSTOP(29973): im calling...!!!!
06-03 12:25:36.869: E/onRestart(29973): now im calling after onStop
06-03 12:25:45.027: E/onSTOP(29973): im calling...!!!!
06-03 12:25:48.221: E/Attendence(30447): Service Created
here in the logcat the last line shows that its call the onstartcommand method again. Why is it so? Even my Activity is not running I meant to say (the service starts in oncreate method on on acticity, but here in the logcat the control goes directly to the onStartCommand when i destroy my App ).
Your service will be START_STICKY so the android framework is restarting it -> This will give you call to onStartCommand()
I changed my service to START_NOT_STICKY so the android framework will not restart my service on its own without any explicit request from out application
To make your service of START_NOT_STICKY, just return value Service.START_NOT_STICKY from onStartCommand()
This worked and solved my issue
I have an app that generates music after a user authenticates with OAuth on a webview activity, looking something like this: main player activity-OAuth Activity-back to main player activity. However, the onCreate method is being called twice when going from the OAuth activity, resulting in two audio tracks generated and played at the same time.
Here's part of the code from the MainActivity:
public class MainActivity extends Activity {
int pitch=60;
private static final float VISUALIZER_HEIGHT_DIP = 50f;
Random rn;
boolean isRunning = true;
boolean isPlaying=false;
SeekBar fSlider;
double sliderval;
MediaPlayer mediaPlayer=new MediaPlayer();
ImageButton startStopButton;
ImageButton stopButton;
SeekBar vSlider;
VisualizerView mVisualizerView;
private Visualizer mVisualizer;
ImageButton connectButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// point the slider to the GUI widget
rn = new Random();
fSlider = (SeekBar) findViewById(R.id.frequency);
fSlider.setProgress(0);
vSlider= (SeekBar) findViewById(R.id.seekBar2);
vSlider.setMax(10);
vSlider.setProgress(0);
TextView viewinterval=(TextView) findViewById(R.id.textView2);
viewinterval.setText("");
startStopButton=(ImageButton) findViewById(R.id.imageButton2);
View activity= this.findViewById(R.id.playerActivity);
stopButton=(ImageButton) findViewById(R.id.imageButton1);
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density));
params.addRule(RelativeLayout.BELOW, R.id.seekBar2);
mVisualizerView = new VisualizerView(this);
mVisualizerView.setLayoutParams(params);
((ViewGroup) activity).addView(mVisualizerView);
connectButton=(ImageButton) findViewById(R.id.imageButton3);
connectButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
mediaPlayer.pause();
Intent intent= new Intent(getApplicationContext(), WebViewActivity.class);
startActivity(intent);
}
});
if(riskscores.length !=0){
viewinterval.setText("generating audio");
new MIDISequence().execute();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPause() {
super.onPause();
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
class MIDISequence extends AsyncTask<String,Void,String>{
Here's the code from my OAuth Activity
public class WebViewActivity extends Activity {
private WebView gWebView;
final String REDIRECT_URI = "https://localhost:5000/receive_code";
final String CLIENT_ID = "can't post it here";
final String CLIENT_SECRET = "can't post it here";
final String SCOPE = "basic names genomes analyses";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
gWebView = (WebView) findViewById(R.id.webView1);
gWebView.loadUrl("https://api.23andme.com/authorize/?redirect_uri="
+ REDIRECT_URI + "&response_type=code&client_id=" + CLIENT_ID
+ "&scope=" + SCOPE);
Log.d("WEBVIEW", "got to webpage");
gWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.startsWith(REDIRECT_URI)) {
Log.d("WEBVIEW", "onpagefinished is called");
System.out.println("got to override");
if (url.indexOf("code=") != -1) {
//if the query contains code
String queryString = null;
try {
queryString = new URL(url).getQuery();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(queryString);
String[] params = queryString.split("&");
String code = null;
for (String param : params) {
if (param.startsWith("code=")) {
code = param.substring(param.indexOf('=') + 1);
}
}
gWebView.setVisibility(View.GONE);
new PostRequest().execute(code);
// don't go to redirectUri
}
}
}
});
}
class PostRequest extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... params) {
code retrieving client data.....
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("CPE" + e);
} catch(SocketException ex)
{
Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
return "error occured";
} catch (JSONException e) {
e.printStackTrace();
return "error occured";
} catch (IllegalStateException e) {
e.printStackTrace();
return "error occured";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error occured";
}
}
return "request complete";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
}
The onCreate method of the MainActivity is called twice for some reason... What is going on here?
There seems to be a mistake in your implementation. The thing is, you are trying to use an Intent object to navigate back to your MainActivity form WebActvitity. This is a problem. You shouldn't be doing that.
Whenever you wanna move back to your previous activity, you should simply be calling finish() in the current Activity.
In our scenario,the by using Intent in your WebActivity you are creating a new instance for your MainActivity which already exists in the stack(background). Simply calling finish() in the WebActivity should close it and your MainActivity should be visible.
Do the following changes,
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
Replace the above method like this,
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Post result", result);
finish();
}
Other than the expected cases, I have observed that only those activities (onCreate) are called twice which are creating new Thread or Runnable, AsyncTask in your case. (I believe this to be a bug in Android).
The solution is simple (though you may not like it :p)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
if(savedInstanceState == null){
// everything else that doesn't update UI
}
}
It seems you are getting multiple instance of your first activity. use this in manifest of 1st activity:
android:launchMode="singleTop"
else call finish() after doing startActivity() for 2nd activity
Warning
**07-07 15:24:25.021: WARN/ActivityManager(57): Activity is launching as a new task, so cancelling activity result.**
07-07 15:24:25.681: WARN/ActivityManager(57): Activity pause timeout for HistoryRecord{43cccce8 com.tcs.QuickNotes/.QuickNotesHome}
07-07 15:24:27.392: INFO/AudioPathIn onActivityResult(1370): onActivityResult
07-07 15:24:27.410: INFO/requestCode(1370): requestCode1
07-07 15:24:27.420: INFO/resultCode(1370): **resultCode0**
My code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("AudioPathIn onActivityResult"," onActivityResult"+audioFilePath.getText().toString());
Log.i("requestCode ","requestCode"+requestCode);
Log.i("resultCode ","resultCode"+resultCode);
if(requestCode == 1)
{
if(resultCode == RESULT_OK)
{
Audioflag=1;
audioFilePath.setVisibility(View.VISIBLE);
String defaultToneStatus = data.getStringExtra("DefaultTone");
if(defaultToneStatus.equals("false"))
{
audioFilePath.setText(AudioRecorder.getFilePath());
}
else
{
defaultAudioToneFlag = 1;
audioFilePath.setText("-");
}
}else
{
Audioflag=0;
}
}
}
Its not entering the above code.
Result code is always 0;
Code from where control is being returned :
public class AudioRecorder extends Activity implements OnClickListener {
String p = null;
static String filePath,FlagFromEdit,primaryIdFromEdit;
static int pId;
static int audioFlag;
Intent intent;
CheckBox defaultRingtone;
MyRecorder recorder;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
/** Called when the activity is first created. */
super.onCreate(savedInstanceState);
setContentView(R.layout.voicenote);
audioFlag=0;
intent=getIntent();
p = intent.getStringExtra("primaryiid");
pId = (Integer.parseInt(p));
Log.v("p", "pid" +pId);
setResult(RESULT_CANCELED);
// FlagFromEdit=intent.getStringExtra("FlagFromEdit");
// primaryIdFromEdit=intent.getStringExtra("PrimaryId");
defaultRingtone = (CheckBox)findViewById(R.id.Cb_defaultRingtone);
defaultRingtone.setOnClickListener(this);
Button btn_record = (Button)findViewById(R.id.btn_record);
btn_record.setOnClickListener(btnListenerRecord);
Button btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(btnListenerStop);
Button btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(btnListenerPlay);
Button btn_save = (Button)findViewById(R.id.btn_save);
btn_save.setOnClickListener(btnListenerSave);
}
private OnClickListener btnListenerRecord = new OnClickListener()
{
public void onClick(View v)
{
try
{
recorder = new MyRecorder("voice/" + pId + "");
recorder.start();
Toast.makeText(getBaseContext(),"Recording started !", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
private OnClickListener btnListenerStop = new OnClickListener()
{
public void onClick(View v)
{
MediaPlayer mp = new MediaPlayer();
try
{
recorder.stop();
Toast.makeText(getBaseContext(),"Stop ! IsPlaying : " + mp.isPlaying(), Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
private OnClickListener btnListenerPlay = new OnClickListener()
{
public void onClick(View v)
{
MediaPlayer mp = new MediaPlayer();
try
{
mp.setDataSource("/sdcard/voice/"+ pId + ".3gp");// set data-source
mp.prepare();// prepare
mp.start();
Toast.makeText(getBaseContext(), "Playing File no : "+pId, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
Toast.makeText(getBaseContext(), " Is playing ? : "+ mp.isPlaying(),
Toast.LENGTH_LONG).show();
}
};
private OnClickListener btnListenerSave = new OnClickListener()
{
public void onClick(View v)
{
try
{
// String fileName = "/sdcard/voice/"+ pId + ".3gp";
// Intent intentSave = new Intent(getBaseContext(),AddToDoList.class);
// intentSave.putExtra("SavedFile", fileName);
// intentSave.putExtra("CalledFrom", "AudioRecorder");
// startActivity(intentSave);
audioFlag=1;
Toast.makeText(AudioRecorder.this,"File saved successfully !",Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("DefaultTone", "false");
setResult(RESULT_OK,intent);
finish();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
public static int getAudioFlag()
{
return audioFlag;
}
public static String getFilePath()
{
filePath ="/sdcard/voice/"+ pId + ".3gp";
return filePath;
}
public static void playAudioFile(Context ctx,String pId)
{
MediaPlayer mp = new MediaPlayer();
try
{
Log.i("playaudiofile","file being played");
//Toast.makeText(ctx,"file being played",Toast.LENGTH_LONG).show();
Toast.makeText(ctx, "Playing File no : "+pId, Toast.LENGTH_LONG).show();
mp.setDataSource("/sdcard/voice/"+ pId + ".3gp");// set data-source
mp.prepare();// prepare
mp.start();
}
catch (Exception e)
{
Toast.makeText(ctx, " No file was assigned ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(AudioRecorder.this,"Default ringtone set !",Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("DefaultTone", "true");
setResult(RESULT_OK,intent);
finish();
}
}
As Pentium10 has noticed, you are calling setResult(RESULT_CANCELED); in
onCreate().
Calling setResult() makes a call to onActivityResult method.
The value of RESULT_CANCELLED is 0x00000000.
So just remove the call setResult from onCreate method