Android call 2 or more classes from main activity - java

I am new to android. I have main activity from which I need to call different classes to perform different functions. But whenever I call two classes at same time, only the last intent is called. Can someone suggest a way to call 2 or more classes at the same time in an activity. Thank you
Below is my code example
Main Activity
public class MainActivity extends AppCompatActivity {
public Api mApi;
Button data;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = (Button) findViewById(R.id.button2);
//calling sygic truck api and implementing sygic call back
mApi = Api.init(getApplicationContext(), "com.sygic.truck", "com.sygic.truck.SygicService", mApiCallback);
//connecting sygic app
mApi.connect();
data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(getApplicationContext(), locationInfo.class);
Intent intent2 = new Intent(getApplicationContext(), routeInfo.class);
Intent[] list = new Intent[2];
list[0] = intent1;
list[1] = intent2;
startActivities(list);
}
});
}
}
locationInfo class
public class locationInfo extends AppCompatActivity {
public Api mApi;
public TextView coordinates;
public String currentLocation = "";
public String longitude;
public String latitude;
public Button data;
public String altitude, speed;
public int speedLimit;
//calling gps class from sygic lib
GpsPosition gpsPos = new GpsPosition();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinates = (TextView) findViewById(R.id.textView);
// sygicGetData();
try {
Log.v("debug", "Location is...1" );
boolean satInfo = true;
int maxTime = 0;
gpsPos = ApiNavigation.getActualGpsPosition(satInfo, maxTime);
longitude = String.valueOf(gpsPos.getLongitude());
latitude = String.valueOf(gpsPos.getLatitude());
altitude = String.valueOf(gpsPos.getAltitude());
speed = String.valueOf(gpsPos.getSpeed());
speedLimit = ApiInfo.getCurrentSpeedLimit(maxTime);
Log.v("debug", "Location is...2" );
Position pos = new Position();
pos.setPosition(gpsPos.getLongitude(), gpsPos.getLatitude());
currentLocation = ApiLocation.getLocationAddressInfo(pos, maxTime);
coordinates.setText("\n" + "Current Location:" + currentLocation + "\n" + "Longitude:" + longitude + "\n" + "Latitude:" + latitude +
"\n" + "Altitude:" + altitude + "\n" + "Current Speed:" + speed +
"\n" + "Speed Limit:" + speedLimit);
} catch (GpsException e) {
Log.e("GpsPosition", "Error code:" + e.getCode());
} catch (InvalidLocationException e) {
Log.e("Location", "Error code:" + e.getCode());
} catch (GeneralException e) {
e.printStackTrace();
}
}
}
routeInfo class
public class routeInfo extends AppCompatActivity {
public String remainingDistance, remainingTime;
public String totalDistance, totalTime;
public Button data;
public TextView coordinates;
public RouteInfo routeInfo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinates = (TextView)findViewById(R.id.textView2);
// sygicGetData();
try {
boolean info = true;
int maxTime = 0;
routeInfo = ApiNavigation.getRouteInfo(info, maxTime);
totalDistance = String.valueOf(routeInfo.getTotalDistance());
remainingDistance = String.valueOf(routeInfo.getRemainingDistance());
totalTime = String.valueOf(routeInfo.getTotalTime());
remainingTime = String.valueOf(routeInfo.getRemainingTime());
coordinates.setText("\n" + "Total Travel Distance:" + totalDistance + "\n" + "Remaining Travel Distance:" + remainingDistance + "\n" + "Total Travel Time:" + totalTime + "\n" +
"Remaining Travel Time:" + remainingTime + "\n");
} catch (GpsException e) {
Log.e("GpsPosition", "Error code:" + e.getCode());
} catch (InvalidLocationException e) {
Log.e("Location", "Error code:" + e.getCode());
} catch (GeneralException e) {
e.printStackTrace();
}
}
}
Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jackfruit.sygicdata4">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".getters.locationInfo"></activity>
<activity android:name=".getters.routeInfo"></activity>
</application>
</manifest>

Ok,
startActivities()
is used to construct something called a synthetic back stack.
In an app when you move from 1 activity to another without invoking a
finish()
in any of the activities you construct something called a "backstack". It is called a back stack because it is the stack of activities that get restored when you keep pressing the back button.
If you wanted to artificially create a backstack you would
-startActivities()
What this does is artificially insert everything but the activity of the last intent into the backstack.
If you wanted to run activit 1 and then run activity2
just call
startActivity()
on them separately
If you want the 2 to tasks to run in parallel you need to use something called "AsyncTask". Literature here

Related

How can I save my listview with Saved Preferences

