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));
}
Related
I have a service which registers a shared preference change listener. The shared preference belongs to another app and is world readable. Despite of keeping a global instance of listener as suggested here, My onSharedPreferenceChanged() is not getting called .
The code of the service is as follows:
public class ClientService extends Service {
public static FileObserver observer;
public static final String addr = "127.0.0.1";
public static final int port = 5001;
public Socket socket = null;
InputStream inputStream;
OutputStream outputStream;
String buffer = new String();
OnSharedPreferenceChangeListener listener;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG, "killing service");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG, "Starting Activity");
Context context = null;
/*try {
socket = new Socket(addr, port);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e(MainActivity.TAG, "Error in opening Socket");
}*/
Log.d(MainActivity.TAG,"Carrying on...");
final MyClientTask clientTask = new MyClientTask(addr, port);
SharedPreferences sp = null;
try {
context = getApplicationContext().createPackageContext("net.osmand.plus", Context.MODE_WORLD_WRITEABLE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Log.e(MainActivity.TAG,"OSMAnd Package not found");
}
if(context != null) {
sp = context.getSharedPreferences("net.osmand.settings", Context.MODE_WORLD_READABLE);
Log.d(MainActivity.TAG, ""+sp.getFloat("last_known_map_lat", 0));
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
Log.d(MainActivity.TAG,"Shared preference "+key+" changed");
if(key == "last_known_map_lat" || key == "last_known_map_lon") {
/* Send this via socket */
float data = sharedPreferences.getFloat(key, 0);
Log.d(MainActivity.TAG, "Sending data: "+data);
clientTask.execute(""+data);
}
}
};
sp.registerOnSharedPreferenceChangeListener(listener);
}
observer = new FileObserver("/data/data/net.osmand.plus/shared_prefs/net.osmand.settings.xml" ) {
#Override
public void onEvent(int event, String path) {
// TODO Auto-generated method stub
if(event == FileObserver.MODIFY) {
Log.d(MainActivity.TAG, "Changed");
}
}
};
return super.onStartCommand(intent, flags, startId);
}
public class MyClientTask extends AsyncTask<String, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(String... buffer) {
try {
byte[] bytes = buffer[0].getBytes();
//outputStream.write(bytes);
Log.d(MainActivity.TAG, "blah");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
The shared preference related code is in onStartCommand().
Anyone has any clue what is wrong ?
Note that in the actual Sharedpreferences file, I can observe the value changing when I see using adb shell
context = getApplicationContext().createPackageContext("net.osmand.plus", Context.MODE_WORLD_WRITEABLE);
your context is null
your con just use "this" service is itself a context
or you can try getSharedPreferences("net.osmand.settings", Context.MODE_WORLD_READABLE);
It seems from this post that what I am trying to do is unsupported in Android. WORLD_READABLE flag for SharedPreferences does not support multi-thread support which might be causing the inconsistencies. In the Android developer site also it is mentioned that multiple process support for SharedPreferences is not available for WORLD_READABLE preferences.
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 want to send text file to dropbox but it is showing DropboxUnlinkedException.
Solution ::
First, let your program get fully authenticated. Just after mDBApi.getSession.startAuthentication() method, onResume method will get called automatically. Let the full authentication get completed and then do what do you want to do.
MainActivity
public class MainActivity extends Activity implements LocationListener{
TextView date;
TextView lati;
TextView longi;
Button b1;
private DropboxAPI<AndroidAuthSession> mDBApi;
private LocationManager locationManager;
private String provider;
final static public String ACCOUNT_PREFS_NAME = "GPS_File";
final static public String APP_KEY = "5qiq4z06ikagxfb";
final static public String APP_SECRET = "f6mbf1hnn0re2ni";
final static public AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
boolean mIsLoggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
//this is start authentication
mDBApi.getSession().startAuthentication(MainActivity.this);
//after this it will call onResume
date = (TextView)findViewById(R.id.textView2);
lati = (TextView)findViewById(R.id.textView4);
longi = (TextView)findViewById(R.id.textView6);
b1 = (Button)findViewById(R.id.button1);
createFile("abcd", "12345", "54321");
toDropbox();
setLoggedIn(mDBApi.getSession().isLinked());
}
void createFile(String str1,String str2,String str3)
{
String data = str1+"\t"+str2+"\t"+str3;
try{
File myFile = new File("/sdcard/DropboxFile1.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
}
catch(Exception e)
{e.printStackTrace();}
}
void toDropbox()
{
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/DropboxFile1.txt";
File file = new File(filePath);
mDBApi.getSession().startAuthentication(MainActivity.this);
try {
mDBApi.putFileOverwrite(filePath, new FileInputStream(file), file.length(), null);
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
//This get call after StartAuthentication..
protected void onResume() {
super.onResume();
AndroidAuthSession session = mDBApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(true);
} catch (IllegalStateException e) {
//Keep this toast.. It will show you the completed authentication..
Toast.makeText(getBaseContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.i("Dropbox", "Error authenticating", e);
}
}
}
private void storeKeys(String key, String secret) {
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(APP_KEY, key);
edit.putString(APP_SECRET, secret);
edit.commit();
}
public void setLoggedIn(boolean loggedIn) {
mIsLoggedIn = loggedIn;
}
public boolean isLoggedIn() {
return mIsLoggedIn;
}
#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;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}//MainActivity Ends..`
`
After authentication get completed do your another stuff.
You're calling startAuthentication but then immediately trying to call API methods (before authentication has actually happened). You can only use the API once the user has authenticated. In your code, here's the part that runs after the user has authenticated and returns to your app:
protected void onResume() {
...
if (session.authenticationSuccessful()) {
...
This error might also come when you miss calling this in onResume() of your activity :
mDBApi.getSession().finishAuthentication();
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
I have trouble using thread.join in my code below. It should wait for the thread to finish before executing the codes after it, right? It was behaving differently on different occasions.
I have three cases to check if my code goes well
App is used for the first time - works as expected but the loading page don't appear while downloading
App is used the second time (db is up to date) - works okay
App is used the third time (db is outdated, must update) - won't update, screen blacks out, then crashes
I think I have problems with this code on onCreate method:
dropOldSchedule();
dropThread.join();
triggerDownload();
Based on the logs, the code works until before this part... What can be the problem?
MainActivity.java
public class MainActivity extends Activity {
final static int INDEX_ACCTTYPE = 0;
final static int INDEX_ECN = 1;
final static int INDEX_TLN = 2;
final static int INDEX_SIN = 3;
final static int INDEX_MOBILE = 4;
final static int INDEX_CITY = 5;
final static int INDEX_START_DATE = 6;
final static int INDEX_START_TIME = 7;
final static int INDEX_END_DATE = 8;
final static int INDEX_END_TIME = 9;
final static int INDEX_REASON = 10;
final static int INDEX_DETAILS = 11;
DatabaseHandler db;
String str;
ProgressDialog pd;
TextView homeText1, homeText2, homeText3, homeText4;
final private String csvFile = "http://www.meralco.com.ph/pdf/pms/pms_test.csv";
final private String uploadDateFile = "http://www.meralco.com.ph/pdf/pms/UploadDate_test.txt";
Thread dropThread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.dropOldSchedule();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
db.close();
pd.dismiss();
}
});
}
});
Thread getUploadDateThread = new Thread(new Runnable() {
public void run() {
try {
URL myURL = new URL(uploadDateFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
str = output;
}
else {
break;
}
}
so.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
pd.dismiss();
}
});
}
});
Thread downloadThread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL url = new URL(csvFile);
Log.i("dl", "start");
InputStream input = url.openStream();
CSVReader reader = new CSVReader(new InputStreamReader(input));
Log.i("dl", "after reading");
String [] sched;
while ((sched = reader.readNext()) != null) {
if(sched[INDEX_CITY].equals("")) sched[INDEX_CITY]="OTHERS";
try {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
sched[INDEX_DETAILS], sched[INDEX_REASON]);
} catch (IndexOutOfBoundsException e) {
db.addRow(sched[INDEX_SIN], sched[INDEX_CITY],
sched[INDEX_START_DATE], sched[INDEX_START_TIME],
sched[INDEX_END_DATE], sched[INDEX_END_TIME],
"", sched[INDEX_REASON]);
//e.printStackTrace();
}
}
input.close();
Log.i("dl", "finished");
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
writeUploadDateInTextFile();
}
});
#SuppressWarnings("unqualified-field-access")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pms_main);
Button home = (Button) findViewById(R.id.home);
home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MeralcoSuite_TabletActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
homeText1 = (TextView) findViewById(R.id.home_text1);
homeText2 = (TextView) findViewById(R.id.home_text2);
homeText3 = (TextView) findViewById(R.id.home_text3);
homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
getUploadDate();
try {
getUploadDateThread.join(); //wait for upload date
Log.d("getUploadDate","thread died, upload date=" + str);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
db.close();
if(!uploadDateEqualsDateInFile()){
dropOldSchedule();
dropThread.join();
triggerDownload();
}
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
triggerDownload();
showDisclaimer();
Log.i("oncreate", "finished!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void dropOldSchedule(){
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
dropThread.start();
}
public void triggerDownload() {
if (!checkInternet()) {
showAlert("An internet connection is required to perform an update, please check that you are connected to the internet");
return;
}
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
downloadThread.start();
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing())
pd.setTitle("Getting upload date...");
else
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
getUploadDateThread.start();
}
public void writeUploadDateInTextFile() {
Log.d("writeUploadDateTextFile", "writing:"+str);
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
"update.txt", 0));
out.write(str);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public void showDisclaimer() {
Log.d("ShowDisclaimer", "showing disclaimer");
homeText3
.setText("..." + str
+ "...");
homeText1.setVisibility(View.VISIBLE);
homeText2.setVisibility(View.VISIBLE);
homeText3.setVisibility(View.VISIBLE);
homeText4.setVisibility(View.VISIBLE);
Log.d("showDisclaimer", "finished showing disclaimer");
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
try {
String recordedDate = "";
InputStream instream = openFileInput("update.txt");
if (instream != null) { // if file the available for reading
Log.d("uploadDateEqualsDateInFile","update.txt found!");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line = null;
while ((line = buffreader.readLine()) != null) {
recordedDate = line;
Log.d("uploadDateEqualsDateInFile","recorded:"+recordedDate);
}
Log.d("uploadDateEqualsDateInFile","last upload date: " + str + ", recorded:" +recordedDate);
if(str.equals(recordedDate)) return true;
return false;
}
Log.d("uploadDateEqualsDateInFile","update.txt is null!");
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean checkInternet() {
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo infos[] = cm.getAllNetworkInfo();
for (NetworkInfo info : infos)
if (info.getState() == NetworkInfo.State.CONNECTED
|| info.getState() == NetworkInfo.State.CONNECTING) {
return true;
}
return false;
}
public boolean dbExists() {
File database=getApplicationContext().getDatabasePath(DatabaseHandler.DATABASE_NAME);
if (!database.exists()) {
Log.i("Database", "Not Found");
return false;
}
Log.i("Database", "Found");
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
if (db != null) {
db.close();
}
}
#Override
protected void onPause() {
super.onPause();
if (db != null) {
db.close();
}
}
}
Sorry but I couldn't find mistakes or problems in your code. But I would strongly recommend you to use AsyncTask for doing something in different thread. AsyncTask is very easy to use and I would say that it is one of the biggest advantages of java. I really miss it in obj-c.
http://labs.makemachine.net/2010/05/android-asynctask-example/
http://marakana.com/s/video_tutorial_android_application_development_asynctask_preferences_and_options_menu,257/index.html
check those links hope that will help you.
It was already mentioned that AsyncTask is the better alternative. However, it may be the case, that your call to join will throw InterruptedException. Try to use it like this:
while(getUploadDateThread.isRunning()){
try{
getUploadDateThread.join();
} catch (InterruptedException ie){}
}
// code after join
I think the problem that your facing is that you are blocking the UI thread when you call join in the onCreate() method. You should move this code into another thread which should execute in the background and once its done you can update the UI.
Here is a sample code:
final Thread t1 = new Thread();
final Thread t2 = new Thread();
t1.start();
t2.start();
new Thread(new Runnable() {
#Override
public void run() {
// Perform all your thread joins here.
try {
t1.join();
t2.join();
} catch (Exception e) {
// TODO: handle exception
}
// This thread wont move forward unless all your threads
// mentioned above are executed or timed out.
// ------ Update UI using this method
runOnUiThread(new Runnable() {
#Override
public void run() {
// Update UI code goes here
}
});
}
}).start();