I try to use this library https://github.com/coomar2841/image-chooser-library to load image on my application.
When I select a image, I have this message "could'nt process no such file"
My code:
public class EditListeModelActivity extends Activity implements ImageChooserListener{
EditText titre;
CheckBox isvisible;
ActionBar actionBar;
ImageView ProfileImage;
private static int RESULT_LOAD_IMAGE = 1;
private boolean imageModifie=false;
private Bitmap newImage;
Builder b;
private ProgressBar pbar;
private ImageChooserManager imageChooserManager;
private String filePath;
private int chooserType;
private String uriFile;
private Button btnValide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_liste_model);
if(savedInstanceState!=null)
{
if (savedInstanceState.containsKey("uri_path")) {
uriFile = savedInstanceState.getString("uri_path");
}
}
actionBar = getActionBar();
actionBar.setDisplayOptions( ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_SHOW_TITLE|ActionBar.DISPLAY_SHOW_CUSTOM);
titre=(EditText)findViewById(R.id.nomEdit);
isvisible=(CheckBox)findViewById(R.id.isvisible);
btnValide=(Button)findViewById(R.id.EditListeModelNow);
ProfileImage = (ImageView) findViewById(R.id.profileImageEdit);
if(uriFile==null)
{
}
else
{
ProfileImage.setImageURI(Uri.parse(uriFile));
newImage=BitmapFactory.decodeFile(uriFile);
ProfileImage.setImageBitmap(newImage);
imageModifie=true;
}
b = new Builder(this);
b.setTitle("Choisir photo");
String[] types = {"Prendre une nouvelle photo", "Choisir une photo existante"};
b.setItems(types, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch(which){
case 0:
takePicture();
break;
case 1:
chooseImage();
break;
}
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
b.show();
//chooseImage();
/*
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);*/
}
});
pbar = (ProgressBar) findViewById(R.id.progressBarEditProfile);
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_liste_model, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK
&& (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
if (imageChooserManager == null) {
reinitializeImageChooser();
}
Log.e("imageChooserManager data ",data.toString());
imageChooserManager.submit(requestCode, data);
} else {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
}
}
#Override
public void onImageChosen(final ChosenImage image) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
if (image != null) {
File f=new File(image.getFileThumbnail());
ProfileImage.setImageURI(Uri.parse(f.toString()));
uriFile=f.toString();
newImage=BitmapFactory.decodeFile(f.toString());
ProfileImage.setImageBitmap(newImage);
imageModifie=true;
}
}
});
}
#Override
public void onError(final String reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
Toast.makeText(EditListeModelActivity.this, reason,
Toast.LENGTH_LONG).show();
}
});
}
// Should be called if for some reason the ImageChooserManager is null (Due
// to destroying of activity for low memory situations)
private void reinitializeImageChooser() {
imageChooserManager = new ImageChooserManager(this, chooserType,
"myfolder", true);
imageChooserManager.setImageChooserListener(this);
imageChooserManager.reinitialize(filePath);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("chooser_type", chooserType);
outState.putString("media_path", filePath);
outState.putString("uri_path", uriFile);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("chooser_type")) {
chooserType = savedInstanceState.getInt("chooser_type");
}
if (savedInstanceState.containsKey("media_path")) {
filePath = savedInstanceState.getString("media_path");
}
if (savedInstanceState.containsKey("uri_path")) {
uriFile = savedInstanceState.getString("uri_path");
}
}
}
private void takePicture() {
chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_CAPTURE_PICTURE, "myfolder", true);
imageChooserManager.setImageChooserListener(this);
try {
pbar.setVisibility(View.VISIBLE);
ProfileImage.setVisibility(View.GONE);
filePath = imageChooserManager.choose();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void chooseImage() {
chooserType = ChooserType.REQUEST_PICK_PICTURE;
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_PICK_PICTURE, "myfolder", true);
imageChooserManager.setImageChooserListener(this);
try {
pbar.setVisibility(View.VISIBLE);
ProfileImage.setVisibility(View.GONE);
filePath = imageChooserManager.choose();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
At ligne `Log.e("imageChooserManager data ",data.toString());
the result is
Intent { dat=content://com.android.providers.media.documents/document/image:22501 flg=0x1 }
I think that the probleme is where is stoked my image. How I do to load my image in my application?
That is a Uri. A Uri is not a file, and so you cannot pass it to decodeFile() on BitmapFactory. Either use an image loading library like Picasso or Universal Image Loader, or have your own background thread that uses openInputStream() on a ContentResolver to read in the contents of that Uri, passing the stream to decodeStream() on BitmapFactory.
Related
I am working on a filter activity in which there are 3 images at the bottom. By default, image 3 will be selected as it is the last one that will be clicked.
This same activity contains Latitude and Longitude which will be sent to next activity to fetch nearby locations.
The problem that I am facing is that among those 3 images when I select a filter for Image 1 and select the image 2, the activity gets restarted and because of this, the lat and long values are reset to 0.0 and 0.0 respectively.
Code -
public class MainActivity extends AppCompatActivity implements FiltersListFragment.FiltersListFragmentListener, EditImageFragment.EditImageFragmentListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_activity_main_filter);
instagramFilterIntent = new Intent(this, MainActivity.class);
ButterKnife.bind(this);
getBundleValues();
loadImage();
setupViewPager(viewPager);
setBitmap(originalImage);
ivSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveImageToGallery();
startingActivtity();
}
});
ivClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveImageToGallery();
}
});
}
double latitude,longitude;
private void getBundleValues() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey("image")) {
Log.e("image", extras.getString("image"));
editingImage = extras.getString("image");
imgFile = new File(extras.getString("image"));
originalFile = imgFile;
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
originalImage = myBitmap;
}
}
if(extras.containsKey("PESDK")){
initiated=extras.getBoolean("PESDK");
}
if(extras.containsKey("Latitude")){
latitude=extras.getDouble("Latitude");
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
if(extras.containsKey("Longitude")){
longitude=extras.getDouble("Longitude");
}
if (extras.containsKey("Filters")) {
filters = extras.getBoolean("Filters");
instagramFilterIntent.putExtra("Filters", filters);
}
if (extras.containsKey("Image1")) {
files[0] = extras.getString("Image1");
instagramFilterIntent.putExtra("Image1", files[0]);
}
if (extras.containsKey("Image2")) {
files[1] = extras.getString("Image2");
instagramFilterIntent.putExtra("Image2", files[1]);
}
if (extras.containsKey("Image3")) {
files[2] = extras.getString("Image3");
instagramFilterIntent.putExtra("Image3", files[2]);
}
initializeImages();
}
}
private void initializeImages() {
if (files[0] != null) {
//Glide.with(getApplicationContext()).load(files[0]).into(preview1Img);
Bitmap bitmap = BitmapFactory.decodeFile(files[0]);
preview1Img.setImageBitmap(bitmap);
if(editingImage.equalsIgnoreCase(files[0])) {
preview1B.setVisibility(View.VISIBLE);
}
}
else {
preview1Layout.setVisibility(View.GONE);
preview1B.setVisibility(View.INVISIBLE);
}
if (files[1] != null) {
//Glide.with(getApplicationContext()).load(files[1]).into(preview2Img);
Bitmap bitmap = BitmapFactory.decodeFile(files[1]);
preview2Img.setImageBitmap(bitmap);
if(editingImage.equalsIgnoreCase(files[1])) {
preview2B.setVisibility(View.VISIBLE);
}
}
else {
preview2Layout.setVisibility(View.GONE);
preview2B.setVisibility(View.INVISIBLE);
}
if (files[2] != null) {
//Glide.with(getApplicationContext()).load(files[2]).into(preview3Img);
Bitmap bitmap = BitmapFactory.decodeFile(files[2]);
preview3Img.setImageBitmap(bitmap);
if(editingImage.equalsIgnoreCase(files[2])){
preview3B.setVisibility(View.VISIBLE);
}
}
else {
preview3Layout.setVisibility(View.GONE);
preview3B.setVisibility(View.INVISIBLE);
}
}
public static void setBitmap(Bitmap originalImage) {
ORIGINAL = originalImage;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// adding filter list fragment
filtersListFragment = new FiltersListFragment();
filtersListFragment.setInitiatedPESDK(initiated);
filtersListFragment.setListener(this);
// adding edit image fragment
editImageFragment = new EditImageFragment();
editImageFragment.setListener(this);
adapter.addFragment(filtersListFragment, getString(R.string.tab_filters));
adapter.addFragment(editImageFragment, getString(R.string.tab_edit));
//filtersListFragment.prepareThumbnail(originalImage);
viewPager.setAdapter(adapter);
}
#Override
public void onFilterSelected(Filter filter, ImageFilter imageFilter) {
// reset image controls
resetControls();
// applying the selected filter
filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
// preview filtered image
if(filter!=null) {
imagePreview.setImageBitmap(filter.processFilter(filteredImage));
}else{
imagePreview.setImageBitmap(imageFilter.renderImage(filteredImage,false));
}
finalImage = filteredImage.copy(Bitmap.Config.ARGB_8888, true);
}
/**
* Resets image edit controls to normal when new filter
* is selected
*/
private void resetControls() {
if (editImageFragment != null) {
editImageFragment.resetControls();
}
brightnessFinal = 10;
saturationFinal = 1.0f;
contrastFinal = 1.0f;
}
/**
* Image View click listners
* */
public void image1Click(View view) {
if (!imgFile.toString().equalsIgnoreCase(files[0])) {
saveImageToGallery();
instagramFilterIntent.putExtra("image", files[0]);
instagramFilterIntent.putExtra("PESDK",initiated);
this.finish();
startActivity(instagramFilterIntent);
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
}
public void image2Click(View view) {
if (!imgFile.toString().equalsIgnoreCase(files[1])) {
saveImageToGallery();
instagramFilterIntent.putExtra("image", files[1]);
instagramFilterIntent.putExtra("PESDK",initiated);
this.finish();
startActivity(instagramFilterIntent);
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
}
public void image3Click(View view) {
if (!imgFile.toString().equalsIgnoreCase(files[2])) {
saveImageToGallery();
instagramFilterIntent.putExtra("image", files[2]);
instagramFilterIntent.putExtra("PESDK",initiated);
this.finish();
startActivity(instagramFilterIntent);
Toast.makeText(this, "lat"+latitude, Toast.LENGTH_SHORT).show();
}
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
// load the default image from assets on app launch
private void loadImage() {
//#todo
// originalImage = BitmapUtils.getBitmapFromGallery(this, Uri.parse(IMAGE_NAME), 300, 300);
filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
finalImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
imagePreview.setImageBitmap(originalImage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == SELECT_GALLERY_IMAGE) {
Log.e("data.getData()", data.getData() + "");
Bitmap bitmap = BitmapUtils.getBitmapFromGallery(this, data.getData(), 800, 800);
// clear bitmap memory
originalImage.recycle();
finalImage.recycle();
finalImage.recycle();
originalImage = bitmap.copy(Bitmap.Config.ARGB_8888, true);
filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
finalImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
imagePreview.setImageBitmap(originalImage);
bitmap.recycle();
// render selected image thumbnails
filtersListFragment.prepareThumbnail(originalImage);
}
}
/*
* saves image to camera gallery
* */
private void saveImageToGallery() {
Dexter.withActivity(this).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
if (originalFile.exists()) {
originalFile.delete();
}
// final String path = BitmapUtils.insertImage(getContentResolver(), finalImage, System.currentTimeMillis() + "_profile.jpg", null);
new MainActivity.SaveImageTask(finalImage, originalFile).execute();
//finish();
}
else {
Toast.makeText(getApplicationContext(), "Permissions are not granted!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
Bitmap finalBitmap;
File name;
public SaveImageTask(Bitmap finalBitmap, File name) {
this.finalBitmap = finalBitmap;
this.name = name;
}
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to SD Card
try {
File file = name;
if (file.exists()) {
} else {
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.e("FIlter MainACTIVITY", "SAVED");
Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
}
}
public void startingActivtity(){
Intent chekInActivity = new Intent(MainActivity.this, CurrentLocationPlaces.class);
if(files[0] != null) {
chekInActivity.putExtra("Image1",files[0].toString());
}
if(files[1] != null) {
chekInActivity.putExtra("Image2",files[1].toString());
}
if(files[2] != null) {
chekInActivity.putExtra("Image3",files[2].toString());
}
chekInActivity.putExtra("source","gallery");
chekInActivity.putExtra("Latitude", latitude);
chekInActivity.putExtra("Longitude", longitude);
startActivity(chekInActivity);
}
}
May I know how to either stop restarting the activity and select the image to get its preview to apply filters or how to save the lat and long values so that it won't get reset when the activity restarts?
If the value should be held across activity restarts you should be using an activity or shared preference.
Basically in your onCreate, load the values and assign them to your Textview (or other component). When they change just update the preference value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Load the lat/lng
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
double lat = preferences.getDouble("latitude", 0);
double lon = preferences.getDouble("longitude", 0);
}
Then where you have your application update that value simply update the preference value.
private void updatePreference(double lat, double lng) {
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("latitude", lat);
editor.putInt("longitude", lon);
editor.commit();
}
That will hold your values and allow you to update/interface with them across activity restarts.
SEE: SharedPreferences
First time I am using GoogleApiClient and want to upload all the text messages to google drive when the share button in the app is clicked. But the data is not uploading on the drive.
MainActivity :
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
SmsAdapter adapter;
FloatingActionButton fab;
Cursor c;
ExportTask task;
ArrayList<CustomSms> smslistSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
smslistSearch = new ArrayList<>();
rv = (RecyclerView) findViewById(R.id.messages_view);
LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
rv.setLayoutManager(llm);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i =new Intent(MainActivity.this,SendSms.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
final ArrayList<CustomSms> smslist, smsgrouplist;
smslist = new ArrayList<>();
smsgrouplist = new ArrayList<>();
//Fetch inobx sms message
c = getContentResolver().query(SmsApplication.INBOX_URI, null, null, null, null);
while (c.moveToNext()) {
String address = c.getString(c.getColumnIndexOrThrow("address"));
String date = c.getString(c.getColumnIndexOrThrow("date"));
String body = c.getString(c.getColumnIndexOrThrow("body"));
smslist.add(new CustomSms(address, date, body));
}
smslistSearch = smslist;
Map<String, CustomSms> map = new LinkedHashMap<>();
for (CustomSms ays : smslist) {
CustomSms existingValue = map.get(ays.address);
if(existingValue == null){
map.put(ays.address, ays);
}
}
smsgrouplist.clear();
smsgrouplist.addAll(map.values());
adapter = new SmsAdapter(MainActivity.this);
adapter.updateList(smsgrouplist);
rv.setAdapter(adapter);
rv.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// TODO Handle item click
ArrayList<CustomSms> smsinsidegroup = new ArrayList<CustomSms>();
String n = smsgrouplist.get(position).address;
for (int i = 0; i < smslist.size(); i++) {
if(smslist.get(i).address.equals(n))
smsinsidegroup.add(smslist.get(i));
}
Intent i = new Intent(MainActivity.this, ReadAllSms.class);
i.putParcelableArrayListExtra("messages", smsinsidegroup);
startActivity(i);
}
})
);
}
catch (Exception e)
{
e.printStackTrace();
}
}
class ExportTask extends AsyncTask<Void, Integer, Uri> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Exporting to file ...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(0);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Uri doInBackground(Void... params) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
fos = new FileOutputStream(f);
int count = c.getCount(), i = 0;
StringBuilder sb = new StringBuilder();
if (c.moveToFirst()) {
do {
sb.append(c.getString(c.getColumnIndex("address")))
.append("\n");
sb.append(c.getString(c.getColumnIndex("body")))
.append("\n");
sb.append("\n");
publishProgress(++i*100/count);
} while (!isCancelled() && c.moveToNext());
}
fos.write(sb.toString().getBytes());
return Uri.fromFile(f);
} catch (Exception e) {
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {}
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Uri result) {
super.onPostExecute(result);
pDialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "Export task failed!",
Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
Intent i = new Intent(MainActivity.this,SearchActivity.class);
i.putParcelableArrayListExtra("search", smslistSearch);
startActivity(i);
return true;
}
if (id == R.id.action_share) {
/*Intent i = new Intent(MainActivity.this,UploadData.class);
startActivity(i);*/
task = new ExportTask();
task.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
if (task != null) {
task.cancel(false);
task.pDialog.dismiss();
}
super.onPause();
}
}
UploadData :
public class UploadData extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "upload_file";
private static final int REQUEST_CODE = 101;
private File textFile;
private GoogleApiClient googleApiClient;
public static String drive_id;
public static DriveId driveID;
FrameLayout rl;
TextView success;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_data);
rl = (FrameLayout) findViewById(R.id.frame);
success = (TextView) findViewById(R.id.success);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBackOrig));
textFile = new File(Environment.getExternalStorageDirectory(), "SmsBackUp.txt");
buildGoogleApiClient();
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "connecting...");
googleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (googleApiClient != null) {
Log.i(TAG, "disConnecting...");
googleApiClient.disconnect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Log.i(TAG, "In onActivityResult() - connecting...");
googleApiClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "in onConnected() - connected");
Drive.DriveApi.newDriveContents(googleApiClient)
.setResultCallback(driveContentsCallback);
}
#Override
public void onConnectionSuspended(int cause) {
switch (cause) {
case 1:
Log.i(TAG, "Connection suspended - Cause: " + "Service disconnected");
break;
case 2:
Log.i(TAG, "Connection suspended - Cause: " + "Connection lost");
break;
default:
Log.i(TAG, "Connection suspended - Cause: " + "Unknown");
break;
}
}
final private ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = new
ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Error creating the new file of contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
new Thread() {
#Override
public void run() {
OutputStream outputStream = driveContents.getOutputStream();
addTextfileToOutputStream(outputStream);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("SmsBackup")
.setMimeType("text/plain")
.setDescription("This is a text file uploaded from device")
.setStarred(true).build();
Drive.DriveApi.getRootFolder(googleApiClient)
.createFile(googleApiClient, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
};
private void addTextfileToOutputStream(OutputStream outputStream) {
byte[] buffer = new byte[1024];
int bytesRead;
try {
BufferedInputStream inputStream = new BufferedInputStream(
new FileInputStream(textFile));
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
}
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Toast.makeText(UploadData.this,
"Error adding file to Drive", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(UploadData.this,
"File successfully added to Drive", Toast.LENGTH_SHORT).show();
showProgress(false);
rl.setBackgroundColor(getResources().getColor(R.color.colorBack));
View root = rl.getRootView();
root.setBackgroundColor(getResources().getColor(R.color.colorBack));
success.setVisibility(View.VISIBLE);
final PendingResult<DriveResource.MetadataResult> metadata
= result.getDriveFile().getMetadata(googleApiClient);
metadata.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
Metadata data = metadataResult.getMetadata();
drive_id = data.getDriveId().encodeToString();
driveID = data.getDriveId();
}
});
}
};
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
}
}
private void buildGoogleApiClient() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
progressBar.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
}
You might want to check on how you work with File Contents, first you might want to check if there is a value on the variable textFile that you have set.
The example below illustrates how to append "hello world" to the DriveContents.
try {
ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
.getFileDescriptor());
// Read to the end of the file.
fileInputStream.read(new byte[fileInputStream.available()]);
// Append to the file.
FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
.getFileDescriptor());
Writer writer = new OutputStreamWriter(fileOutputStream);
writer.write("hello world");
} catch (IOException e) {
e.printStackTrace();
}
There is a related SO question - Upload text file to Google Drive using Android that you might want to check out. The answer in the question reminds the OP regarding how to feed the file with contents.
Lastly, you might want to check this github. This code show how to insert the content of the chat into a file and save it to the drive.
Hope this helps.
In a list view i have image, text and image contains default image when list load with download complete , every thing works fine but when keyboard opens the downloaded image change to default image.
public class ChatScreen extends Activity implements OnClickListener
{
private void stopTimer()
{
if (mTimer1 != null)
{
mTimer1.cancel();
mTimer1.purge();
}
}
private void startTimer()
{
mTimer1 = new Timer();
mTt1 = new TimerTask()
{
public void run()
{
mTimerHandler.post(new Runnable()
{
public void run()
{
try
{
Date date1 = getDate(time);
Date date2 = getDate(getCurrentTime());
if (date2.getTime() - date1.getTime() == 5000)
{
stopTimer();
try
{
chat.setCurrentState(ChatState.paused,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
else if (date2.getTime() - date1.getTime() > 30000)
{
time = getCurrentTime();
try
{
chat.setCurrentState(ChatState.gone,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
}
catch (ParseException e)
{
e.printStackTrace();
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
}
});
}
};
mTimer1.schedule(mTt1, 00, 5000);
}
#Override
protected void onPause()
{
super.onPause();
chat.setChatFragment(null);
System.out.println("onPasue called");
}
}
}
}
}
}
#Override
protected void onResume()
{
super.onResume();
session.saveCurrentName(this.getLocalClassName());
chat.setChatFragment(ctx);
System.out.println("onResume called");
if(checkForCurfew())
showHideView(true, 0);
else
showHideView(false, 0);
}
public void showHideView(final boolean value, final int type)
{
System.out.println("Called");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if(value)
{
btnSend.setEnabled(value);
btnSend.setAlpha(1.0f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(1.0f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(1.0f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(1.0f);
}
else
{
btnSend.setEnabled(value);
btnSend.setAlpha(0.5f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(0.5f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(0.5f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(0.5f);
}
if(!value && type == 0)
inputMessage.setHint("You can't chat during a curfew");
else if(!value && type == 1)
inputMessage.setHint("Can’t Access Internet");
else
inputMessage.setHint("Enter message here");
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
System.gc();
setContentView(R.layout.activity_fragment_chat);
System.out.println("Chat screen called.");
mcon = ChatScreen.this;
chat = ((RooChat) getApplication()).chat;
Bundle bundle = getIntent().getBundleExtra("bundle_data");
System.out.println("bundle- " + bundle);
chatWithJID = bundle.getString("chat_with");
chatWithName = bundle.getString("kid_name");
FromChatJID = bundle.getString("chat_from");
ChatRoomName = bundle.getString("chat_room");
indexOfChatRoom = Integer.parseInt(bundle.getString("index"));
CopyindexOfChatRoom = indexOfChatRoom;
typeFaceCurseCasual = AppFonts.getFont(mcon, AppFonts.CurseCasual);
typeFaceARLRDBDHand = AppFonts.getFont(mcon, AppFonts.ARLRDBDHand);
back = (Button) findViewById(R.id.back);
sendBtn=(Button)findViewById(R.id.send);
sendBtn.setOnClickListener(this);
erasebtn=(Button)findViewById(R.id.erase);
erasebtn.setOnClickListener(this);
smallers=(Button)findViewById(R.id.small_ers1);
smallers.setOnClickListener(this);
mediumers=(Button)findViewById(R.id.medium_ers1);
mediumers.setOnClickListener(this);
largeers=(Button)findViewById(R.id.large_ers1);
largeers.setOnClickListener(this);
smallline=(Button)findViewById(R.id.small);
smallline.setOnClickListener(this);
mediumline=(Button)findViewById(R.id.medium);
mediumline.setOnClickListener(this);
largeline=(Button)findViewById(R.id.large);
largeline.setOnClickListener(this);
back1=(Button)findViewById(R.id.back1);
back1.setOnClickListener(this);
drawView=(DrawingView)findViewById(R.id.Drawing);
doodle_btn=(Button)findViewById(R.id.doodle_btn);
doodle_btn.setOnClickListener(this);
doodle=(LinearLayout) findViewById(R.id.doodle);
back.setOnClickListener(this);
init();
String available = convertAvailability(chat.getUserAvailability(chatWithJID));
if (chatWithName.equalsIgnoreCase("echo") || chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr"))
{
image.setImageResource(R.drawable.status_active);
}
else if (available.equalsIgnoreCase("offline"))
{
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
}
else
{
// chatState.setText(available);
image.setImageResource(R.drawable.status_active);
}
inputMessage.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (chat.isConnected())
{
try
{
time = getCurrentTime();
}
catch (ParseException e1)
{
e1.printStackTrace();
}
if (isTyping == false)
{
try
{
chat.setCurrentState(ChatState.composing, chatWithJID, FromChatJID);
isTyping = true;
startTimer();
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
else if (isTyping == true)
{
stopTimer();
startTimer();
}
}
/*else
Toast.makeText(getApplicationContext(), "Please wait, connecting to server.", 0).show();
*/
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
inputMessage.setOnFocusChangeListener(new OnFocusChangeListener()
{
#Override
public void onFocusChange(final View v, final boolean hasFocus)
{
if (hasFocus && inputMessage.isEnabled() && inputMessage.isFocusable())
new Runnable()
{
#Override
public void run()
{
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(inputMessage, InputMethodManager.SHOW_IMPLICIT);
}
};
}
});
data = session.getUserDetails();
banned = session.getBannedWord();
System.out.println(banned);
JSONArray jsonArray;
if(!banned.equals(""))
{
try
{
jsonArray = new JSONArray(banned);
strArr = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++)
{
strArr[i] = jsonArray.getString(i);
}
//System.out.println(Arrays.toString(strArr));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
public void reFreshData()
{
indexOfChatRoom = db.getChatRoomIndex(chatWithName);
messages = db.getFriendChat(indexOfChatRoom);
adapter = new ChatMessageAdapter(mcon, messages);
chatList.setAdapter(adapter);
}
private void init()
{
db = new DatabaseHelper(mcon);
ctx = this;
chat.setChatFragment(ctx);
session = new SessionManager(mcon);
chatList = (ListView) findViewById(R.id.chatList);
chatWith = (TextView) findViewById(R.id.chat_with);
doodle_txt = (TextView) findViewById(R.id.doodle_txt);
chatState = (TextView) findViewById(R.id.chat_status);
btnPicture = (TextView) findViewById(R.id.picture);
btnPicture.setOnClickListener(this);
btnSticker = (TextView) findViewById(R.id.sticker);
btnSticker.setOnClickListener(this);
btnExtra = (TextView) findViewById(R.id.extra);
btnExtra.setOnClickListener(this);
btnSend = (TextView) findViewById(R.id.btn_send);
btnSend.setTypeface(typeFaceARLRDBDHand, Typeface.BOLD);
btnSend.setOnClickListener(this);
inputMessage = (EditText) findViewById(R.id.et_message);
inputMessage.setTypeface(typeFaceCurseCasual);
chatWith.setText(chatWithName);
image = (ImageView) findViewById(R.id.img_chat_status);
cross = (ImageView) findViewById(R.id.cross);
cross.setOnClickListener(this);
lay_sticker_main = (LinearLayout) findViewById(R.id.lay_sticker_main);
lay_sticker_child = (FlowLayout) findViewById(R.id.lay_sticker_child);
lay_sticker_group = (FlowLayout) findViewById(R.id.lay_sticker_group);
reFreshData();
chatList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, final int arg2,
long arg3) {
// TODO Auto-generated method stub
final ChatMessage msg=adapter.getItem(arg2);
final ImageView btn = (ImageView) arg1.findViewById(R.id.textView1);
final ImageView imgone = (ImageView)arg1.findViewById(R.id.imagev);
try{
if(!btn.getTag().toString().equals("")){
Log.v("","msg getting:..."+btn.getTag().toString());
DownloadImage di=new DownloadImage(ChatScreen.this, btn.getTag().toString(), new BitmapAsyncTaskCompleteListener() {
#Override
public void onTaskComplete(Bitmap result) {
// TODO Auto-generated method stub
Log.v("Img :",""+result);
imgone.setImageBitmap(result);
String filePath=saveImage(result,msg.getId(),msg.getFrom());
btn.setVisibility(View.GONE);
btn.setTag(filePath);
final int index = chatList.getFirstVisiblePosition();
View v = chatList.getChildAt(0);
final int top = (v == null) ? 0 : v.getTop();
Log.v("", "top :.."+top);
chatList.post(new Runnable() {
#Override
public void run() {
chatList.setSelectionFromTop(index,top);
}
});
}
});
di.execute();
}
}
catch(Exception ex){
btn.setVisibility(View.GONE);
btn.setTag("");
}
}
});
handler = new Handler(Looper.getMainLooper())
{
#Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case REFRESH_CHAT_LIST:
adapter.notifyDataSetChanged();
break;
case REFRESH_CHAT_STATUS:
if(text != null)
{
try
{
if (isNumeric(text))
{
chatState.setText(calculateTime(Long.parseLong(text)));
image.setImageResource(R.drawable.status_offline);
}
else
{
chatState.setText(text);
if (chatWithName.equalsIgnoreCase("echo")
|| chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr")) {
image.setImageResource(R.drawable.status_active);
} else if (text.equalsIgnoreCase("offline")) {
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
} else {
image.setImageResource(R.drawable.status_active);
}
}
}
catch(NumberFormatException e)
{
image.setImageResource(R.drawable.status_offline);
e.printStackTrace();
}
}
break;
case REFRESH_MESSAGE_DELIVERY:
adapter.notifyDataSetChanged();
break;
default:
break;
}
}
};
}String filePath ="";
private String saveImage(Bitmap finalBitmap,int chatWith,String from) {
String fileName = chat.getCurrentDateTime();
//msg = "You got a photo. Display of photo will be added in next version of this app.";
final File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "/roo_kids/images/" + from + "/");
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, fileName + ".png");
if (!myFile.exists())
{
try
{
myFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(myFile);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath= myFile.getAbsolutePath()+"::images::";
Log.v("","filePath after decoding:.."+filePath);
Log.v("","chatWith Id after decoding:.."+chatWith);
Log.v("","from after decoding:.."+from);
db.updateFriendChat(chatWith,filePath);
return filePath;
}
public void getAllFiles(String directoryName)
{
}
public boolean isFileExist(String directoryName, String filename)
{
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.picture:
openGallery();
break;
case R.id.extra:
break;
case R.id.btn_send:
sendMessageAndValidate();
break;
case R.id.back:
onBackPressed();
break;
default:
break;
}
}
private void openGallery()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
//intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(intent, SELECT_PICTURE);
}
private String encodeFileToBase64Binary(String path)throws IOException, FileNotFoundException
{
}
String cond="";
public class ExecuteImageSharingProcess extends AsyncTask<String, Integer, String>
{
String base64 = "";
ProgressDialog pd = null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(ChatScreen.this);
pd.setCancelable(false);
pd.setMessage("Please wait..");
pd.show();
}
#Override
protected String doInBackground(String... params)
{
try
{
//base64 = encodeFileToBase64Binary(params[0]);
Log.v("", "params[0].."+params[0]);
byte[] data = params[0].getBytes("UTF-8");
base64= new String(data);
Log.v("", "base64.."+base64);
return "yes";
}
catch (IOException e)
{
e.printStackTrace();
return "no";
}
catch(NullPointerException e)
{
return "no";
}
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(result.equals("yes"))
{
if(chat.isConnected())
{
String prefix = chat.generateRandomChar()+"imagePrefixEnd";
System.out.println("prefix-> "+prefix);
ctx.moveMessagetoXMPP(prefix + base64 + "::images::", 1);
base64 = "";
bitmap = null;
}
}
else
{
Toast.makeText(ctx, "File not found.", Toast.LENGTH_LONG).show();
}
try
{
if ((this.pd != null) && this.pd.isShowing())
{
this.pd.dismiss();
}
} catch (final IllegalArgumentException e)
{
} catch (final Exception e)
{
} finally
{
this.pd = null;
}
}
}
String imgDecodableString = null;
String imgbase64="";
AlertManager alert_dialog;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent i)
{
super.onActivityResult(requestCode, resultCode, i);
try
{
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data)
{
String urlofimage=""; // here i send base64 image to server and it will returns url of image that is send in ExecuteImageSharingProcess method.
new ExecuteImageSharingProcess().execute(urlofimage);
}
});
ucIA.execute();
}
}
else if (resultCode == Activity.RESULT_CANCELED)
{
bitmap = null;
}
} catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
private void sendMessageAndValidate()
{
String msg=inputMessage.getText().toString().replace(" ","");
String msgone=msg.replace("\n", "");
if (msgone.length() > 0)
{
if (chat.isConnected())
{
ctx.moveMessagetoXMPP(inputMessage.getText().toString(), 0);
inputMessage.setText("");
stopTimer();
}
}
}
String thread="";
protected void moveMessagetoXMPP(String msg, final int type)
{
data = session.getUserDetails();
if (checkChatRoomAvailablity(chatWithName))
{
thread = db.getThreadFromChatroom(chatWithName);
}
if (thread.equals(""))
thread = ChatRoomName;
chat.sendMesage(indexOfChatRoom, msg, FromChatJID, chatWithJID, thread, type);
try
{
chat.setCurrentState(ChatState.paused, chatWithJID, FromChatJID);
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
public class MyThread implements Runnable
{
String message;
File file;
public MyThread(String message, File file)
{
this.message = message;
this.file = file;
}
#Override
public void run()
{
String fileName;
if(message.contains("::images::"))
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::images::"))), file);
else
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::doodle::"))), file);
}
}
public void appendMessageInListView(long _id)
{
if (messages.size() > 0)
{
System.out.println(messages.get(messages.size() - 1).getId());
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, ""+ messages.get(messages.size() - 1).getId());
messages.add(messages.size(), cm);
}
else
{
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, "" + _id);
messages.add(messages.size(), cm);
}
refreshChatList();
}
public void refreshChatList()
{
int state = REFRESH_CHAT_LIST;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public void refreshChatStatus() {
int state = REFRESH_CHAT_STATUS;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public int getChatIndex2(String participant) {
return db.getChatRoomIndex(participant);
}
ImageView img;
View oldview;
public class ChatMessageAdapter extends BaseAdapter
{
public ArrayList<ChatMessage> messages;
private Context ctx;
public ChatMessageAdapter(Context ctx, ArrayList<ChatMessage> messages)
{
this.ctx = ctx;
this.messages = messages;
}
#Override
public int getCount()
{
return messages.size();
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
#Override
public View getView(int position, View oldView, ViewGroup parent)
{
if (ctx == null)
return oldView;
final ChatMessage msg = getItem(position);
if (oldView == null || (((Integer) oldView.getTag()) != msg.getIsOutgoing()))
{
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
{
oldView = inflater.inflate(R.layout.fragment_message_outgoing_item, null);
oldView.setTag(MyMessage.OUTGOING_ITEM);
}
else
{
oldView = inflater.inflate(R.layout.fragment_message_ingoing_item, null);
oldView.setTag(MyMessage.INGOING_ITEM);
}
}
TextView message = (TextView) oldView.findViewById(R.id.msg);
message.setTypeface(typeFaceCurseCasual);
LinearLayout lay_txt = (LinearLayout) oldView.findViewById(R.id.lay_txt);
LinearLayout lay_img = (LinearLayout) oldView.findViewById(R.id.lay_img);
img = (ImageView) oldView.findViewById(R.id.imagev);
FrameLayout fmlay=(FrameLayout) oldView.findViewById(R.id.fmlay);
ImageView textView1 = (ImageView) oldView.findViewById(R.id.textView1);
ImageView imgSticker = (ImageView) oldView.findViewById(R.id.img_sticker);
ImageView tickSent = (ImageView) oldView.findViewById(R.id.tickSent);
ImageView tickDeliver = (ImageView) oldView.findViewById(R.id.tickDeliver);
TextView timestamp = (TextView) oldView.findViewById(R.id.timestamp);
oldview=oldView;
timestamp.setTypeface(typeFaceCurseCasual);
message.setText(msg.getMessage());
System.out.println("message in adapter");
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
tickSent.setVisibility(View.VISIBLE);
else
tickSent.setVisibility(View.INVISIBLE);
if (msg.getIsDeliver() == true)
tickDeliver.setVisibility(View.VISIBLE);
else
tickDeliver.setVisibility(View.INVISIBLE);
if(msg.getTimeStamp()!= null) timestamp.setText(getTimeAgo(Long.parseLong(msg.getTimeStamp()),ctx));
if(msg.getMessage()!= null)
{
if(msg.getMessage().contains("::sticker::"))
{
lay_img.setVisibility(View.GONE);
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.VISIBLE);
String Dir = msg.getMessage().substring(2, msg.getMessage().indexOf("-"));
String file = msg.getMessage().substring(2, msg.getMessage().indexOf("}}"));
if(isFileExist(Dir, file))
{
String path = ctx.getFilesDir() + "/booksFolder/"+Dir+"/"+file;
System.out.println("path- "+ path);
Uri imgUri = Uri.parse("file://"+path);
imgSticker.setImageURI(imgUri);
}
else
{
String url = "http://s3.amazonaws.com/rk-s-0ae8740/a/"+file;
System.out.println(url);
new ImageLoaderWithImageview(mcon).DisplayImage(url, imgSticker);
}
}
else if(!msg.getMessage().contains("::images::") && !msg.getMessage().contains("::doodle::"))
{
System.out.println("in text condition");
lay_img.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_txt.setVisibility(View.VISIBLE);
System.out.println("msg coming :"+msg.getMessage());
message.setText(msg.getMessage());
}
else
{
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_img.setVisibility(View.VISIBLE);
if (msg.getIsOutgoing() == MyMessage.INGOING_ITEM)
{
fmlay.setVisibility(View.VISIBLE);
}
Log.v("","msg getting:..."+msg.getMessage());
String pathOne = null ;
if(msg.getMessage().contains("imagePrefixEnd")){
Log.v("In images/doddle if", "askfk");
pathOne="default";
textView1.setVisibility(View.VISIBLE);
String imgpath=setdefaultImage(msg.getMessage());
textView1.setTag(imgpath);
}
else {
Log.v("In images else", "askfk");
try{
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::images::"));
}
catch(Exception ex){
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::doodle::"));
}
textView1.setVisibility(View.GONE);
Bitmap bitmap=setImage(pathOne);
img.setImageBitmap(bitmap);
textView1.setTag("");
}
}
}
return oldview;
}
#Override
public ChatMessage getItem(int position)
{
return messages.get(position);
}
}
public String setdefaultImage(String msg){
Bitmap bImage = BitmapFactory.decodeResource(ChatScreen.this.getResources(), R.drawable.dummyimage);
img.setImageBitmap(bImage);
String urlpath="";
try{
urlpath = msg.substring(0, msg.indexOf("::images::"));
}
catch(Exception ex){
urlpath = msg.substring(0, msg.indexOf("::doodle::"));
}
//Log.v("","msg getting:..."+urlpath);
String pt[]=urlpath.split("PrefixEnd");
//System.out.println("path :"+pt[1]);
return pt[1];
}
public Bitmap setImage(String pathOne){
Bitmap bitmap=null;
File imgFile = new File(pathOne);
//Log.v("","msg image path:..."+pathOne);
if(imgFile.exists())
{
//Log.v("","msg path exits:...");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap= BitmapFactory.decodeFile(pathOne, options);
}
else{
}
return bitmap;
}
}
Try to tag the data model/ data source with your list view view.setTag(dataModel) in getView method of your adapter class.
Why not try RecyclerView instead of ListView and use Fresco Image Library?
I have some problem with printing image to AGPtEK 58mm Mini Bluetooth Pocket POS Thermal Receipt Printer. I am trying to convert webview content into image (this is working fine) and after that I want to print it with this printer but it prints only solid black background. Here is my code:
public class PrintDemo extends Activity {
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int PERMISSIONS_REQUEST_BLUETOOTH = 1;
private static final String TAG_REQUEST_PERMISSION = "Request permission";
private static final int PERMISSIONS_REQUEST_INTERNET = 0;
private static final int PERMISSIONS_REQUEST_BT_ADMIN = 2;
private static final int PERMISSIONS_REQUEST_LOCATION = 3;
private static final String WEB_SITE = "Remembered Web Site";
private static final String IS_CHECKED = "Check box";
#Bind(R.id.btn_search)
Button btnSearch;
#Bind(R.id.btn_print)
Button btnSendDraw;
#Bind(R.id.btn_open)
Button btnSend;
#Bind(R.id.btn_close)
Button btnClose;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("State", "Connecting...");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("State", "Not found");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
String path;
File dir;
File file;
#Bind(R.id.check_box)
CheckBox checkBox;
#Bind(R.id.txt_content)
EditText edtContext;
#Bind(R.id.web_view)
WebView webView;
BluetoothService mService;
BluetoothDevice con_dev;
private SharedPreferences sharedPref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.main);
ButterKnife.bind(this);
mService = new BluetoothService(this, mHandler);
if (!mService.isAvailable()) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.setWebViewClient(new WebViewClient() {
#SuppressLint("SdCardPath")
#Override
public void onPageFinished(final WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
siteToImage(view);
}
}, 5000);
}
});
sharedPref = this.getPreferences(Context.MODE_PRIVATE);
checkPermissions();
}
private void siteToImage(WebView view) {
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(
picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setRememberedWeb() {
if (checkBox.isChecked()) {
String rememberedWeb = sharedPref.getString(WEB_SITE, "");
if (!rememberedWeb.equals("")) {
edtContext.setText(rememberedWeb);
}
}
}
#Override
protected void onPause() {
super.onPause();
saveState(checkBox.isChecked());
}
#Override
protected void onResume() {
super.onResume();
checkBox.setChecked(load());
setRememberedWeb();
}
private void saveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(IS_CHECKED, isChecked);
if (isChecked) {
editor.putString(WEB_SITE, edtContext.getText().toString());
} else {
editor.putString(WEB_SITE, getString(R.string.txt_content));
}
editor.apply();
}
private boolean load() {
return sharedPref.getBoolean(IS_CHECKED, false);
}
private boolean checkPermissions() {
int permissionCheck =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
int permissionInternet =
ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permissionBTAdmin =
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
int permissionLocation =
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bluetooth_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTPermission();
}
return false;
} else if (permissionInternet == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_internet_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestInternetPermission();
}
return false;
} else if (permissionBTAdmin == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_bt_admin_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.INTERNET)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestBTAdminPermission();
}
return false;
} else if (permissionLocation == PackageManager.PERMISSION_DENIED) {
edtContext.setText(R.string.no_location_permissions);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(PrintDemo.this, TAG_REQUEST_PERMISSION, Toast.LENGTH_SHORT).show();
} else {
requestLocationPermission();
}
return false;
} else {
return true;
}
}
private void requestLocationPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
private void requestBTAdminPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN},
PERMISSIONS_REQUEST_BT_ADMIN);
}
private void requestInternetPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.INTERNET},
PERMISSIONS_REQUEST_INTERNET);
}
private void requestBTPermission() {
ActivityCompat
.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH},
PERMISSIONS_REQUEST_BLUETOOTH);
}
#Override
public void onStart() {
super.onStart();
if (!mService.isBTopen()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_print);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btn_open);
btnSend.setOnClickListener(new ClickEvent());
btnClose = (Button) this.findViewById(R.id.btn_close);
btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
btnClose.setEnabled(false);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("TAG", ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, file.getPath());
sendData = pg.printDraw();
mService.write(sendData);
}
public void downloadContent() {
if (!edtContext.getText().toString().equals("") && !edtContext.getText().toString().equals("https://")) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(edtContext.getText().toString())
.build();
HttpService service = retrofit.create(HttpService.class);
Call<ResponseBody> result = service.getContent();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
if (response.body() != null) {
String summary = response.body().string();
webView.loadData(summary, "text/html; charset=utf-8", null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
public interface HttpService {
#GET("/")
Call<ResponseBody> getContent();
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
downloadContent();
} else if (v == btnClose) {
mService.stop();
} else if (v == btnSendDraw) {
printImage();
}
}
}
}
The result is almost what I want you can see by yourself, but the printed image is not clear:
I fixed it guys, this was the problem, the method siteToImage(). Here are the changes I hope it will helps someone:
private void siteToImage() {
webView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.setDrawingCacheEnabled(true);
webView.buildDrawingCache();
Bitmap b = Bitmap.createBitmap(webView.getMeasuredWidth(),
webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Paint paint = new Paint();
int iHeight = b.getHeight();
c.drawBitmap(b, 0, iHeight, paint);
webView.draw(c);
FileOutputStream fos;
try {
path = Environment.getExternalStorageDirectory().toString();
dir = new File(path, "/PrintDemo/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_" + System.currentTimeMillis() + ".jpg";
file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(PrintDemo.this, new String[]{imagePath},
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
b.compress(Bitmap.CompressFormat.PNG, 50, fos);
fos.flush();
fos.close();
b.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
I'm trying to use the google download manager for downloading main and patch expansion files which are both uploaded with the apk. I'm pretty much following the google example. The download process starts but immediately stops with 'STATE_COMPLETED'. No error but the files are still missing. The App only works if I manually copy the files to the device.
This is my Download Activity:
public class DownloadActivity extends Activity implements IDownloaderClient {
private IStub mDownloaderClientStub;
private IDownloaderService mRemoteService;
private boolean downloadDoneRegistered = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
startDownload();
}
#Override
protected void onResume() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(this);
}
super.onResume();
}
#Override
protected void onStop() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.disconnect(this);
}
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.download, menu);
return true;
}
// IDownloaderClient
#Override
public void onServiceConnected(Messenger m) {
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
#Override
public void onDownloadStateChanged(int newState) { //todo
switch (newState) {
case IDownloaderClient.STATE_IDLE:
case IDownloaderClient.STATE_CONNECTING:
case IDownloaderClient.STATE_FETCHING_URL:
case IDownloaderClient.STATE_DOWNLOADING:
break;
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
downloadFailed();
break;
case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
case IDownloaderClient.STATE_PAUSED_ROAMING:
case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
break;
case IDownloaderClient.STATE_COMPLETED:
downloadDone();
return;
default:
break;
}
}
#Override
public void onDownloadProgress(DownloadProgressInfo progress) {
float p = (float)progress.mOverallProgress;
if (progress.mOverallTotal>0) {
p /= (float)progress.mOverallTotal;
} else {
p = 0.0f;
}
String s = String.format(getString(R.string.download_progress).replace("#","%"),100.0f*p);
D.L(this,s);
setProgressBar(p);
setText(s);
}
//
private void startDownload() {
D.L(this,getString(R.string.download_checkfiles));
setProgressBar(0.0f);
setText(getString(R.string.download_checkfiles));
if (!expansionFilesDelivered()) {
D.L(this,"expansion files not downloaded so far");
setProgressBar(0.0f);
setText(String.format(getString(R.string.download_progress).replace("#","%"),0.0f));
try {
Intent launchIntent = DownloadActivity.this.getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent(DownloadActivity.this,DownloadActivity.this.getClass());
intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());
PendingIntent pendingIntent = PendingIntent.getActivity(DownloadActivity.this,0,intentToLaunchThisActivityFromNotification,PendingIntent.FLAG_UPDATE_CURRENT);
D.L(this,"start download service");
int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,pendingIntent,DownloadService.class);
D.L(this,""+startResult+" <-compare-> "+DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED+"=NO_DOWNLOAD_REQUIRED");
if (startResult!=DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
D.L(this,"-> download required, create stub");
setText(String.format(getString(R.string.download_progress).replace("#","%"),0.0f));
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub(this,DownloadService.class);
return;
} else {
D.L(this,"no download required");
downloadDone();
}
} catch (NameNotFoundException e) {
D.L(this,e.getMessage());
downloadFailed();
}
} else {
// validate apk zip files(?)
D.L(this,"expansion files valid, no download required");
downloadDone();
}
}
boolean expansionFilesDelivered() {
if ((Download.MAIN_EXISTS) &&
(!Helpers.doesFileExist(this,Helpers.getExpansionAPKFileName(this,true,Download.MAIN_VERSION),Download.MAIN_SIZE,false))) {
return false;
}
if ((Download.PATCH_EXISTS) &&
(!Helpers.doesFileExist(this,Helpers.getExpansionAPKFileName(this,false,Download.PATCH_VERSION),Download.PATCH_SIZE,false))) {
return false;
}
return true;
}
private void setProgressBar(float value) {
((ProgressBar)findViewById(R.id.progressBar)).setProgress((int)(1000.0f*value));
}
private void setText(String text) {
((TextView)findViewById(R.id.textView)).setText(text);
}
private void downloadDone() {
if (!downloadDoneRegistered) {
downloadDoneRegistered = true;
D.L(this,"downloadDone(): download terminated");
setProgressBar(1.0f);
setText(getString(R.string.download_completed));
boolean fileAccess = true;
if (Download.MAIN_EXISTS) {
Download.SetMainFile(safeFileAccess(Helpers.getExpansionAPKFileName(this,true,Download.MAIN_VERSION)));
fileAccess = fileAccess && (Download.GetMainFile()!=null);
} else {
D.L(this,"no main expansion file");
}
if (Download.PATCH_EXISTS) {
Download.SetPatchFile(safeFileAccess(Helpers.getExpansionAPKFileName(this,false,Download.PATCH_VERSION)));
fileAccess = fileAccess && (Download.GetPatchFile()!=null);
} else {
D.L(this,"no patch expansion file");
}
if (fileAccess) {
D.L(this,"file access passed");
T.StartActivity(this,SplashActivity.class,true);
} else {
fileAccessFailed();
}
}
}
private File safeFileAccess(String fileName) {
D.L(this,"try to access file...");
File r = new File(
Environment.getExternalStorageDirectory()+File.separator+
"Android"+File.separator+
"obb"+File.separator+
getPackageName() ,
fileName);
D.L(this," "+r);
if (r.exists()) {
D.L(this," passed");
} else {
D.L(this," failed");
r = null;
}
return r;
}
private void downloadFailed() {
D.L(this,getString(R.string.download_failed));
setText(getString(R.string.download_failed));
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.download_failed_dialogtext));
builder.setPositiveButton(getString(R.string.download_dialog_okay),new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
builder.create().show();
}
private void fileAccessFailed() {
D.L(this,getString(R.string.download_accessfailed));
setText(getString(R.string.download_accessfailed));
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.download_accessfailed_dialogtext));
builder.setPositiveButton(getString(R.string.download_dialog_okay),new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
builder.create().show();
}
}
My Alarm Receiver:
public class DownloadAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
DownloaderClientMarshaller.startDownloadServiceIfRequired(context,intent,DownloadService.class);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
My Download Service:
public class DownloadService extends DownloaderService {
#Override
public String getPublicKey() {
return Download.BASE64_PUBLIC_KEY;
}
#Override
public byte[] getSALT() {
return Download.SALT;
}
#Override
public String getAlarmReceiverClassName() {
return DownloadAlarmReceiver.class.getName();
}
}
Some data stuff:
public class Download {
private static Download Instance = new Download();
public static Download GetInstance() { return Instance; }
//todo
public static final String BASE64_PUBLIC_KEY = "..actual key..";
public static final byte[] SALT = new byte[] {..numbers..};
public static final boolean MAIN_EXISTS = true;
public static final int MAIN_VERSION = 2;
public static final long MAIN_SIZE = 20971520L;
public static final boolean PATCH_EXISTS = true;
public static final int PATCH_VERSION = 2;
public static final long PATCH_SIZE = 10485760L;
…
Any ideas?