I want develop Pomodoro app. I have edittext, countdowntimer, listview on my project. My app can work.And I have a lot of text on my list. my 3. countdown timer on finish I add text my listview. How can I save listview with sharedpreferences? and How Can I do this . Thanks A lot of
main_activty.class
public class pomodoro extends AppCompatActivity {
Button baslat,backhome,bitir;
EditText edittextcalisma,edittextmola;
CountDownTimer calisma,mola;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter arrayAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomodoro);
listView=(ListView)findViewById(R.id.listv);
arrayAdapter = new ArrayAdapter<String>(
this,R.layout.list_view,R.id.textitem, list);
listView.setAdapter(arrayAdapter);
bitir=findViewById(R.id.bitirbutton);
baslat = findViewById(R.id.baslatbutton);
edittextcalisma = findViewById(R.id.edittextcalisma);
edittextmola = findViewById(R.id.edittextmola);
baslat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeKeyboard();
final int molapo = Integer.valueOf(edittextmola.getText().toString());
final int calismapo = Integer.valueOf(edittextcalisma.getText().toString());
if (calismapo <= 600 && molapo <= 600 && calismapo > 0 && molapo>0){
calisma = new CountDownTimer(calismapo * 60000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
final int molapo = Integer.valueOf(edittextmola.getText().toString());
mola = new CountDownTimer(molapo * 60000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
pomodoro.setText("Bitti");
CountDownTimer bekle = new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millis) {
}
#Override
public void onFinish() {
Calendar c = Calendar.getInstance();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMMM-yyyy HH:mm");
String datetime = dateformat.format(c.getTime());
list.add("Çalışma Süresi : " + calismapo +" dk "+"\n"+ "Mola Süresi : " + molapo+" dk " +"\n" + datetime);
arrayAdapter.notifyDataSetChanged();
}
}.start();
}
}.start();
}
}.start();
}
}
});
}
}
you need to put metadata in LUNCHER activity in order to work
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
</activity>

Android saving data from sensor in internal storage file not found

I am now working on my first android project, including saving data from the sensor on the phone for 15 minutes after the mainAcitivity called. Considering sometimes there may not be sd card in the phone, I decided to store the files on internal storage.
Now I have stuck it these problems for a few days:
After saving the data I have returned the directory with getFilesDir(), but I couldn't find the showed route anyway.
screen shot after running service
/data/user/0/com.example.liya.medicinecalendar/files/201807100711.txt
The service according to the toast sometimes starts and ends not as wished.
In MainActivity.class I just used
startService(new Intent(MainActivity.this,SaveSensorService.class));
I didn't create a thread because I don't wanna let screen activity and service run at the same time.
Here is my SaveSensorService.class
public class SaveSensorService extends Service implements SensorEventListener {
private static final String TAG = "SaveSensorService";
private Float xValue, yValue, zValue, xGyroValue, yGyroValue, zGyroValue;
SensorManager sensorManager;
private Sensor accelerometer, mGyro;
private SimpleDateFormat Date_Format,Newtime_Format;
private Calendar calendar;
private String StartTime, StopTime, CurrentTime, FileName;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: SaveSensorService started.");
Newtime_Format = new SimpleDateFormat("HHmmss");
calendar = Calendar.getInstance();
StartTime = Newtime_Format.format(calendar.getTime());
CurrentTime = StartTime;
//calendar.add(Calendar.MINUTE, 15);//save sensor data for 15min
calendar.add(Calendar.SECOND,60);//for test
StopTime = Newtime_Format.format(calendar.getTime());
Toast.makeText(SaveSensorService.this, StartTime+" SaveSensorService is running",Toast.LENGTH_SHORT).show();
Log.d(TAG, "onCreate: Initializing Sensor Services");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null) {
sensorManager.registerListener(SaveSensorService.this, accelerometer, 5000000);
Log.d(TAG, "onCreate: Registered accelerometer Listener");
} else {
xValue = null;
yValue = null;
zValue = null;
;
}
mGyro = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (mGyro != null) {
sensorManager.registerListener(SaveSensorService.this, mGyro, 5000000);
Log.d(TAG, "onCreate: Registered Gyro Listener");
} else {
xGyroValue = null;
yGyroValue = null;
zGyroValue = null;
}
if ((accelerometer!=null || mGyro != null)&&CurrentTime.compareTo(StopTime) < 0) {
calendar = Calendar.getInstance();
CurrentTime = Newtime_Format.format(calendar.getTime());
saveSensor();
}
else {
stopSelf();
Toast.makeText(SaveSensorService.this,"Time's up or device not support."+ CurrentTime,Toast.LENGTH_SHORT).show();
}
return START_STICKY;
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy: SaveSensorService stopped.");
Toast.makeText(SaveSensorService.this,"Sensordaten wurden gespeichert."+ CurrentTime,Toast.LENGTH_SHORT).show();
}
/*********** save the sensor data during the set time - START *******************/
public void saveSensor () {
//create a new file, named by the current time
Date_Format = new SimpleDateFormat("yyyyMMddHHmm");
FileName = Date_Format.format(calendar.getTime())+".txt";
try{
FileOutputStream fos = null;
//to prevent that the file fail to be read or created, use catch to print the error
// write in txt,
fos = openFileOutput(FileName, MODE_APPEND);
//write the first line - description
fos.write("xValue\tyValue\tzValue\txGyroValue\tyGyroValue\tzGyroValue\r\n".getBytes()); //define the first line
//append the sensor data in the file
fos.write((xValue + "\t" + yValue + "\t" + zValue + "\t" + xGyroValue + "\t" + yGyroValue + "\t" + zGyroValue + "\r\n").getBytes());
fos.flush();
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Log.d(TAG, "onClick: file ist written.");
Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FileName, Toast.LENGTH_SHORT).show();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor sensor = sensorEvent.sensor;
//get accelerometer data
if(sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
Log.d(TAG, "onSensorChanged: X:" + sensorEvent.values[0] + "Y:" + sensorEvent.values[1] + "Z:" + sensorEvent.values[2]);
xValue = sensorEvent.values[0];
yValue = sensorEvent.values[1];
zValue = sensorEvent.values[2];
}
//put gyrocope data
else if(sensor.getType()==Sensor.TYPE_GYROSCOPE) {
Log.d(TAG, "onSensorChanged: XG:" + sensorEvent.values[0] + "YG:" + sensorEvent.values[1] + "ZG:" + sensorEvent.values[2]);
xGyroValue = sensorEvent.values[0];
yGyroValue = sensorEvent.values[1];
zGyroValue = sensorEvent.values[2];
}
}
/***************** save the sensor data during the set time - END *************************/
}
And here is my AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.liya.medicinecalendar">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/foreground"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CalendarActivity"></activity>
<service android:name=".SaveSensorService"
android:enabled="true"/>
<receiver android:name=".AlarmReceiver"></receiver>
<service android:name=".AlarmService"
android:enabled="true"/>
</application>
</manifest>
I will be so grateful if someone can give me some advice to solve this problem when saving data. Thank you so much in advance!

