Error with passing data into intent - android

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

Related

set fetched data from database to a textview after calling intent

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

Retrieve previous inputs Android

I am currently working on a project which requires me to enter and store user's input. Is there any way that I could do so that I can retrieve the previous records as well rather than the current record?
Code
package com.example;
// imports
public class Testing extends Activity {
String tag = "Testing";
EditText amount;
Uri rResult = null;
int request_Code = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testyourself);
amount = (EditText) findViewById(R.id.etUserInput);
Button saveButton = (Button) findViewById(R.id.btnSave);
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.example.Result");
Bundle extras = new Bundle();
extras.putString("amount", amount.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(); // Step E.1
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(); // Step E.1
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 = amount.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 + "/exercise.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 + "/exercise.txt");
br = new BufferedReader(fr);
line = br.readLine();
StringTokenizer st = new StringTokenizer(line, "|");
pullup.setText(st.nextToken());
bench.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();
}
}
}
}
Results Page
public class Result extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
Bundle bundle = getIntent().getExtras();
int amount = Integer.parseInt(bundle.getString("amount"));
TextView ResultView = (TextView) findViewById(R.id.userInput);
ResultView.setText(String.valueOf(amount));
}
}
Instead of writing to a file you can use SharedPreferences which allows you to store information such as user inputs or statistics until explicitly removed. Even if you close your app and re-open it the information that you save using SharedPreferences will remain.
The selected answer for this question is a great example of creating a helper class for SharedPreferences that will allow you to easily save, retrieve, and delete information.
Assuming that you want to save an int value.
If your save and retrieve methods in your helper class are:
public void saveAmount(String key, int amount) {
_prefsEditor.putInt(key,amount);
_prefsEditor.commit();
}
public int getAmount(String key) {
return _sharedPrefs.getInt(key,0); //returns 0 if nothing is found
}
and you have an ArrayList of ints like so:
ArrayList<int> arrayList = new ArrayList<int>();
arrayList.add(123);
arrayList.add(231);
arrayList.add(312); //These are just placeholder values.
then you can create a loop to save:
private AppPreferences _appPrefs;
.
.
.
for(int i = 0; i < arrayList.size(); i++) {
_appPrefs.saveAmount(i,arrayList.get(i));
}
Note that in the above method the keys for the elements are just the indices of the elements within the array.
In order to retrieve the information and recreate the ArrayList you need to first save the length of the ArrayList in shared preferences as well.
public void saveLength(int length) {
_prefsEditor.putInt("length", length);
_prefsEditor.commit();
}
public int getLength() {
return _sharedPrefs.getInt("length",0);
}
then you can create a loop to retrieve:
ArrayList<int> arrayList = new ArrayList<int>();
.
.
.
for(int i = 0; i < _appPrefs.getLength(); i++) {
arrayList.add(getAmount("" + i));
}

onStartCommand Call after Destroying an Activity

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

InstantiationException occur while Downloading using Service

I was trying to do a service sample program and i am getting following exception
09-10 20:57:57.871: E/AndroidRuntime(280): FATAL EXCEPTION: main 09-10
20:57:57.871: E/AndroidRuntime(280): java.lang.RuntimeException:
Unable to instantiate service com.example.demoservice.DownloadService:
java.lang.InstantiationException:
com.example.demoservice.DownloadService
I have seen many solutions to this type of execption like passing string to constructor etc.But those solutions didnt solved this issue.
Code sample is given below
public class MainActivity extends Activity {
TextView textView ;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if(bundle != null){
String filepath = bundle.getString(DownloadService.FILEPATH);
int result = bundle.getInt(DownloadService.RESULT);
if(result == Activity.RESULT_OK){
Toast.makeText(context, "Sucess" + filepath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Sucess", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
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;
}
public void onClick(View v){
Intent i = new Intent(this, DownloadService.class);
i.putExtra(DownloadService.FILENAME, "index.html");
i.putExtra(DownloadService.URL, "http://www.vogella.com/index.html");
startService(i);
textView.setText("Service started");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
}
Service class
public class DownloadService extends IntentService{
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String urlpath = intent.getStringExtra(URL);
String filename = intent.getStringExtra(urlpath);
File output = new File(Environment.getExternalStorageDirectory(), filename);
if(output.exists()){
output.delete();
}
InputStream input = null;
FileOutputStream fout = null;
try {
java.net.URL url = new java.net.URL(urlpath);
input = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(input);
fout = new FileOutputStream(output.getPath());
int next = -1;
while((next = reader.read())!= -1){
fout.write(next);
}
result = Activity.RESULT_OK;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fout != null){
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
publishResult( output.getAbsoluteFile(), result);
}
private void publishResult(File absoluteFile, int result2) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,DownloadService.class);
intent.putExtra(FILEPATH, absoluteFile);
intent.putExtra(RESULT, result2);
sendBroadcast(intent);
}
}
I am running app using Emulator.Is it possible to run this problem in emulator,because writing to external directory
Can anyone help me?
Use
public DownloadService() {
super("DownloadService");
// TODO Auto-generated constructor stub
}
Instead of
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
UPDATE:
You have to declare a default constructor which calls the public IntentService (String name) super constructor of the IntentService class you extend. ie. In simple words, you need to provide no-argument constuctor for your service ,without which android wont be able to instantiate your service.
you start the intentservice using startService(your_intent); And as per the documentation
You should not override onStartCommand() method for your
IntentService. Instead, override onHandleIntent(Intent), which the
system calls when the IntentService receives a start request.
IntentService

android : Unable to stop activity

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.

Categories

Resources