Android Gridview is not showing images from assets folder - java

I have a specific problem which has not be answered yet on stackoverflow; I have images in the assets folder numbered like 0.jpg, 1.jpg, 2.jpg etc. Using a for loop I select three images from the asssets folder and I am trying to add these images to a gridview but the images are not showing. The activity starts up okay just no images!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
gridView = (GridView) findViewById(R.id.gridview_result);
// Sets the Tag
gridView.setTag(GRIDVIEW_TAG);
/*
* Adapt the image for the GridView format
*/
imageAdapter = new ImageGridViewAdapter(getApplicationContext());
gridView.setAdapter(imageAdapter);
// Set the orientation to landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// Retrieve 3 images form the database which appear
// similar
for (int i = 0; i < 3; i++) {
// System.out.println(Retrieval.distances[i][0]);
image = Retrieval.distances[i][0];
int num = (int) image;
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(num);
String imageNum = sBuilder.toString();
System.out.println(imageNum);
String file = imageNum + ".jpg";
try {
// get input stream
InputStream ims = getAssets().open(file);
Log.i("ERROR_IMS", ims + "");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, file);
// set image to ImageView
gridView.setBackground(d);
Log.i("ERROR_d", d + "");
Log.i("ERROR_gridview", gridView+"");
} catch (IOException ex) {
Log.e("I/O ERROR", "Failed when ...");
}
}
}
I believe the issue is occurring in the try/catch. Any help will be much appreciated!

You should get all images first and set it to your adapter.
// set image to ImageView
gridView.setBackground(d);
doesn't affect to your grid items view.
A good tutorial for it: guide

Related

Show random images in imageview from assest folder in xml

I want to add images from asses to an imageview automatically. the below code does work well when images are in a drawable folder, but I want to create a separate folder name avatar in the asset folder and get random images from there in my imageview.
int[] images = new int[] {R.drawable.image01, R.drawable.image02, R.drawable.image03};
// Get the ImageView
setContent(R.layout.main);
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
// Get a random between 0 and images.length-1
int imageId = (int)(Math.random() * images.length);
// Set the image
mImageView.setBackgroundResource(images[imageId]);
Thanks in advance.
I suggest you to use AssetManager.list()
To list all the assets for the given folder within /assets folder, we use AssetManager.list(). Suppose we have some files within /assets/img and we need to list all those files, then we write code as follows.
String[] imgPath = assetManager.list("img");
Here we get String array of file names within img directory.
try {
String[] imgPath = assetManager.list("img");
for (int i = 0; i< imgPath.length; i++) {
InputStream is = assetManager.open("img/"+imgPath[i]);
Log.d(TAG, imgPath[i]);
Bitmap bitmap = BitmapFactory.decodeStream(is);
imageViewbyCode = new ImageView(this);
imageViewbyCode.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imageViewbyCode.setLayoutParams(params);
myLayout.addView(imageViewbyCode);
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
Please try below code:-
AssetManager assetManager = getAssets();
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
InputStream inputStream = assetManager.open("yourimage.jpg")
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
mImageView.setImageBitmap(bitmap);

how to plot a graph with a CSV file?

I want to plot a diagram in android with GraphView library http://www.android-graphview.org/ . but the number of points of diagram is more than 12000 and it isn't possible to add all single points manually. my data saved in storage (with custom format) as shown below :
0.000,116.288
0.008,122.422
0.016,126.721
...
I get the data from https://physionet.org/cgi-bin/atm/ATM
with this setting:
Signals:ABP
Time format:seconds
Toolbox:Export signals as CSV
and I need to read them from file and convert data as shown below for plotting diagram :
new DataPoint(0.000,116.288),
new DataPoint(0.008,122.422),
new DataPoint(0.016,126.721)...
I copied my CSV file in asset folder and read it. then I convert them into Double and try to plot diagram with data.
but the diagram is not correct . I think the problems appears when I want to add new Datapoint, because it need to add a comma "," after each line
pls advise how I can add it?
besides,sometimes after running the application it has stopped.
java code:
public class Plot_Activity extends AppCompatActivity {
String valXY[];
Double Xval;
Double Yval;
GraphView graph;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GraphView graph = (GraphView) findViewById(R.id.graph);
try {
reader=new BufferedReader(new InputStreamReader(getAssets().open("plot/b00_2010_abp_5s.txt")));
String mline;
while((mline=reader.readLine())!=null)
{
valXY = mline.split(",");
Xval =Double.parseDouble(valXY[0]);
Yval =Double.parseDouble(valXY[1]);
DataPoint[] dp = new DataPoint[valXY.length];
for (int i = 0; i < valXY.length; i++)
{
dp[i] = new DataPoint(Xval, Yval);
}
LineGraphSeries<DataPoint> series = new LineGraphSeries<>(dp);
graph.addSeries(series);
}
} catch (IOException e)
{
e.printStackTrace();
}
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0);
graph.getViewport().setMaxX(1);
graph.getViewport().setScrollable(true); // enables horizontal scrolling
graph.getViewport().setScrollableY(true); // enables vertical scrolling
}
}
XML code:
<com.jjoe64.graphview.GraphView
android:id="#+id/graph"
android:layout_marginRight="11dp"
android:layout_width="wrap_content"
android:layout_height="280dp"
thank in advance
java code:
with using Graphview library:
public class Plot_Activity extends AppCompatActivity {
String valXY[];
Double Xval;
Double Yval;
GraphView graph;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GraphView graph = (GraphView) findViewById(R.id.graph);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(getAssets().open("plot/excel_data_abp.csv")));
reader.readLine(); //skip first line of file
reader.readLine(); //skip second line of file
String mline;
ArrayList<DataPoint> arrDataPoint=new ArrayList<>();
while ((mline = reader.readLine()) != null) {
valXY = mline.split(",");
Xval = Double.parseDouble(valXY[0]);
Yval = Double.parseDouble(valXY[1]);
DataPoint dp = new DataPoint(Xval, Yval);
arrDataPoint.add(dp);
}
DataPoint[] listDp = new DataPoint[arrDataPoint.size()];
for(int i=0;i<arrDataPoint.size();i++){
listDp[i]=arrDataPoint.get(i);
}
LineGraphSeries<DataPoint> series = new LineGraphSeries<>(listDp);
graph.addSeries(series);
} catch (IOException e) {
e.printStackTrace();
}
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0);
graph.getViewport().setMaxX(1);
graph.getViewport().setScrollable(true); // enables horizontal scrolling
graph.getViewport().setScrollableY(true); // enables vertical scrolling
}
}
You have to tackle this one step by step.
First you want to read a CSV file. Search for "parse csv file java" and you'll find many tutorials on how to do this.
As you parse through the csv file you'll want to build an array (or two) from the values collected.
Use these values in a for loop to generate new data points. So instead of manually entering each value, you'll have something that looks more like this:
DataPoint[] dp = new DataPoint[yourCSVArray.size()];
for (int i = 0; i < yourCSVArray.size(); i++) {
dp[i] = new DataPoint(variableX, variableY);
}
LineGraphSeries<DataPoint> series = new LineGraphSeries<>(dp);
graph.addSeries(series);
Now that you have some direction, try piecing some code together and if you run into trouble post your code for help.

