I'm nearly finished with my App!
It's working fine, but there's a little mistake in it..
My App is an "Note"-App with some notes that are prefabricated and are the first opening of the app.
Therefore I save this notes at the first start and get them everytime I start the app again.
Unfortunately I'm have 66 prefabricated notes and they are all saved, but in the ListView there are only 45 or so in it..
I don't think it's something with syntax because the app works fine except the loss of 21 prefabricated notes
Here's my MainActivity Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean useDarkTheme = preferences.getBoolean(PREF_DARK_THEME, false);
SharedPreferences prefers = getApplicationContext().getSharedPreferences("prefs_daten", MODE_PRIVATE);
if (useDarkTheme) {
setTheme(R.style.AppTheme_dark);
}
super.onCreate(savedInstanceState);
if (VERBOSE) Log.v(TAG, "+ ON CREATE +");
setContentView(layout.activity_hauptmenu);
mListNotes = findViewById(id.listview);
itemTitel = new ArrayList<>();
itemTitel.addAll(Arrays.asList(string.Titel1, string.Titel2, string.Titel3, ...
string.Titel66));
itemStory = new ArrayList<>();
itemStory.addAll(Arrays.asList(string.Blackstory1, ...));
itemLosung = new ArrayList<>();
itemLosung.addAll(Arrays.asList(string.Losung1, ..));
}
private void StandardBS() {
if (Listensize==0){
anzahl_BS=66;
int a;
for(a=0; a<anzahl_BS; a++){
try{
tempTitel = getResources().getString(itemTitel.get(a));
tempStory = getResources().getString(itemStory.get(a));
tempLosung = getResources().getString(itemLosung.get(a));
Blackstory blackstory = new Blackstory(System.currentTimeMillis(), tempTitel, tempStory, tempLosung);
Log.w("Blackstory", ""+tempTitel);
Utilities.saveBlackstory(this, blackstory);
//Toast.makeText(this, "Blackstory wurde gespeichert!", Toast.LENGTH_SHORT).show();
}
catch (NullPointerException e){
//Toast.makeText(this, "Standard wurde falsch ausgeführt", Toast.LENGTH_SHORT).show();
}
}
Log.w("Anzahl", ""+a);
}
#Override
protected void onResume() {
super.onResume();
try{
mListNotes.setAdapter(null);
}
catch (NullPointerException e){
Toast.makeText(this, "not null", Toast.LENGTH_SHORT).show();
}
final ArrayList<Blackstory> blackstories = Utilities.getAllSavedBlackstory(getApplicationContext());
Listensize=blackstories.size();
anzahl_BS=Listensize;
if(blackstories != null && blackstories.size() > 0) { //check if we have any notes!
na = new BlackstoryAdapter(this, layout.item_layout1, blackstories);
try{
mListNotes.setAdapter(na);
}
catch (NullPointerException e){
Toast.makeText(this, "Irgendwas ist falsch2", Toast.LENGTH_SHORT).show();
}
//set click listener for items in the list, by clicking each item the note should be loaded into NoteActivity
try{
mListNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//run the NoteActivity in view/edit mode
fileName = ((Blackstory) mListNotes.getItemAtPosition(position)).getDateTime()
+ Utilities.FILE_EXTENSION;
Intent viewBlackstoryIntent = new Intent(getApplicationContext(), number1.class);
viewBlackstoryIntent.putExtra(Utilities.EXTRAS_NOTE_FILENAME, fileName);
startActivity(viewBlackstoryIntent);
}
});
mListNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//ask user if he really wants to delete the note!
Dialog_delete(position, id);
return true;
}});}
catch (NullPointerException e){
Toast.makeText(this, "Irgendwas ist falsch3", Toast.LENGTH_SHORT).show();
}}
else { //remind user that we have no notes!
Toast.makeText(getApplicationContext(), "you have no saved notes!\ncreate some new notes :)"
, Toast.LENGTH_SHORT).show();
}
firstOpen=false;
}
My Utilities (to save and load notes):
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static final String EXTRAS_NOTE_FILENAME = "EXTRAS_NOTE_FILENAME";
public static boolean saveBlackstory(Context context, Blackstory blackstory){
String fileName = String.valueOf(blackstory.getDateTime()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try{
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(blackstory);
oos.close();
}
catch (IOException e) {
e.printStackTrace();
Log.w("Failed","");
return false;
}
return true;
}
public static ArrayList<Blackstory> getAllSavedBlackstory(Context context) {
ArrayList<Blackstory> blackstories = new ArrayList<>();
File filesDir = context.getFilesDir();
ArrayList<String> blackstoryFiles = new ArrayList<>();
int size = blackstoryFiles.size();
//add .bin files to the noteFiles list
for(String file : filesDir.list()) {
if(file.endsWith(FILE_EXTENSION)) {
blackstoryFiles.add(file);
Log.w("Included", ""+file);
}
}
//read objects and add to list of notes
FileInputStream fis;
ObjectInputStream ois;
for (int i = 0; i < blackstoryFiles.size(); i++) {
try{
fis = context.openFileInput(blackstoryFiles.get(i));
ois = new ObjectInputStream(fis);
blackstories.add((Blackstory)ois.readObject());
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return blackstories;
}
public static Blackstory getBlackstoryByFileName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
if(file.exists() && !file.isDirectory()) { //check if file actually exist
Log.v("UTILITIES", "File exist = " + fileName);
FileInputStream fis;
ObjectInputStream ois;
try { //load the file
fis = context.openFileInput(fileName);
ois = new ObjectInputStream(fis);
Blackstory note = (Blackstory) ois.readObject();
fis.close();
ois.close();
return note;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
public static boolean deleteFile(Context context, String fileName) {
File dirFiles = context.getFilesDir();
File file = new File(dirFiles, fileName);
if(file.exists() && !file.isDirectory()) {
return file.delete();
}
return false;
}
And my Adapter:
public class BlackstoryAdapter extends ArrayAdapter<Blackstory> {
public static final int WRAP_CONTENT_LENGTH = 50;
public BlackstoryAdapter(Context context, int resource, List<Blackstory> blackstories) {
super(context, resource, blackstories);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_layout1, null);
}
Blackstory blackstory = getItem(position);
if(blackstory != null) {
TextView title = convertView.findViewById(R.id.single_titel);
title.setText(blackstory.getTitel());
}
return convertView;
}
My Blackstory.java:
public class Blackstory implements Serializable {
private String mTitel;
private String mStory;
private String mLosung;
private long mDateTime;
public Blackstory(long dateInMills, String titel, String story, String losung) {
mDateTime = dateInMills;
mTitel = titel;
mStory = story;
mLosung = losung;
}
public void setDateTime(long dateTime) {
mDateTime = dateTime;
}
public long getDateTime() {
return mDateTime;
}
public String getDateTimeFormatted(Context context) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"
, context.getResources().getConfiguration().locale);
formatter.setTimeZone(TimeZone.getDefault());
return formatter.format(new Date(mDateTime));
}
public String getTitel() {
return mTitel;
}
public void setTitel(String titel) {
mTitel = titel;
}
public String getStory() {
return mStory;
}
public void setStory(String story) {
mStory = story;
}
public String getLosung() {
return mLosung;
}
public void setLosung(String losung) {
mLosung = losung;
}
}
There need not be getCount() method as pointed out by AguThadeus. The array data is passed to the superclass so that will take care of the number of views.
Related
I have created a ImageLoading class which downloads and saves data to local storage. I am also calling it from multiple activities. After saving I need to update collection of class from which the instance of asyncTask is created. I don't want to use if statements in task to handle this and I don't want to inherit this task to other activities. Please Suggest me how to do this. I am sharing my code here.
public class LoadImageTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
private long ID;
private Context context;
private SQLiteHandler sqLiteHandler;
private String imageType;
private int position;
public LoadImageTask(String url, ImageView imageView, long ID, Context context, String imageType, int position) {
this.url = url;
this.imageView = imageView;
this.ID = ID;
this.context = context;
this.imageType = imageType;
this.position = position;
sqLiteHandler = new SQLiteHandler(context);
}
String getRandomString(int length)
{
String data = "";
Random rand = new Random();
for (int i = 1 ; i <= length ; i++) {
int n = rand.nextInt(26) + 97;
data += String.valueOf((char)n);
}
return data;
}
private File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getPackageName()
+ "/Files");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmssSSS").format(new Date());
timeStamp = String.format("%s_%s", timeStamp, getRandomString(10));
File mediaFile;
String mImageName="Image_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("Error:","Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
ImageDownload imageDownload = new ImageDownload(ID,pictureFile.getAbsolutePath());
if(imageType.equals(Constants.ImageType.PROFILE)) {
sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.PROFILE);
}
else if(imageType.equals(Constants.ImageType.BANNER)) {
sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.BANNER);
}
else if(imageType.equals(Constants.ImageType.SUBJECT)) {
if(sqLiteHandler.UpdateUserImagePath(imageDownload,Constants.ImageType.SUBJECT)){
((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
//((MainActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
//((MessageList) context).messageDataItems.get(position).SubjectImage = imageDownload.ImagePath;
}
}
} catch (FileNotFoundException e) {
Log.d("Error:", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Error:", "Error accessing file: " + e.getMessage());
}
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
Drawable d = new BitmapDrawable(imageView.getResources(), result);
imageView.setBackground(d);
storeImage(result);
//imageView.setImageBitmap(result);
}
}
Simply just do it like this :
((AppCompatActivity) context).subjectsItems.get(position).Image = imageDownload.ImagePath;
hello i'm trying to save pictures taken from url on my application, but when i try to access the memory to place the data, an error comes out
unable to decode stream java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory)
this is my DownloadManager Class
public static ArrayList<String> urls = new ArrayList<String>();
public static OnDownloadCompleteListener downloadCompleteListener;
public static void copyFile(String sourceFile, String destinationFile) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void initialize() {
downloadCompleteListener = new OnDownloadCompleteListener() {
#Override
public void onDownloadComplete(String url, String localPath) {
Log.i("LOG", "Image Download Complete, Original URL: " + url + ", Save Path: " + localPath);
String newPath = localPath.replace("/temp/", "/final/");
copyFile(localPath, newPath);
String filename = HelperString.getFileName(localPath);
new File(localPath).delete();
Set<ImageView> imageViews = AdapterSerials.imageMap.keySet();
for (ImageView imageView: imageViews) {
if (AdapterSerials.imageMap.get(imageView).equals(filename)) {
if (imageView != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(newPath, options);
imageView.setImageBitmap(bitmap);
}
}
}
}
};
}
public static void addToDownloadList(String url, ImageView imgLogo) {
String filename = HelperString.getFileName(url);
AdapterSerials.imageMap.put(imgLogo, filename);
if (urls.contains(url)) {
return;
}
if (new File(G.DIR_FINAL + "/" + filename).exists()) {
return;
}
urls.add(url);
DownloadRequest downloadRequest = new DownloadRequest()
.downloadPath("http://87.236.215.180/mazi/" + url)
.filepath(G.DIR_TEMP + "/" + filename)
.listener(downloadCompleteListener)
.download();
}
this is my DownloadRequest Class :
public class DownloadRequest {
private int downloadedSize;
private int totalSize;
private int percent;
public int getDownloadedSize() {
return downloadedSize;
}
public int getTotalSize() {
return totalSize;
}
public int getPercent() {
return percent;
}
public DownloadRequest download() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
totalSize = connection.getContentLength();
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
percent = (int) (100.0f * (float) downloadedSize / totalSize);
if (percent == 100 && listener != null) {
G.HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onDownloadComplete(downloadPath, filepath);
}
});
}
if (simulate) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return this;
}
private String downloadPath;
private String filepath;
private OnDownloadCompleteListener listener;
private boolean simulate;
public DownloadRequest downloadPath(String value) {
downloadPath = value;
return this;
}
public DownloadRequest filepath(String value) {
filepath = value;
return this;
}
public DownloadRequest listener(OnDownloadCompleteListener value) {
listener = value;
return this;
}
public DownloadRequest simulate(boolean value) {
simulate = value;
return this;
}
And this is my G class :
public class G extends Application {
public static Context context;
public static final String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_APP = SDCARD + "/serial";
public static final String DIR_CACHE = DIR_APP + "/cache";
public static LayoutInflater inflater;
public static final Handler HANDLER = new Handler();
public static Activity currentActivity;
public static StructSerials selectedSerials;
public static StructFavSerials selectedFavSerials;
public static ArrayList<StructComment> rates = new ArrayList<StructComment>();
public static final int DOWNLOAD_BUFFER_SIZE = 8 * 1024;
public static final String DIR_FINAL = DIR_APP + "/final";
public static final String DIR_TEMP = DIR_APP + "/temp";
public static String android_id;
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
preferences = PreferenceManager.getDefaultSharedPreferences(context);
initImageLoader(getApplicationContext());
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
new File(DIR_APP).mkdirs();
new File(DIR_CACHE).mkdirs();
new File(DIR_TEMP).mkdirs();
new File(DIR_FINAL).mkdirs();
DownloadManager.initialize();
}
remember add this permission into your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have an ArrayList<String> that I save in shared preference in Activity A. I access the list from a second activity (ListActivity). Activity A starts ListActivity for a result. When an item is clicked the ListActivity sends the string at that position to Activity A for use. A long click allows you to delete.
When I delete from the list, I want to save the new (the latest) list in sharedpreferences. PLEASE! How can I do this? I just need the List to popup, you do your thing, and it goes away after saving the newest list.
I tried so many ways (code is patchwork at this point) but the deleted item persists when I open ListActivity again after deleting the item.
My code is below...
Activity A:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
...
lyricTitle = (AutoCompleteTextView) findViewById(R.id.lyricTitle);
...
lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// load in song when selected from auto-complete list
lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
}
});
lyricHolder = (EditText) findViewById(R.id.lyricHolder);
newSongBtn = (ImageView) findViewById(R.id.newSongBtn);
newSongBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (areFieldsNull(lyricTitle.getText().toString(),
lyricHolder.getText().toString()))
alertEmpty.show();
else {
/** There is some redundancy within performSave() here */
performSave();
lyricTitle.setText("");
lyricHolder.setText("");
}
}
});
...
findBtn = (Button) findViewById(R.id.findBtn);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showListIntent = new Intent(getApplicationContext(), pickActivity.class);
startActivityForResult(showListIntent, GET_SONG_CODE);
Log.i("TAG1", "Starting pickActivity.class for result");
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
...
// init sharedPreferences
colorPref = getSharedPreferences(COLOR_PREF, MODE_PRIVATE);
titlePref = getSharedPreferences(TITLE_PREF, MODE_PRIVATE);
externalSDPref = getSharedPreferences(EXTERNAL_SD_PREF, MODE_PRIVATE);
// load defaults of sharedPreferences
titleList = new ArrayList<>();
try {
titleList = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetTitleListAdapter(titleList);
...
} //end onCreate
private void mSetTitleListAdapter(ArrayList<String> List) {
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
List
);
lyricTitle.setAdapter(autoCompleteAdapter);
}
...
private boolean areFieldsNull(String title, String song) {
// check if the text fields are empty
return (
title.isEmpty()||
title.equals(" ")||
title.equals(" ")||
song.isEmpty()||
song.equals(" ")||
song.equals(" ")
);
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
alertSave.show();
}
else
alertEmpty.show();
}
private void saveTitleArray() {
// save string array list in shared prefs
try {
prefEditor = titlePref.edit();
prefEditor.putString(TITLE_PREF, ObjectSerializer.serialize(titleList));
} catch (IOException e) {
e.printStackTrace();
}
prefEditor.apply();
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isExternalStoragePresent()&&externalSD_box.isChecked()){
// save to the SD card IF SD is found AND enableSD_box is checked
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File songFile = new File (path, title + ".txt");
try {
OutputStream os = new FileOutputStream(songFile);
byte[] data = song.getBytes();
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
// new songs (but not updated songs) go to top
if (!titleList.contains(title))
titleList.add(0, title);
mSetTitleListAdapter(titleList);
saveTitleArray();
}
private String openSongFile(String title){
BufferedReader bufferReader = null;
StringBuilder builder = new StringBuilder();
try {
FileInputStream fis = openFileInput(title);
bufferReader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = bufferReader.readLine()) != null) {
builder.append(line + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// when pickActivity ListView returns result
Log.i("TAG1", "Activity data returned from pickActivity.class");
if (requestCode == GET_SONG_CODE && resultCode == RESULT_OK) {
String title = data.getData().toString();
lyricTitle.setText(title);
lyricHolder.setText(openSongFile(title));
Log.i("TAG1", "Result success\nSong loaded into edittext");
Toast.makeText(this, "\""+title+"\""+" selected", Toast.LENGTH_SHORT).show();
}
}
ListActivity:
public class pickActivity extends ListActivity {
ArrayList<String> songListArray;
SharedPreferences titlePref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_song);
Log.i("TAG2", "pickActivity.class created");
// init string array from blank list or sharedPref saved data
titlePref = getSharedPreferences(writeActivity.TITLE_PREF, MODE_PRIVATE);
songListArray = new ArrayList<>();
try {
songListArray = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(writeActivity.TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetListAdapter(songListArray);
Log.i("TAG2", "Extra received and set");
mSetListAdapter(songListArray);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Log.i("TAG2", "onItemLongClick()");
final AlertDialog.Builder confirmDel = new AlertDialog.Builder(pickActivity.this);
confirmDel.setTitle("Delete Song")
.setIcon(R.mipmap.ic_keeper)
.setMessage("Are you sure you want " +
"\"" + songListArray.get(position) +
"\"" + " gone?")
.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// system default is dismiss()
}
})
.setNegativeButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// delete song, title, then update title list
getApplicationContext().deleteFile(songListArray.get(position));
songListArray.remove(position);
Log.i("TAG2", "Item deleted from list");
updateSharedPref(titlePref, writeActivity.TITLE_PREF, songListArray);
mSetListAdapter(songListArray);
Toast.makeText(
getApplicationContext(),
"Deleted",
Toast.LENGTH_SHORT).show();
}
});
confirmDel.create().show();
return true;
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("TAG2", "onListItemClick()");
Intent resultIntent = new Intent(EXTRA_NAME, Uri.parse(songListArray.get(position)));
setResult(RESULT_OK, resultIntent);
finish();
}
private void mSetListAdapter(ArrayList<String> list) {
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);
setListAdapter(arrayAdapter);
Log.i("TAG2", "ArrayList adapter set");
}
private void updateSharedPref(SharedPreferences sharedPref,
String prefFileName,
ArrayList<String> list) {
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString(prefFileName, ObjectSerializer.serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Log.i("TAG2", "SharedPref updated!");
}
}
Honestly, source code would help a lot in this case...
My best guess (without any code) would be, please make sure that you call
editor.apply();
and not
editor.commit();
i am trying to implement a pdf reader via a pdf library from git hub https://github.com/jblough/Android-Pdf-Viewer-Library but when i implement the code.. all i am getting is a blank page.. the url is correct the pdf has content and this is similar to this q .. Example of code to implement a PDF reader
my code consist of multiple methods, the main method is used to select the which pdf should be chosen to display. then the pdf name is passed on to method "copyreadassets"
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getApplicationContext().getFilesDir() + "/"+url;
openPdfIntent(path); }
the openpdfintentmethod is used to open the values
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
pdf.class contains the following..
public class Pdf extends Activity{
public int getPreviousPageImageResource() {
return R.drawable.left_arrow; }
public int getNextPageImageResource() {
return R.drawable.right_arrow; }
public int getZoomInImageResource() {
return R.drawable.zoom_in; }
public int getZoomOutImageResource() {
return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() {
return R.id.etPassword; }
public int getPdfPasswordOkButton() {
return R.id.btOK; }
public int getPdfPasswordExitButton() {
return R.id.btExit; }
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit; }
}
In your AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<activity android:name="com.example.readassetpdf.myPDFActivity"></activity>
in your case activity is pdf class
<activity android:name="com.example.readassetpdf.pdf"></activity>
and use following method
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
//out = getApplicationContext().openFileOutput(file.getName(),
//Context.MODE_WORLD_READABLE);
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf";
openPdfIntent(path);
}
and call it as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
CopyReadAssets("mypdf.pdf");
}
And the function copyfile is as below
private void copyFile(InputStream in, OutputStream out) throws IOException{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
The replacement is
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
to
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
I'm editing an open source app: A simple coloring page app for kids. I need to be able to make the user import his own images to be colored. Here is the full source code.
And here is the code for loading images from R.drawable:
public class StartNewActivity extends NoTitleActivity implements View.OnClickListener
{
// This is an expensive operation.
public static int randomOutlineId()
{
return new ResourceLoader().randomOutlineId();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Apparently this cannot be set from the style.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.start_new);
GridView gridview = (GridView) findViewById(R.id.start_new_grid);
gridview.setAdapter(new ImageAdapter(this));
}
public void onClick(View view)
{
setResult(view.getId());
finish();
}
private static class ResourceLoader
{
ResourceLoader()
{
// Use reflection to list resource ids of thumbnails and outline
// images.First, we list all the drawables starting with the proper
// prefixes into 2 maps.
Map<String, Integer> outlineMap = new TreeMap<String, Integer>();
Map<String, Integer> thumbMap = new TreeMap<String, Integer>();
Field[] drawables = R.drawable.class.getDeclaredFields();
for (int i = 0; i < drawables.length; i++)
{
String name = drawables[i].getName();
try
{
if (name.startsWith(PREFIX_OUTLINE))
{
outlineMap.put(name.substring(PREFIX_OUTLINE.length()),
drawables[i].getInt(null));
}
if (name.startsWith(PREFIX_THUMB))
{
thumbMap.put(name.substring(PREFIX_THUMB.length()),
drawables[i].getInt(null));
}
}
catch (IllegalAccessException e)
{
}
}
Set<String> keys = outlineMap.keySet();
keys.retainAll(thumbMap.keySet());
_outlineIds = new Integer[keys.size()];
_thumbIds = new Integer[keys.size()];
int j = 0;
Iterator<String> i = keys.iterator();
while (i.hasNext())
{
String key = i.next();
_outlineIds[j] = outlineMap.get(key);
_thumbIds[j] = thumbMap.get(key);
j++;
}
}
public Integer[] getThumbIds()
{
return _thumbIds;
}
public Integer[] getOutlineIds()
{
return _outlineIds;
}
public int randomOutlineId()
{
return _outlineIds[new Random().nextInt(_outlineIds.length)];
}
private static final String PREFIX_OUTLINE = "outline";
private static final String PREFIX_THUMB = "thumb";
private Integer[] _thumbIds;
private Integer[] _outlineIds;
}
private class ImageAdapter extends BaseAdapter
{
ImageAdapter(Context c)
{
_context = c;
_resourceLoader = new ResourceLoader();
}
public int getCount()
{
return _resourceLoader.getThumbIds().length;
}
public Object getItem(int i)
{
return null;
}
public long getItemId(int i)
{
return 0;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null)
{
// If it's not recycled, initialize some attributes
imageView = new ImageView(_context);
imageView.setLayoutParams(new GridView.LayoutParams(145, 145));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setOnClickListener(StartNewActivity.this);
}
else
{
imageView = (ImageView) convertView;
}
imageView.setImageResource(_resourceLoader.getThumbIds()[position]);
imageView.setId(_resourceLoader.getOutlineIds()[position]);
return imageView;
}
private Context _context;
private ResourceLoader _resourceLoader;
}
}
You can use File to write the imported file of the user. Use something like this.
public boolean write(byte[] data, File file)
{
if (file.getParentFile().exists()) {
if (file.exists()) {
file.delete();
}
} else {
file.getParentFile().mkdirs();
}
try{
OutputStream output = new FileOutputStream(file);
output.write(data);
output.close();
return true;
}catch(Exception e){
Log.v("FileManager", "Error writing file.", e);
return false;
}
}
Sample:
String pathName = "/mnt/sdcard/Android/data/com.company.project/files/tmp/photo.png";
Bitmap bmp = BitmapFactory.decodeFile(pathName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
write(byteArray, new File("/mnt/sdcard/Android/data/com.company.project/files/photo.png");