My BroadcastReceiver is called two times when turning on/off wifi or gps?

I have googled many time to find the solution but It didn't work.
struggeld with this for many days ,please help me if you faced this problem and solved it.
when I turn on or off wifi or Gps the Receiver triggers two time
although sometimes once but if it triggers two time it would corrupt my plans for the app.
thx in advance ...
inside manifest.xml :
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
<action android:name="android.location.PROVIDERS_CHANGED"/>
</intent-filter>
</receiver>
this the BroadcastReceiver class :
public class MyBroadcastReceiver extends BroadcastReceiver {
String TAG_NETW = "NetworkConnctivityUtils";
#Override
public void onReceive(Context context, Intent intentR) {
try {
// MyApplication.dbApp = new SqliteHelper(context, ConstHelper.DATABASE_PATH, ConstHelper.DATABASE_NAME);
SimpleDateFormat sdf = new SimpleDateFormat(ConstHelper.Simple_Date_Format);
if (intentR.getAction().matches("android.location.PROVIDERS_CHANGED")) {
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.d(TAG_NETW, "locationGps" + " ------ event On " + intentR.getAction());
StatusDriverQueryHelper.insertStatusDriverlog(EnumDeviceStatus.GPSOn, "0", AuthenticateHelper.getDeviceId(context, ""), UnicodeHelper.numberToEnglish(sdf.format(new Date())));
StatusDriverQueryHelper.showItems();
} else if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// todo : if at this time of other provider change the gps was of / or no what will be the status
Log.d(TAG_NETW, "locationGps" + " ------ event Off " + intentR.getAction());
StatusDriverQueryHelper.insertStatusDriverlog(EnumDeviceStatus.GPSOff, "0", AuthenticateHelper.getDeviceId(context, ""), UnicodeHelper.numberToEnglish(sdf.format(new Date())));
StatusDriverQueryHelper.showItems();
}
LogService.sendAllStatus();
} else {
}
} catch (Exception e) {
Log.d(TAG_NETW, "locationGps" + " error On GPS EVENT Reciver " + intentR.getAction());
}
/***************************/
try {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intentR.getAction())) {
int status = NetworkConnctivityUtils.getConnectivityStatusString(context);
Log.e(TAG_NETW, " here : " + intentR.getAction() + " , STATUS : " + String.valueOf(status));
// Wifi is connected
if (status == NetworkConnctivityUtils.NETWORK_STATUS_NOT_CONNECTED) {
Log.d(TAG_NETW, "CONNECTIVITY" + " Not-----Available");
} else if (status == NetworkConnctivityUtils.NETWORK_STAUS_WIFI) {
Log.d(TAG_NETW, "CONNECTIVITY" + " OK wifi");
} else if (status == NetworkConnctivityUtils.NETWORK_STATUS_MOBILE) {
Log.d(TAG_NETW, "CONNECTIVITY" + " OK mobile");
} else {
Log.d(TAG_NETW, "CONNECTIVITY" + " nonononon ---");
}
}
} catch (Exception e) {
}
}
}
***** FOUND A WAY TO SOLVE IT
but I don't know this is the best way to handle it :
I use a flag to check if it is the first time then after 1 or 2 sec return the flag back.
// ....
#Override
public void onReceive(Context context, Intent intentR) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(ConstHelper.Simple_Date_Format);
if (intentR.getAction().matches("android.location.PROVIDERS_CHANGED")) {
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
if (ConstHelper.GpsActionisDoneOnce == false) {
ConstHelper.GpsActionisDoneOnce = true;
new Handler().postDelayed(new Runnable() {
public void run() {
ConstHelper.GpsActionisDoneOnce = false;
}
}, 500);
// GPS ACTION/CHECKING ..
} else {
}
}
} catch (Exception e) {
}
// ......
The use of broadcast receiver is deprecated because contribute to low system performance. The proper way to do it is using the JobScheduler.