Getting current image from imageview (android)

I have an ImageView in which I load images from camera and gallery , and I do it using imgview.setimagebitmap(bitmap) ,( and I change the image again and again ) it works fine, but when I try to get the current image back for some processing (applying effect or rotate) it returns me the old image not the current one.
I think the problem is with imgview.setimagebitmap(bitmap).
can I be helped?
I have the following code:
try {
iv_image.buildDrawingCache();
Bitmap source = iv_image.getDrawingCache();
} catch(Exception ex) {
int a;
int b;
a = 11;
b = 12;
}
Can you please try to obtain the batman as follows :
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap()

How to display images in simple listview listadapter in android

I want to display image in simple listview,
we have arraylist HashMap which have values like city, description, etc.
& also the base64 image string which we have to convert to image and set to the each row of of the ListView and List row xml is listview_row.xml
This is my code for displaying the text fields in listview, which is done:
ArrayList<HashMap<String, String>> arllist = new ArrayList<HashMap<String, String>>();
Intent intent = getIntent();
arllist = (ArrayList<HashMap<String, String>>) intent.getSerializableExtra("map");
int length = arllist.size();
for(int i=0; i<length; i++)
{
try{
String stringToConvert = arllist.get(i).get("image");
byte[] decodedString = Base64.decode(stringToConvert, Base64.NO_PADDING);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
ImageView image = (ImageView)this.findViewById(R.id.img);
image.setImageBitmap(decodedByte);
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(productlist.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
SimpleAdapter listadapter = new SimpleAdapter(this, arllist, R.layout.list_item,
new String[] {"city", "category", "description", "mobile", "landmark"},
new int[] {R.id.city, R.id.category, R.id.desc, R.id.mobile, R.id.landmark});
ListView list=(ListView)findViewById(R.id.list);
list.setAdapter(listadapter);
My question is how to convert and bind image to adapter to display it on listview's each row
and also get's error on converting image --- bad base64
I think This Tutorial is exactly what you're looking for.
Edit:
Try this:
Android Encode-Decode
For converting Base64 string, try this-
Assuming your image data is a String called myImageData:
byte[] imageAsBytes = Base64.decode(myImageData.getBytes());
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);

Associate an image with Radio button in Android

I want to fetch Images from my URL and add it to the radio button that is further added to a radio group. However, i could not find metod such as setText to set text for radio button. I wish to add image to my radio button in similar fashion. Is there any hint/method that can do the same for me? Any hint/code example would be really helpful for me,
RadioGroup rg = new RadioGroup (this);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton rb[]= new RadioButton[children.size()];
for (int i = 0; i < var.size(); i++)
{
Element movieAtt = (Element)doc.getRootElement().getChild("movies").getChildren("movie").get(i);
MovieName[i]=movieAtt.getAttributeValue( "Title" );
MovieCover[i]=movieAtt.getAttributeValue( "cover" );
ShowTime[i]=movieAtt.getAttributeValue( "showtime" );
rb[i] = new RadioButton(this);
rb[i].setText(movieAtt.getAttributeValue("Title"));
rg.addView(rb[i]);
//Calling this func to get Images
//LoadImageFromWebOperations(movieAtt.getAttributeValue( "cover" ));
//rb[i].buildDrawingCache(LoadImageFromWebOperations(movieAtt.getAttributeValue( "cover" )));
public static Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch (Exception e)
{
return null;
}
}
Is the problem with the image or the text? As for the image, I believe this should work:
Drawable d = LoadImageFromWebOperations(movieAtt.getAttributeValue("cover"));
rb[i].setButtonDrawable(d);
Make sure to set gravity to Gravity.CENTER or your image won't be centered around the radio button.
You should find information about the text in the RadioButton reference.

Categories

Resources