I am currently working on a small app and have the intention of building a gallery within the app. I currently have the camera intent working but I am not sure how to display the stored images in a grid (i.e. GridView). Here is the GalleryActivity:
public class GalleryActivity extends Activity {
TextView header;
private static final int ACT_START_CAMERA_APP = 0; //indicator to start the camera app
private ImageView capturedPhoto;
private String imageFileLocation = " ";
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.gallery_activity);
capturedPhoto = (ImageView) findViewById(R.id.viewCapturedPhoto);
header = (TextView) findViewById(R.id.heading);
header.setTextKeepState("My Gallery");
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
//inflate the menu; adds items to the action bar if present
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//handles action bar item click here. The action bar
//will automatically handle clicks on the home button
//as long as you specify a parent activity in AndroidManifest.xml
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
//invoked ACTION_IMAGE_CAPTURE - native Android method to access the camera
public void TakePhoto(View view){
Intent callCameraApplicationIntent = new Intent();
callCameraApplicationIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try{
photoFile = createImageFile(); //will contain the address of the captured photo
} catch (IOException exception) {
exception.getStackTrace();
}
//intent used to store the requested image/file i.e. photoFile
//tells Android where to store the picture
callCameraApplicationIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(callCameraApplicationIntent, ACT_START_CAMERA_APP);
}
//if we successfully take a picture print "Picture saved"
//else return "Cannot connect to camera" by default
protected void onActivityResult (int requestCode, int resultCode, Intent data){
//check if you have similar results for defining ACT_START_CAMERA_APP and resultCode
//if so, continue
if(requestCode == ACT_START_CAMERA_APP && resultCode == RESULT_OK) {
Toast.makeText(this, "Picture saved", Toast.LENGTH_SHORT).show();
Bitmap capturedPhotoBitmap = BitmapFactory.decodeFile(imageFileLocation);
capturedPhoto.setImageBitmap(capturedPhotoBitmap);
}
}
//allows storage of pictures on the phone
//create non-collision fileNames i.e. that do not have the same name and appends a stamp
//to the photo to make it unique
File createImageFile() throws IOException {
//create timestamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//append timestamp to generic name IMAGE_
String imageFileName = "IMAGE_" + timeStamp + "_";
File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//now create the file
File image = File.createTempFile(imageFileName, ".jpg", storageDirectory);
imageFileLocation = image.getAbsolutePath();
return image;
}
I am wondering if storing the images that are returned by createImageFile() in a list and displaying the items from the list in a gridView fashion is feasible. Here is the .xml for the Gallery:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/heading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="My Gallery"
android:textSize="30dp"
android:gravity="center"
android:textStyle="bold"
android:clickable="true"
android:background="#android:color/holo_blue_light"
android:textColor="#FFFFFF"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Camera"
android:id="#+id/photoButton"
android:onClick="TakePhoto"
android:clickable="true"
android:enabled="true"
android:layout_alignBottom="#+id/heading"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/photoButton"
android:id="#+id/viewCapturedPhoto"
android:clickable="true"
/>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/heading">
</GridView>
</RelativeLayout>
As you can see in the xml, I have the button for the camera and the GridView in the same file. Would it be better to have them separated? and finally, any implementation suggestions for my intentions (i.e. taking a photo, storing it, then displaying it in the grid)?
Related
So I am creating an android application which opens the url entered by the user. Now each time an url is entered by the user, it needs to be save using the "save" button and the save list is seen using the "list" button.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.application.mota_app.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:text="#string/enter_the_url_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/enter_URL"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:textSize="19sp"
android:textColor="#android:color/holo_green_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtbox_website"
android:layout_marginTop="18dp"
android:width="300dp"
android:inputType="textUri"
android:layout_below="#+id/enter_URL"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_save"
android:textColor="#color/colorAccent"
android:onClick="save"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/visit"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/btn_visit"
android:textColor="#android:color/holo_blue_dark"
android:onClick="open"
android:layout_marginBottom="50dp"
android:layout_alignBottom="#+id/btn_save"
android:layout_centerHorizontal="true" />
<Button
android:text="#string/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_list"
android:onClick="list"
android:textColor="?android:attr/colorPressedHighlight"
android:layout_below="#+id/btn_save"
android:layout_alignLeft="#+id/btn_save"
android:layout_alignStart="#+id/btn_save" />
</RelativeLayout>
This is the XML for the second Activity which will be opened when the list button is clicked:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/show"
android:scrollbars="horizontal|vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="63dp" />
<TextView
android:text="#string/list_of_saved_url_s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:id="#+id/textView"
android:textColor="#color/colorAccent"
android:textSize="24sp" />
</RelativeLayout>
This is my main class:
public class MainActivity extends AppCompatActivity {
private EditText url;
private Button save;
ArrayList<String> addArray = new ArrayList<String>();
private Button list;
private ListView show1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText)findViewById(R.id.txtbox_website);
save = (Button)findViewById(R.id.btn_save);
list = (Button)findViewById(R.id.btn_list);
show1 = (ListView)findViewById(R.id.show);
}
public void open(View view){
if (url.getText().toString().matches("")) {
Toast.makeText(getApplicationContext(), "Enter a website to open!", Toast.LENGTH_SHORT).show();
return;
}
if (!url.getText().toString().startsWith("http://") && !url.getText().toString().startsWith("https://"))
{
url.setText("http://" + url.getText().toString());
}
if (!Patterns.WEB_URL.matcher(url.getText().toString()).matches())
{
Toast.makeText(getApplicationContext(), "Invalid URL!", Toast.LENGTH_SHORT).show();
url.setError("Enter a valid URL");
url.setText("");
url.setSelection(0);
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url.getText().toString()));
startActivity(browserIntent);
}
public void save(View view) {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getInput = url.getText().toString();
if(addArray.contains(getInput))
{
Toast.makeText(getBaseContext(), "URL already added to the list!", Toast.LENGTH_LONG).show();
}
else if(getInput == null || getInput.trim().equals(""))
{
Toast.makeText(getBaseContext(), "Input field is empty!", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
((EditText)findViewById(R.id.txtbox_website)).setText("");
}
}
});
}
public void list(View view) {
list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent screen = new Intent(MainActivity.this, Activity2.class);
startActivity(screen);
}
});
}
#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_settings) {
return true;
}http://www.stackoverflow.com
return super.onOptionsItemSelected(item);
}
}
My save button and list button is not able to save and list the URLs entered by the user.
What should I add?
Thanks
1) Not Saving:
Currently you are storing data statically inside your addArray object. Which gets cleared when you close app.
I think better to use persist data storage. So you can retrieve already stored websites when app re-launched. (Like browser manages history). Available storage options
2) Not showing list:
You need to pass your current list of urls (i.e. addArray variable) in bundle when starting Activity2 And read that list inside Activity2 onCreate. Find here.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
show1.setAdapter(adapter);
You don't need this list adapter inside your main activity, You need to create it inside Activity2 and set this adapter in your listview.
I hope it will help you fix your issues.
I would appreciate some help, I want to take three photos under the same Intent with startActivityForResults() within a loop, and getting back onActivityResult () which prints those three photos in three imageviews, with MarshMallow, and its specific permissions (I think this is not the issue and it should be solved in my code),
The issue is that the application takes those three pictures, and makes the ArrayList or URIs, but it does not arrive to actually printing those three photos in the three imageviews,
Here is my code, thanks in advance,
-----------------
MainActivity.java
-----------------
public class MainActivity extends AppCompatActivity {
//private int numFotos = 1;
//private Bitmap bitmap;
private ArrayList <Uri> uriFiles;
private ImageView imageView1, imageView2,imageView3;
private Button button_takePics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_takePics = (Button) findViewById(R.id.Butt_tiraFotos);
imageView1 = (ImageView) findViewById(R.id.image_1);
imageView2 = (ImageView) findViewById(R.id.image_2);
imageView3 = (ImageView) findViewById(R.id.image_3);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
button_takePics.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[]
{ Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
button_takePics.setEnabled(true);
}
}
}
public void takePictures(View view){
uriFiles = new ArrayList<>();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
for (int i=1; i<4; i++){
uriFiles.add(Uri.fromFile(getOutputMediaFile()));
intent.putParcelableArrayListExtra(MediaStore.EXTRA_OUTPUT,uriFiles);
startActivityForResult(intent, 100);
}
}
private static File getOutputMediaFile() {
File mediaStorageDir=null;
File formattedFile = null;
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
formattedFile= new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
return formattedFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
uriFiles = data.getParcelableArrayListExtra(MediaStore.EXTRA_OUTPUT);
// AQUI EMPIEZA EL PROBLEMA ////////
imageView1.setImageURI(uriFiles.get(0));
imageView2.setImageURI(uriFiles.get(1));
imageView3.setImageURI(uriFiles.get(2));
}
}
}
}
-------------------
activity_main.xml
-------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.faustocheca.photochooseshare.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="18dp"
android:layout_marginTop="18dp"
android:textSize="18sp"
android:text="Tira, escoge y comparte Fotos" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Tira 3 Fotos"
android:id="#+id/Butt_tiraFotos"
android:onClick="takePictures"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/image_1"
android:layout_weight="1"
android:layout_width="80dp"
android:layout_height="120dp"
android:layout_margin="1dp"
android:background="#feafea"/>
<ImageView
android:id="#+id/image_2"
android:layout_weight="1"
android:layout_width="80dp"
android:layout_height="120dp"
android:layout_margin="1dp"
android:background="#feafea"/>
<ImageView
android:id="#+id/image_3"
android:layout_weight="1"
android:layout_width="80dp"
android:layout_height="120dp"
android:layout_margin="1dp"
android:background="#feafea"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Comparte"
android:id="#+id/Butt_comparte"
/>
</LinearLayout>
This will not work; a single startActivityForResult will result in a single call to onActivityResult.
There's no contract in the ACTION_IMAGE_CAPTURE documentation or elsewhere in the system that says that you can issue it multiple times and get one result with 3 URIs.
You'll have to loop it so that you fire one intent, wait for the result, fire the second intent, wait for the result, etc.
You may be able to fire the 3 intents in a loop like this, but I'm not sure I'd trust that the responding camera application would actually be invoked 3 times. But even so, you'll receive 3 separate onActivityResult calls, if that works.
Image for button 500x500.
I have created an ImageButton and when ImageButton is clicked the system camera should launch and the image brought from the system's camera app will be shown in the ImageView. But, the problem is: the button doesn't work here. Other than button if I click anywhere in the app the system camera launches but in case of button click the camera doesn't launch. What kind of error is causing this unexpected behaviour?
Java File:
public class Home extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// CAMERA BUTTON IMPLEMENTATION
ImageButton cameraButton = (ImageButton)findViewById(R.id.imageButton);
imageView = (ImageView)findViewById(R.id.imageView);
/* Disable the button if the user doesn't have camera */
if(!hasCamera())
cameraButton.setEnabled(false);
// CAMERA BUTTON IMPLEMENTATION
}
// Check if the user has a camera
private boolean hasCamera(){
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
// Launching the camera
public void launchCamera(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture and pass results along to onActivityResult
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
// If you want to return the image taken
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
//Get the photo
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
imageView.setImageBitmap(photo);
}
}
}
XML FILE:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.muchmore.www.chasquido.Home"
android:background="#drawable/home_background"
android:id="#+id/home_activity"
android:onClick="launchCamera">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome User!!!"
android:id="#+id/welcome_tag"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#000"
/>
<ImageButton
android:layout_width="90dp"
android:layout_height="90dp"
android:id="#+id/imageButton"
android:background="#drawable/camera_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:minHeight="300dp"
android:minWidth="300dp"
android:layout_above="#+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
You have assigned OnClickListener android:onClick="launchCamera" to your RelativeLayout (your root view) instead to your ImageButton.
I currently have a method to fetch all the videos from the device and display in a listview. Currently I only show the album name and title with a default image for the thumbnail which repeats in all the rows of the listview. The method to do that is
try {
mAdapter = new SimpleCursorAdapter(
this,
// Use a template that displays a text view
R.layout.media_select_row,
null,
// Map from database columns...
new String[] {
MediaStore.Video.Media.ALBUM,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media._ID},
// To widget ids in the row layout...
new int[] {
R.id.row_album,
R.id.row_title,
R.id.row_icon,},
0);
setListAdapter(mAdapter);
getListView().setItemsCanFocus(true);
// Normal click - open the editor
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
String filename = c.getString(dataIndex);
videoFilename = filename;
String substr = videoFilename.substring(videoFilename.length() - 3);
if(substr.equals("mp4")) {
if(callPath == 1) {
Intent intent = new Intent(DubVideoList.this, DubStudio.class);
intent.putExtra("videoPath", videoFilename);
startActivity(intent);
}else if(callPath == 2){
Intent intent = new Intent(DubVideoList.this, DubStudioBeta.class);
intent.putExtra("videoPath", videoFilename);
startActivity(intent);
}
}else{
Toast.makeText(DubVideoList.this,getString(R.string.mp4_support),Toast.LENGTH_LONG).show();
}
}
});
mInternalCursor = null;
mExternalCursor = null;
getLoaderManager().initLoader(INTERNAL_CURSOR_ID, null, this);
getLoaderManager().initLoader(EXTERNAL_CURSOR_ID, null, this);
} catch (SecurityException e) {
// No permission to retrieve video?
Log.e("SecurityError", e.toString());
// TODO error 1
} catch (IllegalArgumentException e) {
// No permission to retrieve video?
Log.e("IllegalArgument", e.toString());
// TODO error 2
}
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.row_icon) {
setSoundIconFromCursor((ImageView) view, cursor);
return true;
}
return false;
}
});
Now I need to replace the default image for each cell with the Video's Thumbnail ? Is there a way to do that ? I have given the row's XML also for your reference. Thanks in advance.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="#+id/row_icon"
android:gravity="center_vertical"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="4dp"
android:layout_marginTop="4dp"
android:src="#drawable/filmicon"
android:layout_gravity="center" />
<LinearLayout
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_marginTop="8dip"
android:layout_marginBottom="8dip"
android:layout_width="0px"
android:layout_weight="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="4dip">
<TextView android:id="#+id/row_title"
android:textColor="#ff000000"
android:textSize="18sp"
android:singleLine="true"
android:shadowColor="#999999"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:id="#+id/row_album"
android:textColor="#ff1bbcff"
android:textSize="12sp"
android:singleLine="true"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
To get the thumbnail, you can use this code
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(video_path,
MediaStore.Images.Thumbnails.MINI_KIND);
Use this code to add video thumb in listview.
Method :1
Bitmap bMap= ThumbnailUtils.createVideoThumbnail("local file path" ,
MediaStore.Video.Thumbnails.MINI_KIND);
MViewHolder.imageThumb.setImageBitmap(bMap);
Method :2
Use Glide
compile 'com.github.bumptech.glide:glide:3.7.0'
Glide
.with( context )
.load( Uri.fromFile( new File( filePath ) ) )
.into( MViewHolder.imageThumb );
Hello i need Your help in displaying data from database in activity, ive been trying many things but have no idea how to do that. Im creating some kind of weather app. It has Data in Database on the device.
There is DataBaseHandler Class which returns List with all Spots.
public List<Spot> getUserSpotList(int id){
List<Spot> spotList = new ArrayList<Spot>();
String selectQuery = "SELECT " +SPOT_ID+","+ SPOT_NAME + ","+ SPOT_LATITUDE + ","+SPOT_LONGITUDE+","+SPOT_WIND_SPEED +","+SPOT_WEATHER_ICON+
" FROM " + TABLE_SPOT + " WHERE "+SPOT_USER_ID + "="+id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Spot spot = new Spot();
spot.setSpot_id(Integer.parseInt(cursor.getString(0)));
spot.setSpotName(cursor.getString(1));
spot.setSpotLatitude(cursor.getString(2));
spot.setSpotLongitude(cursor.getString(3));
spot.setWindSpeed(Double.parseDouble(cursor.getString(4)));
spot.setSpotWeatherIcon(cursor.getString(5));
// Adding User to list
spotList.add(spot);
} while (cursor.moveToNext());
}
return spotList;
}
And i Have Activity with listView xml in witch i want to display some stuff from the code above based on another relativelayout for one element.
SpotActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.mk.rcwindy.SpotActivity">
<ListView
android:id="#+id/listLajout"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:layout_weight="1"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And here is Relative layout for one element in the list view above.
I would like to connect SpotName from database with TextView id=SpotName, Windspeed from database with Windspeed Text View, and Display image in ImageView based on SpotWeatherIcon from database.
spotlista_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:id="#android:id/list">
<ImageView
android:id="#+id/SpotAvilabilityIcon"
android:layout_width="20dp"
android:layout_height="match_parent"
android:background="#color/green_apple"/>
<ImageView
android:id="#+id/WeatherIcon"
android:layout_width="70dp"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/WindSpeed"
android:scaleType="centerInside"
/>
<TextView
android:id="#+id/WindSpeed"
android:text=""
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/WindSpeedUnit"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
<TextView
android:text="m/s"
android:textSize="30dp"
android:id="#+id/WindSpeedUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/SpotAvilabilityIcon"
android:layout_toStartOf="#+id/WeatherIcon"
android:layout_toLeftOf="#+id/WeatherIcon"
android:layout_centerVertical="true">
<TextView
android:id="#+id/SpotName"
android:text=""
android:textSize="40dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_centerVertical="true"/>
</FrameLayout>
</RelativeLayout>
And here is the code of activity SpotActivity
public class SpotActivity extends ActionBarActivity {
int loggedUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spot);
Intent intent = getIntent();
if (null != intent) {
loggedUserId = intent.getIntExtra("logged", 0);
}
String text = "logged user id = "+loggedUserId;
Toast t1 = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
t1.show();
}
public int userIdSender(){
return loggedUserId;
}
#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_spot, 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_settings) {
return true;
}
if (id== R.id.action_new){
Intent intent = new Intent(this, SpotAddActivity.class);
intent.putExtra("logged",loggedUserId);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Thanks for Help! I tried to do that and still have a big problems so now im asking for help. Its a school project im working at and that is the last thing i have to do to make the app work-Display stuff :D
You need to create an adapter for your ListView. I recommend you watch The World Of ListView.
All an adapter does is provide a view for each item in your data set. For cursor data, you should subclass CursorAdapter and implement the newView() and bindView() methods at the minimum.