Grid view taking time to load - android

I have a grid view on onCreate I am creating a grid view getting image url the from local database But when that activity is loading it showing a white screen.
How to remove that white screen I don't know where to move this gredview.A am attachig the full code please tell me what should I do.Try to click the sync button that sync button will first clear the local database then it get all xml value from server and put that into local database after that this activity will be restarted then this onCreat method will be called and blank white screen will be shown.
CODE URL http://www.fileconvoy.com/dfl.php?id=g2561f0a6e7dcc50b9992656609078e5c6d63c814c
My code follows
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
String pdfPath = Environment.getExternalStorageDirectory().toString() + "/ICA Faculty/";
Toast.makeText(getApplicationContext(),pdfPath+((TextView) v.findViewById(R.id.hiddenPdfUrl)).getText(), Toast.LENGTH_SHORT).show();
try {
File file = new File(pdfPath+((TextView) v.findViewById(R.id.hiddenPdfUrl)).getText());
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Sorry no PDF reader found.", Toast.LENGTH_SHORT).show();
}
}
});
File folder = new File(Environment.getExternalStorageDirectory() + "/ICA Faculty");
db.open();
c = db.getAllRecords();
//If data exist in local database AND "ICA Faculty" folder exist
//Getting the sd card file name from local database
if (c.moveToFirst() && folder.exists() && folder.listFiles() != null)
{
//This array list will help to create image
imgUrl = new ArrayList<String>();
pdfUrl = new ArrayList<String>();
do
imgUrl.add(c.getString(3));
pdfUrl.add(c.getString(2));
} while (c.moveToNext());
ImageAdapter adapter = new ImageAdapter(MainActivity.this);
gridview.setAdapter(adapter);
}
else
{
Toast.makeText(getApplicationContext(), "You need to sync to create your library.", Toast.LENGTH_LONG).show();
}
db.close();
}

The GridView, as subclass of AdapterView, can use an empty view to show when there is no data by the setEmptyView() method.
For examples look at this question Correct use of setEmtpyView in AdapterView

Related

How to retrieve an image converted to byte array from sqlite db and place it in RecyclerView?