how to create an save sensor data in a csv file in internal memory

I'm trying to get the accelerometer data in a file on internal storage , i tried many ways they but i get errors like java.io.FileNotFoundException: Value.csv: open failed: EROFS (Read-only file system) or ESIDIR.
#RequiresApi(api = Build.VERSION_CODES.N)
public class MainActivity extends Activity implements SensorEventListener,View.OnClickListener {
private TextView xText, yText, zText;
private Sensor sensor;
private SensorManager sManager;
private Button startB, stopB;
private boolean mInitialized;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create sensor manager
sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Accelerometer sensor
sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//Register sensor Listener
sManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
// assign Textview
xText = (TextView) findViewById(R.id.xText);
Button startButton = (Button) findViewById(R.id.startB);
Button stopButton = (Button) findViewById(R.id.stopB);
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
mInitialized = false;
}
public void onResume() {
super.onResume();
sManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
sManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int acc) {
}
public void onSensorChanged(SensorEvent event) {
xText.setText(" X :" + Float.toString(event.values[0]) + "\n" +
" Y :" + Float.toString(event.values[1]) + "\n" +
" Z :" + Float.toString(event.values[2]));
try {
writeToCsv(Float.toString(event.values[0]), Float.toString(event.values[1]), Float.toString(event.values[2]));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.startB:
sManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
break;
case R.id.stopB:
sManager.unregisterListener(this);
break;
}
}
public void writeToCsv(String x, String y, String z) throws IOException {
Calendar c = Calendar.getInstance();
File path = Environment.getDataDirectory();
boolean success = true;
if (!path.exists()) {
success = path.mkdir();
}
if (success) {
String csv = "Value.csv";
FileWriter file_writer = new FileWriter(csv, true);
String s = c.get(Calendar.HOUR) + "," + c.get(Calendar.MINUTE) + "," + c.get(Calendar.SECOND) + "," + c.get(Calendar.MILLISECOND) + "," + x + "," + y + "," + z + "\n";
file_writer.append(s);
file_writer.close();
}
}
}
File path = Environment.getDataDirectory();
Will deliver path /data. Which is not readable and not writable as you have seen. Change to for instance
File path = getFilesDir();

Unfortunately, Organitza't (my app) has stopped

