I'm loading a text file into an EditText but the file only gets partially loaded. I've tried two different files and get the same result. One file gets cut off halfway through line 35 and the other line 37. No idea why.
<com.mobilewebtoolkit.EditTextLineNumbers
android:id="#+id/ide"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:gravity="left"
android:inputType="textMultiLine"
android:lineSpacingExtra="5dp"
android:textSize="15sp"
android:visibility="visible" >
code:
private void openFile(final File aFile) {
String nullChk = et.getText().toString();
if (!changed || nullChk.matches("")) {
try {
currentFile = aFile;
getExt();
et.setText(new Scanner(currentFile).useDelimiter("\\Z").next());
changed = false;
exists = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save first?");
alert.setMessage("(Will be saved in the current working directory)");
alert.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String temptxt = et.getText().toString();
if (currentFile.exists()) {
try {
saveFile(currentFile.getPath(), temptxt);
currentFile = aFile;
getExt();
} catch (NullPointerException e) {
Log.i("NullPointer", currentFile.getName());
}
try {
et.setText(new Scanner(currentFile)
.useDelimiter("\\Z").next());
getExt();
if (extension.equals("txt")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("html")
|| extension.equals("htm")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("css")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("js")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("php")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
} else if (extension.equals("xml")) {
Toast.makeText(MainActivity.this,
"Extension: " + extension,
Toast.LENGTH_LONG).show();
}
changed = false;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
saveAs(null);
}
}
});
final File tempFile = aFile;
alert.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
try {
et.setText(new Scanner(tempFile).useDelimiter(
"\\Z").next());
changed = false;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
changed = false;
}
});
alert.setNeutralButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
changed = true;
dialog.cancel();
}
});
alert.show();
}
}
You should iterate over your Scanner until hasNext() return false to make sure the whole file is read. See more information here: Beware of using java.util.Scanner with ā/zā
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(tempFile).useDelimiter("\\Z");
while (scanner.hasNext()) {
sb.append(scanner.next());
}
et.setText(sb);
Related
I have this android app which connects to an mqtt broker and listens for instructions to play/pause a ringtone or open/close the flashlight.
It runs as supposed to until i change my settings and call the function flashOnOff after this. Then i get a null pointer exception but i can not understand why.
This is my code (i did not include my imports to save some space):
public class MainActivity extends AppCompatActivity {
// Layout related parameters
Toolbar myToolbar;
Spinner mySpinner;
ImageButton flashlightButton;
Button ringtone;
EditText message;
// Camera/flashlight related parameters
Camera camera;
Camera.Parameters parameters;
// MQTT related parameters
private String BrokerIp = "tcp://192.168.1.3:1883";
private int qos = 2;
static String Username = "user1";
static String Password = "user1";
String topicStr = "commands";
String clientId = "AndroidClient";
MqttConnectOptions options;
MqttAndroidClient client;
Vibrator vibrator;
// Ringtone related parameters
Ringtone myRingtone;
MediaPlayer ringtoneMP ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
myRingtone = RingtoneManager.getRingtone(getApplicationContext(),uri);
myToolbar = (Toolbar) findViewById(R.id.toolbar);
mySpinner = (Spinner) findViewById(R.id.spinner);
flashlightButton = (ImageButton) findViewById(R.id.image);
myToolbar.setLogo(R.drawable.twoguyswatchmrrobot);
myToolbar.setTitle(getResources().getString(R.string.app_name));
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_itam,
getResources().getStringArray(R.array.Toolbar_dropdown_entries));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(myAdapter);
ringtoneMP = MediaPlayer.create(this,R.raw.games_of_thrones);
ringtone = (Button) this.findViewById(R.id.ringtone);
message = (EditText)findViewById(R.id.messagePublish);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,
mySpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT)
.show();
if (mySpinner.getSelectedItem().toString().equals("Exit App")){
exit();
}else if(mySpinner.getSelectedItem().toString().equals("Settings"))
{
Intent intent;
intent = new Intent(MainActivity.this, SettingsActivity.class);
intent.putExtra("CURRENT_IP",client.getServerURI());
intent.putExtra("CURRENT_QOS", Integer.toString(qos));
intent.putExtra("CURRENT_TOPIC",topicStr);
startActivityForResult(intent,1); // this is so we can take the results back to mainActivity later
}else{
System.out.println("ara3e, den exw diale3ei tipota");
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
//Flashlight on Create start
if(isFlashAvailable()) // check if flash is available on this device, if it is open camera (module) and make button clickable
{
camera = Camera.open();
parameters = camera.getParameters();
}else
{ // if flashlight is not supported dont let the user click the button
flashlightButton.setEnabled(false);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error.");
builder.setMessage("Flashlight not available on this device. \nExit?"); // inform the user and let him choose how to continue
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
exit();
}
});
builder.setNegativeButton("Stay without flashlight", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
flashlightButton.setOnClickListener(new View.OnClickListener() { // listen for flash button clicks
#Override
public void onClick(View view) {
flashOnOff();
}
});
ringtone.setOnClickListener(new View.OnClickListener() { // Ringtone listener
#Override
public void onClick(View view) {
ringtoneOnOff(ringtoneMP);
}
});
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
// client = pahoMqttClient.getMqttClient(MainActivity.this,BrokerIp,clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
Log.d("Connection:"," Lost");
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.d("Delivery"," completed with iMqttDeliveryToken: " + iMqttDeliveryToken);
}
});
}
//Flashlight start
#Override
protected void onStop() {
super.onStop();
if(camera!=null)
{
camera.release();
camera = null;
}
}
//Flashlight end
//Backkey exit confirmation
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit application?")
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
// when yes is clicked exit the application
public void onClick(DialogInterface arg0, int arg1) {
exit();
}
})
.setNegativeButton("No", new
DialogInterface.OnClickListener() {
// when no is clicked do nothing
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
//Backkey end
// PUBLISH MESSAGE
private void setSubscription(MqttAndroidClient client, String topic, int qos){
try{
client.subscribe(topic, qos);
}
catch (MqttException e){
e.printStackTrace();
}
}
private void unsetSubscription(MqttAndroidClient client,String topic){
try{
client.unsubscribe(topic);
}catch (MqttException e){
e.printStackTrace();
}
}
public void conn(View v){
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
// pub();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "not connected", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconn(View v){
if (client.isConnected()) {
try {
IMqttToken token = client.disconnect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "could not disconnect", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}else {
Toast.makeText(MainActivity.this, "Client is already disconnected", Toast.LENGTH_LONG).show();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void pub(View v) {
String topic = topicStr;
try {
client.publish(topic, String.valueOf(message.getText()).getBytes(),qos,false);
} catch (MqttException e) {
e.printStackTrace();
}
}
private void ringtoneOnOff(MediaPlayer ringtoneMP){
if (ringtoneMP.isPlaying()){
ringtoneMP.pause();
}else{
ringtoneMP.start();
}
}
private void myMessageArrived(String s,MqttMessage mqttMessage){
if ((mqttMessage.toString()).equals("Flash on")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Flashlight already on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Turning flashlight on", Toast.LENGTH_SHORT).show();
flashOnOff();
}
} else if ((mqttMessage.toString()).equals("Flash off")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Turning flashlight off", Toast.LENGTH_SHORT).show();
flashOnOff();
} else {
Toast.makeText(MainActivity.this, "Flashlight already off", Toast.LENGTH_SHORT).show();
}
} else if ((mqttMessage.toString()).equals("Ringtone on")) {
if (ringtoneMP.isPlaying()) {
Toast.makeText(MainActivity.this, "Ringtone already playing", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Playing ringtone", Toast.LENGTH_SHORT).show();
ringtoneMP.start();
}
} else if ((mqttMessage.toString()).equals("Ringtone off")) {
if (ringtoneMP.isPlaying()) {
ringtoneMP.pause();
} else {
Toast.makeText(MainActivity.this, "Ringtone already not being played", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("INFO:", "This Command does not exist");
}
vibrator.vibrate(500);
myRingtone.play();
}
public void exit(){
finish();
System.exit(0);
}
public boolean isFlashAvailable(){ // boolean function that returns true if flash is supported on this device
return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
public void flashOnOff(){ // self explanatory
if (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH)){ // if the flash is on torch mode
Log.d("BHKE","408");
this.flashlightButton.setImageResource(R.drawable.off);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // turn it off
}else{
Log.d("BHKE","412");
this.flashlightButton.setImageResource(R.drawable.on);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); // else turn it on
}
this.camera.setParameters(this.parameters);
this.camera.startPreview();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String tempBrokerIp;
String temptopic="";
Integer tempqos;
Boolean BrokerIpChanged = true;
Boolean qosChanged = true;
Boolean topicChanged = true;
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (1) : {
if (resultCode == Activity.RESULT_OK) {
tempBrokerIp = data.getStringExtra("CURRENT_IP");
tempqos = Integer.parseInt(data.getStringExtra("CURRENT_QOS"));
temptopic = data.getStringExtra("CURRENT_TOPIC");
Log.d("Info BROKER, TOPIC, QOS", ":"+ tempBrokerIp+ " " + temptopic+ " " + tempqos);
if (tempBrokerIp.equals(BrokerIp)) {
BrokerIpChanged=false;
Log.i("BrokerIpChanged =", BrokerIpChanged.toString());
}
if (tempqos.equals(qos)) {
qosChanged=false;
Log.i("qosChanged =", qosChanged.toString());
}else {
qos = tempqos;
}
if (temptopic.equals(topicStr)){
topicChanged=false;
Log.i("topicChanged =", topicChanged.toString());
}else{
topicStr = temptopic;
}
if (!BrokerIpChanged && !qosChanged && !topicChanged) return;
if (BrokerIpChanged){
try {
client.disconnect();
BrokerIp = tempBrokerIp;
topicStr = temptopic;
qos = tempqos;
// final String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
// options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1); // to user the latest mqtt version
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
Log.w("Mqtt","Connected to:"+ BrokerIp);
try{
Log.v("INFO 11111:", "about to subscribe with: "+ topicStr + qos);
client.subscribe(topicStr,qos);
}catch (MqttException e){
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
System.out.println(client.isConnected());
// if (client.isConnected()){
// Log.v("INFO 22222:", "about to subscribe with: "+ temptopic + tempqos);
// client.subscribe(temptopic,tempqos);
// }
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}catch (MqttException e){
e.printStackTrace();
}
}else
{
try {
client.unsubscribe(topicStr);
client.subscribe(temptopic,tempqos);
topicStr = temptopic;
qos = tempqos;
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public boolean isFlashOn(){
return (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH));
}
I can provide the settings activity code too is needed
It seems that the two variables needed for the flashOnOff where not initiallized after i returned from the settings activity.
Ī added :
if (isFlashAvailable()){
camera = Camera.open();
parameters = camera.getParameters();
}
at the onActivityResult start and it works like a charm.
I have listview with three viewholders one for image one for video one for audio
In videholder i have listview in which I am showing thumbnail of video if it downloaded.Its working fine but when i scroll then that thumbnail set on another imageview too.
mConvertView = convertView;
chatMessage=chatMessages.get(position);
final TextViewHolder mTextViewHolder;
final ImageViewHolder mImageViewHolder;
final AudioViewHolder mAudioViewHolder;
Object object=chatMessages.get(position);
// mHandler = new Handler();
disply = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.displayer(new RoundedBitmapDisplayer(20)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).defaultDisplayImageOptions(disply).build();
ImageLoader.getInstance().init(config);
rd = new RecordBaseHandler(context);
if(chatMessage.getAssetsId() != null)
{
if(chatMessage.getType().equalsIgnoreCase("audio"))
{
Log.d("Node", "Item position is "+chatMessages.get(position));
mAudioViewHolder = getAudioViewHolder(mConvertView);
mAudioViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mAudioViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mAudioViewHolder, false);
mAudioViewHolder.play.setTag(position);
mAudioViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mycontent = chatMessage.getProperty("content-type");
try {
Cursor rs = rd.getData(chatMessage.getAssetsId());
rs.moveToFirst();
filepath = rs.getString(rs.getColumnIndex("file_path"));
Log.d("Node", "FINALLY FILE PATH IS " + filepath);
if (!rs.isClosed()) {
rs.close();
}
if (filepath != null) {
mAudioViewHolder.download.setVisibility(View.GONE);
} else {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.download.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
// TODO: handle exception
Log.d("Node", "EXECPTIOn " + e);
}
mAudioViewHolder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Node: ", "Reading all contacts..");
List<RecordModel> contacts = rd.getAllContacts();
for (RecordModel cn : contacts) {
String log = "Id: "+ cn.getId()+ " ,Name: "+ cn.getAttch_id()+ " ,Phone: " + cn.getFile_path();
Log.d("Node: ",log);
}
// File tempMp3 = File.createTempFile("record", ".mp3", f);
new Thread()
{
public void run() {
File tempMp3 = null;
try {
tempMp3 = File.createTempFile("record", ".mp3",Environment.getExternalStorageDirectory());
} catch (IOException e) {
e.printStackTrace();
}
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "smb_" + System.currentTimeMillis() + "_audio.mp3");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY"+tempMp3);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
context.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "file downloaded successfully", Toast.LENGTH_LONG).show();
mAudioViewHolder.download.setVisibility(View.GONE);
}
});
rd.addContact(new RecordModel(chatMessage.getAssetsId(), audioFileName));
};
}.start();
}
});
mAudioViewHolder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.GONE);
mAudioViewHolder.pause.setVisibility(View.VISIBLE);
Log.d("DATA", "currently playing " + position);
playingAudioPosition = position;
Object tag = mAudioViewHolder.play.getTag();
// Here we get the position that we have set for the checkbox using setTag.
String str=chatMessage.getAssetsId();
Cursor rs = rd.getData(str);
rs.moveToFirst();
try
{
filepath = rs.getString(rs.getColumnIndex("file_path"));
}
catch(Exception e)
{
Toast.makeText(mConvertView.getContext(), "File is not downloaded", Toast.LENGTH_LONG).show();
}
Log.d("Node", "file path for id "+ str + "is "+ filepath);
if (!rs.isClosed()) {
rs.close();
}
if(filepath==null) //we check whether file is present or not
{
Toast.makeText(mConvertView.getContext(), "File is Not downloaded", Toast.LENGTH_SHORT).show();
((View)v.getParent()).findViewById(R.id.btndn).setVisibility(View.VISIBLE);
// mAudioViewHolder.download.setVisibility(mConvertView.VISIBLE);
}
else {
((View) v.getParent()).findViewById(
R.id.chat_audio_progress_bar)
.setVisibility(View.VISIBLE);
// mAudioViewHolder.progressBar.setVisibility(mConvertView.VISIBLE);
mediaPlayer = new MediaPlayer();
String yofile = "file://" + filepath;
mediaPlayer
.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(yofile);
} catch (IllegalArgumentException
| SecurityException
| IllegalStateException | IOException e) {
// TODO Auto-generated catch block
Log.e("Node", "ERRORSS Part 1 is" + e);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
mAudioViewHolder.isPlaying = false;
/**
* since audio is stop
* playing, remove its
* position value
* */
playingAudioPosition = -1;
}
});
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Node", "ERRORSS is Part 2 " + e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
isMediaReleased = false;
mAudioViewHolder.progressBar.setMax(mediaPlayer.getDuration());
updateSeekBar();
}
}
});
mAudioViewHolder.pause
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAudioViewHolder.play.setVisibility(View.VISIBLE);
mAudioViewHolder.pause.setVisibility(View.GONE);
mediaPlayer.stop();
}
});
}
if (chatMessage.getType().equalsIgnoreCase("image") || chatMessage.getType().equalsIgnoreCase("photo"))
{
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is Image position is "+chatMessages.get(position));
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
if (chatMessage.getProperty("localfile") != null) {
imageUri1 = chatMessage.getProperty("localfile");
String status = chatMessage.getProperty("isUpload");
imageUri2 = "file://" + imageUri1;
Log.d("Node", "This time from local");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
//
// Log.d("Node", "IMAGEURI is : " + imageUri2
// + "And status is " + status);
} else {
Log.d("Node", "Here we are now else");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "This is Image",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context,
ShowImgActivity.class);
String urll = chatMessage.getUrl();
Bitmap bitmap = mImageViewHolder.myimageview.getDrawingCache();
intent.putExtra("URL", urll);
intent.putExtra("BitmapImage", bitmap);
context.startActivity(intent);
}
});
}
//if aatchmnet is video then do this
else if (chatMessage.getType().equalsIgnoreCase("video")) {
mImageViewHolder = getImageViewHolder(mConvertView);
mImageViewHolder.mChatmessage=chatMessage;
// TODO change below code
if(chatMessage.getSenderId() != null)
setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mImageViewHolder, false);
mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
// Log.d("Node1", "This time from local videos");
if (chatMessage.getVideo_thumb() != null) {
Log.i("Node", "Yes this video has thumbnail");
Bitmap bitmp = StringToBitMap(chatMessage.getProperty("video_thumb"));
if (bitmp != null) {
mImageViewHolder.myimageview.setImageBitmap(bitmp);
} else {
mImageViewHolder.myimageview
.setImageResource(R.drawable.vids);
}
} else {
Log.i("Node", "Yes this dont have thumbanil");
ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
mImageViewHolder.myimageview, disply);
}
mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final ImageView imageThumbnail = (ImageView)v;
final Handler handler=new Handler() {
public void handleMessage(Message msg) {
Log.e("", "handeler bmVideoThumbnail"+bmVideoThumbnail);
if (bmVideoThumbnail!=null) {
imageThumbnail.setImageBitmap(bmVideoThumbnail);
}
};
};
new Thread()
{
public void run() {
//We are creating folder first using mkdir
File f = new File(Environment.getExternalStorageDirectory()+ "/smbchat/");
if(!f.exists()){
f.mkdirs();
}
//then we want to store downloded file in that folder
File output = new File(f, "VID_" + System.currentTimeMillis() + "_video.mp4");
Log.d("Node", "URL VALUE "+chatMessage.getUrl());
HttpRequest.get(chatMessage.getUrl()).receive(output);
audioFileName=String.valueOf(output);
Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
donloadedVideoUri= "file://" + audioFileName;
Log.e("Node", "donloadedVideoUri INSIDE THREAD------"+donloadedVideoUri);
bmVideoThumbnail=ThumbnailUtils.createVideoThumbnail(audioFileName, android.provider.MediaStore.Video.Thumbnails.MICRO_KIND);
Log.e("Node", "bmVideoThumbnail---------"+bmVideoThumbnail);
if(bmVideoThumbnail !=null)
handler.sendEmptyMessage(0);
};
}.start();
// String uriString = chatMessage.getUrl();
// Uri intentUri = Uri.parse(uriString);
//
// Intent intent2 = new Intent();
// intent2.setAction(Intent.ACTION_VIEW);
// intent2.setDataAndType(intentUri, "video/*");
// context.startActivity(intent2);
}
});
}
}
else {
mTextViewHolder = getTextViewHolder(mConvertView);
mTextViewHolder.mChatmessage=chatMessage;
Log.d("Node", "this is text position is "+chatMessages.get(position));
//TODO redo following logic
if(chatMessage.getSenderId() != null)
setAlignment(mTextViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
else
setAlignment(mTextViewHolder, false);
mTextViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));
mTextViewHolder.txtMessage.setText(chatMessage.getBody());
mTextViewHolder.message = chatMessage;
}
return mConvertView;
Use one ViewHolder and define three fields and show hide views according status.
Maintain Status in list not in adapter.
Because list item recreated on list view scroll.
You can see same thumbnail in multiple list items as Android reuses the view of list item.
Care needs to be taken that you make the thumbnail invisible or use 'Icon which suggests no image' if you don't have the correct image for that position of list item. This check has to be made in getView method of your adapter of the list.
I understand that a similar question has been asked but I am seriously stuck on this problem.
When I close the application, it says "Saving Data" which means my on stop method is being called but when I re open the app, it fails to mention that it is "getting data" meaning my onStart method is not being called.
The middle block of code seems to be the most important, I just wanted to include all of it so that if someone were to bump into my situation again, they could see everything.
How do I use the sharedpreferences class in this situation to save the background color and call the onStart method when I reopen the application?
As of now, it always resorts to the default Colour.
Thank you for your time.
EditText ed;
String background_color;
String Color_Value;
String Message;
int datablock =100;
int selectedItem;
int Color_Position;
int change=0;
View root;
View someView;
SharedPreferences prefer;
SharedPreferences.Editor prefer_edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);
ActionBar bar = getActionBar();
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
//Hides app title and icon
if (Color_Value!= null){
onStart();
}
else {
}
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//Creates a spinner
ed = (EditText)findViewById(R.id.edit);
final String[] dropdown = getResources().getStringArray(R.array.Colors);
ArrayAdapter <String> adapter = new ArrayAdapter<String>(bar.getThemedContext(),
android.R.layout.simple_spinner_item,android.R.id.text1,dropdown);
//sets up the drop down navigation list in the action bar
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bar.setListNavigationCallbacks(adapter, new OnNavigationListener(){
#Override
public boolean onNavigationItemSelected(int selectedItem, long arg1) {
//Java always starts counting at zero
if (selectedItem == 0){
someView = findViewById(R.id.layout);
root = someView.getRootView();
root.setBackgroundColor((Color.parseColor("#005640")));
Color_Position =Color.parseColor("#005640");
//prefer_edit.putInt("background_color", ((Color.parseColor("#005640"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 1){
someView = findViewById(R.id.layout);
root = someView.getRootView();
root.setBackgroundColor((Color.parseColor("#045345")));
Color_Position =Color.parseColor("#045345");
//prefer_edit.putInt("background_color", ((Color.parseColor("#045345"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 2){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#384355");
root.setBackgroundColor((Color.parseColor("#384355")));
//prefer_edit.putInt("background_color", ((Color.parseColor("#384355"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 3){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#990088");
root.setBackgroundColor((Color.parseColor("#990088")));
//prefer_edit.putInt("background_color",((Color.parseColor("#990088"))));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
else if (selectedItem == 4){
someView = findViewById(R.id.layout);
root = someView.getRootView();
Color_Position =Color.parseColor("#026211");
root.setBackgroundColor((Color.parseColor("#026211")));
// prefer_edit.putInt("background_color", (Color.parseColor("#026211")));
Toast.makeText(getBaseContext(), "Color Changed", Toast.LENGTH_SHORT).show();
Log.i("At", "Position "+selectedItem);
}
return true;
}
});
}
public void onStart(){
super.onStart();
Log.i("Getting Data", "Color is equal to "+Color_Position);
SharedPreferences prefer = getSharedPreferences(Color_Value,0);
prefer.getInt(background_color, 0);
}
public void onStop(){
super.onStop();
Log.i("Saving Data", "Color is equal to "+Color_Position);
SharedPreferences prefer = getSharedPreferences(Color_Value, 0);
SharedPreferences.Editor prefer_edit = prefer.edit();
prefer_edit.putInt(background_color, Color_Position);
prefer_edit.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check_box, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case
R.id.action_settings:
//Pass data between activities here
break;
case
R.id.action_save:
SaveData();
break;
case
R.id.action_error:
LoadData();
break;
case
R.id.action_edit:
ChangeTextColor(change);
change++;
break;
}
return true;
}
public void SaveData(){
Message =ed.getText().toString();
try {
FileOutputStream out = openFileOutput("text.txt", MODE_PRIVATE);
OutputStreamWriter output = new OutputStreamWriter(out);
try{
output.write(Message);
output.flush();
output.close();
Toast.makeText(getBaseContext(), "Save successful", Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void LoadData(){
try {
FileInputStream fis = openFileInput("text.txt");
InputStreamReader ins = new InputStreamReader(fis);
//Deserialize the file
char[] Data = new char [datablock];
String final_data ="";
int size;
try {
while((size = ins.read(Data))>0){
String read_data = String.copyValueOf(Data, 0 ,size);
final_data+=read_data;
Data = new char[datablock];
}
Toast.makeText(getBaseContext(), "Message : " + final_data, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Methods galore!
public void ChangeTextColor(int change){
if ((change % 2) == 0) {
// number is even
ed.setHint("enter a message to save");
ed.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Toast.makeText(getApplicationContext(), "Text color changed to red", Toast.LENGTH_LONG).show();
change++;
}
else {
// number is odd
ed.setHint("enter a message to save");
ed.setTextColor(getResources().getColor(android.R.color.black));
Toast.makeText(getApplicationContext(), "Text color changed to black", Toast.LENGTH_LONG).show();
change++;
}
}
}
onStart is called after onCreate, please remove this
if (Color_Value!= null){
onStart();
}
else {
}
and you can retrieve the color fron SharedPreferences directly in onCreate.
hi advances i need your help, please. i have URI code
Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse("http://xxx/dev/android/ATMnet-Mobile_v1.1_vc2.apk"));
i wanna change the last URI with variable like this
Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse("http://xxx/dev/android/ATMnet-Mobile_v1.1_vc"+stringText+".apk"));
so, the version code (vc) can modified by variable which i write
and this is my full code, anyone could correct my code?
URL textUrl;
String StringBuffer;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
while ((StringBuffer = bufferReader.readLine()) != null)
{
stringText += StringBuffer;
}
bufferReader.close();
//textServer.setText(stringText);
} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
//textServer.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//textServer.setText(e.toString());
}
PackageManager manager = getPackageManager();
PackageInfo info;
try {
info = manager.getPackageInfo(getPackageName(), 0);
int version = info.versionCode;
if(Integer.parseInt(stringText) != version)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle(""+stringText+" "+version+" is Available.");
alertDialogBuilder
.setMessage("Do you want to download?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse("http://xxx/dev/android/ATMnet-Mobile_v1.1_vc2.apk"));
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
} catch (NameNotFoundException e)
{
e.printStackTrace();
}
i hope anyone can help me :'(
There is no problem in changes. Concatination avaliable and it works fine.
Use
Uri.parse("something" + str + ".apk")
Good luck!
I am having problems making my TextViews visible from another thread using the method showDisclaimer(). I have used runOnUiThread() to set the visibility of my TextViews. Basically, I want to show these views after importing the csv to the database. Can you take a look and see what I missed?
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;
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";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView homeText1 = (TextView) findViewById(R.id.home_text1);
TextView homeText2 = (TextView) findViewById(R.id.home_text2);
TextView homeText3 = (TextView) findViewById(R.id.home_text3);
TextView homeText4 = (TextView) findViewById(R.id.home_text4);
homeText1.setVisibility(View.INVISIBLE);
homeText2.setVisibility(View.INVISIBLE);
homeText3.setVisibility(View.INVISIBLE);
homeText4.setVisibility(View.INVISIBLE);
//db = new DatabaseHandler(MainActivity.this);
if(dbExists()){
db = new DatabaseHandler(MainActivity.this);
Log.d("Count", "" + db.count());
if(!uploadDateEqualsDateInFile())
promptOptionalUpdate("There is a new schedule");
showDisclaimer();
Log.i("oncreate", "finished!");
return;
}
promptRequiredUpdate("Schedule not updated");
//showDisclaimer();
Log.i("oncreate", "finished!");
}
public void promptOptionalUpdate(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
dropOldSchedule();
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void dropOldSchedule(){
//TODO drop old schedule
}
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.dismiss();
pd = ProgressDialog.show(this, "Downloading schedule",
"This may take a few minutes...", true, false);
Thread thread = new Thread(new Runnable() {
public void run() {
db = new DatabaseHandler(MainActivity.this);
db.beginTransaction();
try {
URL myURL = new URL(csvFile);
BufferedReader so = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (true) {
String output = so.readLine();
if (output != null) {
String[] sched = output.split(",");
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();
}
}
else {
break;
}
}
so.close();
} catch (MalformedURLException e) {
e.printStackTrace();
db.endTransaction();
} catch (IOException e) {
e.printStackTrace();
db.endTransaction();
}
Log.d("Count", ""+db.count());
db.setTransactionSuccessful();
db.endTransaction();
runOnUiThread(new Runnable() {
public void run() {
while (!pd.isShowing());
getUploadDate();
writeUploadDateInTextFile();
showDisclaimer();
pd.dismiss();
}
});
}
});
thread.start();
//while(thread.isAlive());
Log.d("triggerDownload", "thread died, finished dl. showing disclaimer...");
}
public void getUploadDate() {
Log.d("getUploadDate", "getting upload date of schedule");
if(pd!=null && pd.isShowing()) pd.dismiss();
pd = ProgressDialog.show(this, "Getting upload date",
"This may take a few minutes...", true, false);
Thread thread = 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.start();
while (thread.isAlive());
Log.d("getUploadDate","thread died, upload date="+str);
}
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");
TextView homeText1x = (TextView) findViewById(R.id.home_text1);
TextView homeText2x = (TextView) findViewById(R.id.home_text2);
TextView homeText3x = (TextView) findViewById(R.id.home_text3);
TextView homeText4x = (TextView) findViewById(R.id.home_text4);
homeText3x
.setText("You may view the schedule of pre-arranged power interruptions by clicking any of these buttons : SIN, City or Date. " +
"The schedule has been updated as of " + str
+ ". Meralco is exerting all efforts to restore electric service as scheduled." +
" The schedule, however, may change without further notice. For verification, follow-ups, or " +
"latest updates, please contact our CALL CENTER through telephone nos. 16211, " +
"fax nos. 1622-8554/1622-8556 or email address callcenter.tech.assist#meralco.com.ph.");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
}
public void promptRequiredUpdate(String Message) {
Log.d("required update","required!");
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setMessage(Message)
.setCancelable(false)
.setPositiveButton("Update Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "update");
triggerDownload();
dialog.cancel();
}
})
.setNegativeButton("Later",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("SHOW ALERT -->!", "cancel");
dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public boolean uploadDateEqualsDateInFile() {
Log.d("uploadDateEqualsDateInFile","comparing schedule upload dates");
getUploadDate();
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 void showAlert(String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setMessage(Message).setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
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();
}
}
}
simplymoody, do what Chirag Raval suggested by declaring private static TextView homeText1, globally and in your onCreate initialise them. However, you should always update the UI from the main thread. But showDisclaimer() is still running on the background thread, so you could run the showDisclaimer() a couple of different ways. One would be to do what you have done in getUploadDate():
runOnUiThread(new Runnable() {
public void run() {
showDisclaimer()
}
});
Or you could use a handler:
private Handler showDisclaimerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
homeText3x.setText("TEXT");
homeText1x.setVisibility(View.VISIBLE);
homeText2x.setVisibility(View.VISIBLE);
homeText3x.setVisibility(View.VISIBLE);
homeText4x.setVisibility(View.VISIBLE);
Log.d("ShowDisclaimer", "finished showing disclaimer");
return false;
}
});
And everywhere in a background thread you wish to run your showDisclaimer(), instead you run:
showDisclaimerHandler.sendEmptyMessage(0);