I'm stuck in problem. It's one of my first android apps and I don't know how to overcome this thing. My problem is i have a SQLite database in which I am saving an image converted to byte array and some more data but when I am retrieving that data and want to show in RecyclerView then image is not showing up in RecyclerView list. Other data is displayed properly, but image field is empty. Does anyone know what is wrong in my code?
That's how I'm trying to set a list item in adapter (onBindViewHolder):
byte[] image = selectedGame.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
gameItemView.imageGame.setImageBitmap(bitmap);
It's my GameListActivity where I fill list with gamesData:
gamesRecyclerView = findViewById(R.id.gamesRecyclerView);
gamesData = new ArrayList<>();
gamesAdapter = new GamesAdapter(gamesData);
((GamesAdapter) gamesAdapter).setGamesActivity(this);
Cursor cursor = db.getGames();
gamesData.clear();
if(cursor.getCount() == 0){
Toast.makeText(getApplicationContext(), "No games in database", Toast.LENGTH_SHORT).show();
}
else {
while (cursor.moveToNext()) {
gamesData.add(new Game(cursor.getInt(cursor.getColumnIndex("Id")),
cursor.getString(cursor.getColumnIndex("gameTitle")),
cursor.getString(cursor.getColumnIndex("gameGenre")),
cursor.getInt(cursor.getColumnIndex("year")),
cursor.getString(cursor.getColumnIndex("gameDescription")),
cursor.getInt(cursor.getColumnIndex("gamePC")),
cursor.getInt(cursor.getColumnIndex("gamePS3")),
cursor.getInt(cursor.getColumnIndex("gamePS4")),
cursor.getInt(cursor.getColumnIndex("gameXONE")),
cursor.getInt(cursor.getColumnIndex("gameX360")),
cursor.getInt(cursor.getColumnIndex("gameNINTENDO")),
cursor.getInt(cursor.getColumnIndex("likesCount")),
cursor.getBlob(cursor.getColumnIndex("image"))
));
}
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
gamesRecyclerView.setAdapter(gamesAdapter);
gamesRecyclerView.setLayoutManager(layoutManager);
Here I'm adding a game to database (that's interesting that when I'm trying to get all games after adding some game then it prints out wrong array of bytes):
btnAddYourGame.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try{
byte[] gameImage = imageViewToByte(image);
System.out.println(gameImage.length);
Boolean checkGame = openHelper.checkIfGameExists(title);
if (checkGame == true) {
openHelper.addGame(title, genre, year, description, pcAvailable, ps3Available, ps4Available, x360Available, xoneAvailable, nintendoAvailable, gameImage);
Cursor cursor = openHelper.getGames();
while (cursor.moveToNext()) {
System.out.println(cursor.getBlob(cursor.getColumnIndex("image")).length);
}
Toast.makeText(getApplicationContext(), getResources().getString(R.string.action_game_add_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), getResources().getString(R.string.action_game_add_failed), Toast.LENGTH_SHORT).show();
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
});

How to get into the Downloads Folder to load all the pictures?

I want to add the downloads folder to my code,
this is my helper class (File Paths):
//"storage/emulated/0" = Environment.getExternalStorageDirectory().getPath().
public String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
public String PICTURES = ROOT_DIR + "/Pictures";
public String CAMERA = ROOT_DIR + "/DCIM/camera";
public String DOWNLOADS = ROOT_DIR + "/Download";
and this my class where I use this paths
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if(FileSearch.getDirectoryPaths(filePaths.PICTURES) != null){
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
ArrayList<String> directoryNames = new ArrayList<>();
for(int i = 0; i < directories.size(); i++){
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
directories.add(filePaths.CAMERA);
directories.add(filePaths.DOWNLOADS);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, directories); // WARUM
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup image grid for the directory chosen
setupGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
If I cut the downloads part out, I get all the files of the other paths but if the downloads part is inside my code, I got an Exception because the downloads files arent added to the arrayList later.
I need the correct path for the downloads.
I found this:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
but this returns me a file and I need a String in my helper class.
EDIT:
Sorry, it was my fault. I got the Exception because I didnt had any pictures in my other directories. After I inserted one, my Downloads Folder was showed. I solved this error with try and catch now.
You can get String path from File like this
String path = file.toURI().toString();

How to get videos in GridView from **SDCard/folder/subfolder"

I have to fetch all the videos from "/SDCard/Folder/SubFolder" and display them in a GridView.
I am able to save the videos into the desired subfolder created by me and can see them directly from the folder. But I want to show them into a GridView but when I am running my code, It displays nothing but only a black blank screen. Here is my code, please tell me that what mistake I am doing here..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview_main);
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/SDCard/Picture/MyCameraVideo");
// Create a new folder if no folder named SDImageTutorial exist
file.mkdirs();
}
if (file.isDirectory()) {
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++) {
// Get the path of the image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
// Locate the GridView in gridview_main.xml
grid = (GridView) findViewById(R.id.gridview);
// Pass String arrays to LazyAdapter Class
adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
// Set the LazyAdapter to the GridView
grid.setAdapter(adapter);
// Capture gridview item click
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(ViewActivity.this, ViewImage.class);
i.putExtra("filepath", FilePathStrings);
i.putExtra("filename", FileNameStrings);
i.putExtra("position", position);
startActivity(i);
}
});
}
}

List all the folder and files of Dropbox using Dropbox API

Am looking for the tutorial to display all the files and folder in a listview..but I didn't get anything..Does anyone here know that how can I show all the folder and files of Dropbox into my listview..So that when I click on any of the file..Then that file starts download..
Well I know here that How to download a file from Dropbox, but for that I need to put that name of the file in my code in a static way..
I am also going to use filter afterwards for .csv file only...but I want to show all the files in a listview.
Thanks..
String[] fnames = null;
Entry dirent = mApi.metadata("/", 1000, null, true, null);
ArrayList<Entry> files = new ArrayList<Entry>();
ArrayList<String> dir=new ArrayList<String>();
for (Entry ent: dirent.contents)
{
files.add(ent);// Add it to the list of thumbs we can choose from
//dir = new ArrayList<String>();
dir.add(new String(files.get(i++).path));
}
i=0;
fnames=dir.toArray(new String[dir.size()]);
return fnames;
This is what i use.
once you have stringarray fnames,you can display it in a listview.
You can display it in a gridview like this
final GridView gv=(GridView)temp.findViewById(R.id.gridView1);
ArrayAdapter<String> ad = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1,fnames);
gv.setBackgroundColor(Color.BLACK);
gv.setNumColumns(3);
gv.setGravity(Gravity.CENTER);
gv.setAdapter(ad);
gv.setBackgroundResource(R.drawable.black_cloud1);
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(mContext,gv.getItemAtPosition(arg2).toString(),Toast.LENGTH_SHORT).show();
temp.setData(fnames,gv.getItemAtPosition(arg2).toString());
return;
}
});
Try this code to list the files.....I don't know more about Dropbox, try it
Entry contact = mDBApi.metadata("/", 0, null, true, null);
List<Entry> CFolder = contact.contents;
for (Entry entry : CFolder) {
Log.i("DbExampleLog", "Filename: " + entry.fileName());}
please use this one , it is the latest api .....
public void login(String accessToken) {
DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder("ManualApp")
.withHttpRequestor(OkHttp3Requestor.INSTANCE)
.build();
mDbxClient = new DbxClientV2(requestConfig, accessToken);
}
public List<Metadata> getListFile(String path) {
if (mDbxClient == null) {
RkLogger.e("get files error", "must login first please");
return null;
}
try {
return mDbxClient.files().listFolder(path).getEntries();
} catch (DbxException e) {
RkLogger.e("DbxException ", e.toString());
return null;
}
}