I am getting error message when I start another activity named Task. The application have 4 image buttons (the other buttons image open correctly. When I click "TaskViewer"(ImageButton2) appears the error.
The activity that attempts to open: (ViewTask)
public class ViewTask extends Activity {
protected TaskerDbHelper db;
List<Task> list;
MyAdapter adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
db = new TaskerDbHelper(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.list_inner_view, list);
ListView listTask = (ListView) findViewById(R.id.listView1);
listTask.setAdapter(adapt);
}
public void addTaskNow(View v) {
EditText t = (EditText) findViewById(R.id.editText1);
String s = t.getText().toString();
if (s.equalsIgnoreCase("")) {
Toast.makeText(this, "enter the task description first!!",
Toast.LENGTH_LONG);
} else {
Task task = new Task(s, 0);
db.addTask(task);
Log.d("tasker", "data added");
t.setText("");
adapt.add(task);
adapt.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_view_task, menu);
return true;
}
private class MyAdapter extends ArrayAdapter<Task> {
Context context;
List<Task> taskList = new ArrayList<Task>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<Task> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList = objects;
this.context = context;
}
/**
* This method will DEFINe what the view inside the list view will
* finally look like Here we are going to code that the checkbox state
* is the status of task and check box text is the task name
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBox chk = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_inner_view,
parent, false);
chk = (CheckBox) convertView.findViewById(R.id.chkStatus);
convertView.setTag(chk);
chk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task changeTask = (Task) cb.getTag();
changeTask.setStatus(cb.isChecked() == true ? 1 : 0);
db.updateTask(changeTask);
Toast.makeText(
getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG)
.show();
}
});
} else {
chk = (CheckBox) convertView.getTag();
}
Task current = taskList.get(position);
chk.setText(current.getTaskName());
chk.setChecked(current.getStatus() == 1 ? true : false);
chk.setTag(current);
Log.d("listener", String.valueOf(current.getId()));
return convertView;
}
}
}
The main activity:
public class MainActivity extends Activity {
private Context activity;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
entrarboton();
}
private void entrarboton() {
ImageButton accionentrar = (ImageButton) findViewById(R.id.imageButton0);
accionentrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.android.calendar");
startActivity(LaunchIntent);
}
});
ImageButton accionentrar2 = (ImageButton) findViewById(R.id.imageButton3);
accionentrar2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,Notes.class));
}
});
ImageButton accionentrar3 = (ImageButton) findViewById(R.id.imageButton2);
accionentrar3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,ViewTask.class));
}
});
ImageButton accionentrar4 = (ImageButton) findViewById(R.id.imageButton4);
accionentrar4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,Altres.class));
}
});
AutoCompleteTextView auto = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
String[] noms = getResources() . getStringArray(R.array.noms_array);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, noms);
auto.setThreshold(1);
auto.setAdapter(adapter);
}
}
Android Manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.dppalvaplicacio.app.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.Calendari"
android:label="#string/title_activity_calendari" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.Notes"
android:label="#string/title_activity_notes" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.ViewTask"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.dppalvaplicacio.app.Altres"
android:label="#string/title_activity_altres" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Logcat
Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.dppalvaplicacio.app/databases/taskerManager
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:520)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:263)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.dppalvaplicacio.app.TaskerDbHelper.getAllTasks(TaskerDbHelper.java:70)
at com.dppalvaplicacio.app.ViewTask.onCreate(ViewTask.java:33)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
TaskDbHelper
public class TaskerDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "taskerManager";
// tasks table name
private static final String TABLE_TASKS = "tasks";
// tasks Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TASKNAME = "taskName";
private static final String KEY_STATUS = "status";
public TaskerDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASKNAME
+ " TEXT, " + KEY_STATUS + " INTEGER)";
db.execSQL(sql);
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
// Create tables again
onCreate(db);
}
// Adding new task
public void addTask(Task task) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName()); // task name
// status of task- can be 0 for not done and 1 for done
values.put(KEY_STATUS, task.getStatus());
// Inserting Row
db.insert(TABLE_TASKS, null, values);
db.close(); // Closing database connection
}
public List<Task> getAllTasks() {
List<Task> taskList = new ArrayList<Task>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setStatus(cursor.getInt(2));
// Adding contact to list
taskList.add(task);
} while (cursor.moveToNext());
}
// return task list
return taskList;
}
public void updateTask(Task task) {
// updating row
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASKNAME, task.getTaskName());
values.put(KEY_STATUS, task.getStatus());
db.update(TABLE_TASKS, values, KEY_ID + " = ?",new String[] {String.valueOf(task.getId())});
db.close();
}
}
The problem is in your TaskDBHelper class, and more specifically the onCreate method. This method is called automatically when you try to do work on the database, but the database is not created yet. So it first calls the onCreate method and then the method, that does work on it, in your case - getAllTasks. The problem is that you are closing your db in the onCreate method, preventing any further operations on the database within this class instance. Your method should look like this:
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASKNAME
+ " TEXT, " + KEY_STATUS + " INTEGER)";
db.execSQL(sql);
}

Categories