Android : Load image from specific directory

I have a gallery that is displaying thumbnail images in custom directories. The gallery displays fine, but I am unable to open the full image by clicking the thumbnail. My [non functioning] click listener is below
try {
if (LoadImageFiles() == true) {
GridView imgGallery = (GridView) findViewById(R.id.gallery);
final ImageAdapter ia = new ImageAdapter(PersonMedia.this);
imgGallery.setAdapter(ia);
// Set up a click listener
imgGallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String imgPath = paths.get(position);
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", imgPath);
startActivity(intent);
}
});
}
} catch (Exception ex) {
Log.e("PersonMedia.LoadPictures", ex.getMessage());
}
Here is how the gallery is populated
//Declare a module level hashtable
private Hashtable<Integer, String> paths;
private boolean LoadImageFiles() {
try{
mySDCardImages = new Vector<ImageView>();
paths = new Hashtable<Integer, String>();
fileCount = 0;
sdDir = new File(imageDirectory);
sdDir.mkdir();
if (sdDir.listFiles() != null)
{
File[] sdDirFiles = sdDir.listFiles();
if (sdDirFiles.length > 0)
{
for (File singleFile : sdDirFiles)
{
Bitmap bmap = decodeFile(singleFile);
BitmapDrawable pic = new BitmapDrawable(bmap);
ImageView myImageView = new ImageView(PersonMedia.this);
myImageView.setImageDrawable(pic);
myImageView.setId(mediaCount);
paths.put(fileCount, singleFile.getAbsolutePath());
mySDCardImages.add(myImageView);
mediaCount++;
fileCount ++;
}
}
}
}
catch(Exception ex){ Log.e("LoadImageFiles", ex.getMessage()); }
return (fileCount > 0);
}
I was able to resolve this by using a hashtable to store the position and path of the images when the thumbnails are loaded. Below are the 2 pertinent code snippets
//Where the gallery is populated and the onclick is defined
private void PopulateGallery() {
try {
if (LoadImageFiles() == true) {
GridView imgGallery = (GridView) findViewById(R.id.gallery);
imgGallery.setAdapter(new ImageAdapter(PersonMedia.this));
// Set up a click listener
imgGallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String imgPath = paths.get(position);
Intent intent = new Intent(getApplicationContext(), ViewImage.class);
intent.putExtra("filename", imgPath);
startActivity(intent);
}
});
}
} catch (Exception ex) {
Log.e("PersonMedia.LoadPictures", ex.getMessage());
}
}
//Where the images are loaded. You'll need to create a module level hashtable
private Hashtable<Integer, String> paths;
private boolean LoadImageFiles() {
try{
mySDCardImages = new Vector<ImageView>();
paths = new Hashtable<Integer, String>();
fileCount = 0;
sdDir = new File(imageDirectory);
sdDir.mkdir();
if (sdDir.listFiles() != null)
{
File[] sdDirFiles = sdDir.listFiles();
if (sdDirFiles.length > 0)
{
for (File singleFile : sdDirFiles)
{
Bitmap bmap = decodeFile(singleFile);
BitmapDrawable pic = new BitmapDrawable(bmap);
ImageView myImageView = new ImageView(PersonMedia.this);
myImageView.setImageDrawable(pic);
myImageView.setId(mediaCount);
paths.put(fileCount, singleFile.getAbsolutePath());
mySDCardImages.add(myImageView);
mediaCount++;
fileCount ++;
}
}
}
}
catch(Exception ex){ Log.e("LoadImageFiles", ex.getMessage()); }
return (fileCount > 0);
}
Do your images have extensions, such as .jpg or .png? I'm not quite sure but it looks like you are looking for an image that is string version of your personId, without any file extension.
Please correct me if I'm wrong.
Also please post more details, such as the errors you are getting.
Updated answer below.
Use View.setTag(Object), when you are adding items to your ListView (I am guessing). You can call something like the following.
view.setTag("imgFile.jpg");
And then from inside of your onClickListener, just do this:
String img = (String) getTag();

Categories

Resources