hi i have create one simple media player.... now its working fine. i retrieve video thumbnails in gallery. when i click the thumbnails video will play in other page... if i click thumbnails video play same page...see my screen shot....my video play in that red box...this type of frame how to create.....
this is my screen shot:
if i click thumbnails the video will play another page:
that screen shot:
this is for my coding:
public class videothumb extends Activity
{
private final static Uri MEDIA_EXTERNAL_CONTENT_URI =
MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
private final static String _ID = MediaStore.Video.Media._ID;
private final static String MEDIA_DATA = MediaStore.Video.Media.DATA;
//flag for which one is used for images selection
private Gallery _gallery;
private Cursor _cursor;
private int _columnIndex;
private int[] _videosId;
private Uri _contentUri;
private int video_column_index;
protected Context _context;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_context = getApplicationContext();
setContentView(R.layout.main);
//set GridView for gallery
_gallery = (Gallery) findViewById(R.id.videoGrdVw);
//set default as external/sdcard uri
_contentUri = MEDIA_EXTERNAL_CONTENT_URI;
//initialize the videos uri
//showToast(_contentUri.getPath());
initVideosId();
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(_context));
_gallery.setOnItemClickListener(videogridlistener);
}
private void initVideosId() {
try
{
//Here we set up a string array of the thumbnail ID column we want to get back
String [] proj={_ID};
// Now we create the cursor pointing to the external thumbnail store
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int count= _cursor.getCount();
System.out.println("total"+_cursor.getCount());
// We now get the column index of the thumbnail id
_columnIndex = _cursor.getColumnIndex(_ID);
//initialize
_videosId = new int[count];
//move position to first element
_cursor.moveToFirst();
for(int i=0;i<count;i++)
{
int id = _cursor.getInt(_columnIndex);
//
_videosId[i]= id;
//
_cursor.moveToNext();
//
}
}catch(Exception ex)
{
showToast(ex.getMessage().toString());
}
}
protected void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_LONG).show();
}
private AdapterView.OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
// Now we want to actually get the data location of the file
String [] proj={MEDIA_DATA};
// We request our cursor again
_cursor = managedQuery(_contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null);
//System.gc();
// video_column_index =
_cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
_columnIndex = _cursor.getColumnIndex(MEDIA_DATA);
// Lets move to the selected item in the cursor
_cursor.moveToPosition(position);
String filename = _cursor.getString(_columnIndex);
Intent intent = new Intent(videothumb.this, ViewVideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
showToast(filename);
// Toast.makeText(videothumb.this, "" + position, Toast.LENGTH_SHORT).show();
}
};
private class VideoGalleryAdapter extends BaseAdapter
{
public VideoGalleryAdapter(Context c)
{
_context = c;
}
public int getCount()
{
return _videosId.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(_context);
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(_videosId[position]));
imgVw.setAdjustViewBounds(true);
imgVw.setBackgroundColor(Color.WHITE);
imgVw.setLayoutParams(new Gallery.LayoutParams(150, 100));
imgVw.setPadding(5,5,5,5);
imgVw.setScaleType(ImageView.ScaleType.FIT_XY);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +",
"+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(getContentResolver(),id,
MediaStore.Video.Thumbnails.MICRO_KIND, null);
System.out.println("ff"+MediaStore.Video.Thumbnails.
getThumbnail(getContentResolver(),id, MediaStore.Video.Thumbnails.MICRO_KIND, null));
return thumb;
}
}
}
coding 2:`
public class ViewVideo extends Activity {
private String filename;
private VideoView Video;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main1);
//setContentView(new Zoom(this));
Video=(VideoView)findViewById(R.id.VideoView01);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("videofilename");
Video.setVideoPath(filename);
Video.setMediaController(new MediaController(this));
Video.requestFocus();
Video.start();
}
}
anyone help me...
You want to use Videoview
<VideoView android:id="#+id/Videoview1"
android:layout_marginTop="100px"
android:layout_marginLeft="10px"
android:layout_width="20px"
android:layout_height="200px"/>
and create object in your activity
and play.
videoview.start();
like this.
Hope this will help you
private VideoView mVView;
mVView= (VideoView) findViewById(R.id.Videoview1);
mVView.setVideoPath("sdcard/filename.mp4");
mVView.start();
Related
I was working with android project these days, and It will finish soon, but I got stuck in my project. First, I want to create search activity which will be used for searching movies. The searching activity runs well, but whenever it comes to adding the selected movie, it shown me the error code below:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.idstream.pojo.Movies.setTitle(java.lang.String)' on a null object reference
at com.example.idstream.search.MoviesDetailActivity.addFavorite(MoviesDetailActivity.java:96)
at com.example.idstream.search.MoviesDetailActivity.access$100(MoviesDetailActivity.java:19)
at com.example.idstream.search.MoviesDetailActivity$1.onClick(MoviesDetailActivity.java:78)
This code has an error in this area:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
I've tried to add the selected movie to database in other activity, but it didn't mention any error. But when I tried to save the selected movie to database, it turns out an error. I also tried to send it to a toast, which I wanna make sure whether the value that I sent was successfully retrieved. The toast is successfully get the data.
Here is my SearchFragment.java:
public class SearchMovieFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {
ListView lvMovieItems;
EditText txtTitleMovieInput;
ImageView imgMoviesSearch;
Button btnSearchMovie;
AdaptersMovie adaptersMovie;
MovieHelper movieHelper;
Boolean act = true;
Boolean insert = true;
Boolean delete = true;
private View mView;
public SearchMovieFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_search_movie, container, false);
txtTitleMovieInput = (EditText)mView.findViewById(R.id.txtMovieTitle);
String mTitles = txtTitleMovieInput.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitles);
imgMoviesSearch = (ImageView)mView.findViewById(R.id.imgMovies);
btnSearchMovie = (Button) mView.findViewById(R.id.btn_search);
btnSearchMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mTitleMovie = txtTitleMovieInput.getText().toString();
if(TextUtils.isEmpty(mTitleMovie)){
return;
}
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitleMovie);
getLoaderManager().restartLoader(0, bundle, SearchMovieFragment.this);
}
});
getLoaderManager().initLoader(0, bundle, SearchMovieFragment.this);
adaptersMovie = new AdaptersMovie(getActivity());
adaptersMovie.notifyDataSetChanged();
lvMovieItems = (ListView)mView.findViewById(R.id.listMovies);
lvMovieItems.setAdapter(adaptersMovie);
lvMovieItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movies item = (Movies)parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), MoviesDetailActivity.class);
intent.putExtra(MoviesDetailActivity.EXTRA_MOVIE, item.getTitle());
intent.putExtra(MoviesDetailActivity.EXTRA_RELEASE, item.getRelease_info());
intent.putExtra(MoviesDetailActivity.EXTRA_LANGUAGE, item.getLanguage());
intent.putExtra(MoviesDetailActivity.EXTRA_OVERVIEW, item.getDescription());
intent.putExtra(MoviesDetailActivity.EXTRA_PHOTOS, item.getPhotos());
startActivity(intent);
}
});
return mView;
}
#NonNull
#Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, #Nullable Bundle args) {
String temp = "";
if (args != null){
temp = args.getString(EXTRA_MOVIE);
}
return new MovieAsyncTaskLoader(getActivity(), temp);
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {
adaptersMovie.setData(data);
}
#Override
public void onLoaderReset(#NonNull Loader<ArrayList<Movies>> loader) {
adaptersMovie.setData(null);
}
}
My MoviesDetailActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies_detail);
setTitle("Movie's Details");
tvTitles = findViewById(R.id.movieTitles);
tvReleased = findViewById(R.id.movieRelease);
tvLanguages = findViewById(R.id.movieLanguages);
tvDescription = findViewById(R.id.movieDescriptions);
imageMovies = findViewById(R.id.moviesImage);
progressBar = findViewById(R.id.progressMovie);
fav_moviesBtn = findViewById(R.id.fab_movie);
progressBar.setVisibility(View.VISIBLE);
String mvTitles = getIntent().getStringExtra(EXTRA_MOVIE);
String mvLanguages = getIntent().getStringExtra(EXTRA_LANGUAGE);
String mvOverview = getIntent().getStringExtra(EXTRA_OVERVIEW);
String mvRelease = getIntent().getStringExtra(EXTRA_RELEASE);
String mvPhotos = getIntent().getStringExtra(EXTRA_PHOTOS);
tvTitles.setText(mvTitles);
tvReleased.setText(mvRelease);
tvLanguages.setText(mvLanguages);
tvDescription.setText(mvOverview);
Glide.with(MoviesDetailActivity.this)
.load("https://image.tmdb.org/t/p/w185" + mvPhotos)
.placeholder(R.color.colorFreshOrange)
.dontAnimate()
.into(imageMovies);
movieHelper = new MovieHelper(MoviesDetailActivity.this);
movieHelper.open();
mMoviess = getIntent().getIntExtra(FAVOURITE,0);
fav_moviesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isAdd) {
addFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Ditambahkan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_yes_24_foreground);
} else {
removeFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Dihapuskan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_no_24_foreground);
}
}
});
progressBar.setVisibility(View.GONE);
}
private void addFavorite() {
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.insertMovie(movies);
}
private void removeFavorite() {
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.deleteMovie(getIntent().getStringExtra(EXTRA_MOVIE));
}
}
And this one is my MovieHelper.java:
public Boolean getOne(String name){
String querySingleRecord = "SELECT * FROM " + DATABASE_TABLE + " WHERE " +DatabaseContract.MovieColoumn.TITLE+ " " + " LIKE " +"'"+name+"'" ;
Cursor cursor = database.rawQuery(querySingleRecord,null);
cursor.moveToFirst();
Log.d("cursor", String.valueOf(cursor.getCount()));
if (cursor.getCount() > 0 ){
return true;
}else if(cursor.getCount() == 0){
return false;
}
return false;
}
public long insertMovie(Movies mMovies){
ContentValues args = new ContentValues();
args.put(IDS,mMovies.getId());
args.put(DatabaseContract.MovieColoumn.TITLE,mMovies.getTitle());
args.put(DatabaseContract.MovieColoumn.RELEASE_INFO,mMovies.getRelease_info());
args.put(DatabaseContract.MovieColoumn.LANGUAGE,mMovies.getLanguage());
args.put(DatabaseContract.MovieColoumn.DESCRIPTION,mMovies.getDescription());
args.put(DatabaseContract.MovieColoumn.PHOTOS,mMovies.getPhotos());
return database.insert(DATABASE_TABLE,null,args);
}
I believe the problem is here:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Notice that you're using the same EXTRA_TITLE for both.
I think that what's happening is that getParcelableExtra() is returning null, because the implementation of Bundle (the extras) will catch the ClassCastException:
// ...
try {
return (T) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Parcelable", e);
return null;
}
And then you get a NullPointerException when you try to call setTitle().
Instead, create a new Movies instance yourself:
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Alternatively, you could implement the Parcelable interface in your Movies class, and then you wouldn't have to bother adding all of its fields one by one.
I am getting error: Target must not be null Picasso
public void getListFromDb(){
Cursor res = myDb.ViewAll();
startManagingCursor(res);
//Map cursor from db to viewFields
String[] fromFieldNames = new String[]{DatabaseHelper.COL_2, DatabaseHelper.COL_3, DatabaseHelper.COL_4, DatabaseHelper.COL_5};
int[] toViewIDS = new int[]{R.id.viewName, R.id.viewAddress, R.id.viewPostcode, R.id.viewType};
//Create SimpleCursorAdaptor with null cursor
SimpleCursorAdapter myCursorAdaptor = new SimpleCursorAdapter(this, R.layout.item_layout, null, fromFieldNames, toViewIDS, 0);
// Set adaptor for listView
myList.setAdapter(myCursorAdaptor);
Picasso
.with(getApplicationContext())
.load("http://www.newton.ac.uk/files/covers/968361.jpg")
.resize(600, 200) // resizes the image to these dimensions (in pixel). does not respect aspect ratio
.into(img);
new AsyncTask<SimpleCursorAdapter, Void, Cursor>() {
private SimpleCursorAdapter mSimpleCursorAdapter;
#Override
protected Cursor doInBackground(SimpleCursorAdapter... params) {
// Save cursorAdapter to use in postExecute
this.mSimpleCursorAdapter = params[0];
// Load cursor on background thread with search function
return myDb.ViewAll();
}
}
#Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
// and update the cursor (which is already in the listview)
this.mSimpleCursorAdapter.changeCursor(cursor);
}
}.execute(myCursorAdaptor);
}
private void registerListClickCallback() {
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long IDinDB) {
Cursor res = myDb.GetRow(IDinDB);
if (res.moveToFirst()) {
long idDB = res.getLong(DatabaseHelper.ROWID);
String message = "ID: " + idDB;
//Toast.makeText(ViewActivity.this, message, Toast.LENGTH_LONG).show();
String hello = Long.toString(idDB);
Intent intent = new Intent(ViewActivity.this, ImageFullViewActivity.class);
intent.putExtra("ImgID", hello);
startActivity(intent);
}
}
});
}
How do I solve this issue.
Also, the url of the image is just temporary as I'm using it for testing. Will I be able to insert the Real Path of the image inside .load() ?
Thanks
I am using theMovieDb.com API to fetch data.On launching the app it shows grid view of popular movies. In setting menu, it has option to sort the grid view on the basis of more popular and highest rated. I am using shared preferences to store user preferences and a listener on preference change.But unable to sort the grid view.
MainActivityFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridView = (GridView) rootView.findViewById(R.id.grid_view_movies);
final ImageAdapter mAdapter= new ImageAdapter(getActivity(),listMovie);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie movieSelected= listMovie.get(position);
String movieTitle=movieSelected.getTitle();
String movieThumbnail=movieSelected.getUrlThumbnail();
String movieReleaseDate=movieSelected.getReleaseDate();
String movieOverview=movieSelected.getOverview();
String movieRating = movieSelected.getRating();
Intent i = new Intent( getActivity() ,DetailsMovies.class);
i.putExtra(EXTRA_MESSAGE_1, movieThumbnail);
i.putExtra(EXTRA_MESSAGE_2, movieTitle);
i.putExtra(EXTRA_MESSAGE_3, movieReleaseDate);
i.putExtra(EXTRA_MESSAGE_4, movieRating);
i.putExtra(EXTRA_MESSAGE_5, movieOverview);
startActivity(i);
}
});
return rootView;
}
private void sendJsonRequest() {
//In the case of theMovieDB it is JSON Object Request
//Specify several argument in JSON Object Request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJsonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
private void parseJsonResponse(JSONObject response) {
if (response == null || response.length() == 0) {
return;
}
long id = -1;
String title = Constants.NA;
String releaseDate = Constants.NA;
String synopsis = Constants.NA;
String urlThumbnail = Constants.NA;
String rating = Constants.NA;
try {
if (response.has(KEY_RESULTS)) {
JSONArray jsonArray = response.getJSONArray(KEY_RESULTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentMovies = jsonArray.getJSONObject(i);
//Get the id of the current movie
//If statement is used to check whether id is null or not.
if (currentMovies.has(KEY_ID) && !currentMovies.isNull(KEY_ID)) {
id = currentMovies.getLong(KEY_ID);
}
//Get the synopsis of the current movie
if (currentMovies.has(KEY_OVERVIEW) && !currentMovies.isNull(KEY_OVERVIEW)) {
synopsis = currentMovies.getString(KEY_OVERVIEW);
}
//Get the title of the current movie
if (currentMovies.has(KEY_TITLE) && !currentMovies.isNull(KEY_TITLE)) {
title = currentMovies.getString(KEY_TITLE);
}
//Get the urlThumbnail of the current movie
if (currentMovies.has(KEY_POSTER_PATH) && !currentMovies.isNull(KEY_POSTER_PATH)) {
urlThumbnail = currentMovies.getString(KEY_POSTER_PATH);
}
//Get the release date of the current movie
if (currentMovies.has(KEY_RELEASE_DATE) && !currentMovies.isNull(KEY_RELEASE_DATE)) {
releaseDate = currentMovies.getString(KEY_RELEASE_DATE);
}
//Get the rating of current movie
if (currentMovies.has(KEY_VOTE_AVERAGE) && !currentMovies.isNull(KEY_VOTE_AVERAGE)) {
rating = currentMovies.getString(KEY_VOTE_AVERAGE);
}
//Create movie object
movie=new Movie();
movie.setId(id);
movie.setTitle(title);
movie.setUrlThumbnail("http://image.tmdb.org/t/p/w185/" + urlThumbnail);
movie.setReleaseDate(releaseDate);
movie.setOverview(synopsis);
movie.setRating(rating);
//This decides when to add movies to the ArrayList
if (id != -1 && !title.equals(Constants.NA)) {
listMovie.add(movie);
}
}
}
} catch (JSONException e) {
Log.e("error", e.getMessage());
}
}
public String getRequestUrl() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String order = pref.getString(getString(R.string.pref_order_key), getString(R.string.pref_popularity));
if(order.equals(getString(R.string.pref_rating)))
return URL + "vote_average" + UrlEndpoints.URL_PARAM + MyApplication.API_KEY;
else
return URL+ "popularity"+UrlEndpoints.URL_PARAM + MyApplication.API_KEY;
}
//Base Adapter which is used to put poster in grid view
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Movie> movieItems;
public ImageAdapter(Context c, ArrayList<Movie> movieList) {
this.mContext = c;
this.movieItems = movieList;
}
public int getCount() {
return movieItems.size();
}
public Object getItem(int position) {
return movieItems.get(position);
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item_movies, null);
}
mNetworkImageView = (NetworkImageView) convertView.findViewById
(R.id.networkImageView);
//Getting movie data for the row
Movie m = movieItems.get(position);
//Thumbnail Image
//ImageLoader is used to load the images from json object retrieved.
imageLoader=VolleySingleton.getInstance().getImageLoader();
mNetworkImageView.setImageUrl(m.getUrlThumbnail(), imageLoader);
return convertView;
}
}
}
SettingsActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
// Added preferences from XML
addPreferencesFromResource(R.xml.pref_general);
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
// Added preferences
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_order_key)));
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}
My application pulls data from a web service that generates different sections for each user. Then I am going to use these sections to create tabs using FragmentPagerAdapter.
I have used an Async task to pull data from the web service. However the overridden methods such as getCount() and getPageTitle() in the FragmentPagerAdapter executed prior to my asynctask and completes its job. How can I prevent this and generate dynamic number of tabs and their title name based on the data fetched from the web service?
In other words how can I create dynamic number of tabs and titles based on the data fetch from the web service
My Code for FragmentPagerAdapter as below. As you can see I have hard coded the amount of tabs as well as their title names.
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new SectionFragment();
Bundle args = new Bundle();
args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Camera".toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return "SECTION 4";
}
return null;
}
//setting the section title
private void setSectionTitle(){
}
//count the number of sections
private int countNumberofSections(){
int numberOfSection = 0;
return numberOfSection;
}
}
Then I have my Fragment code as below which has the the caller to the Async Task
public static class SectionFragment extends Fragment implements OnTaskCompleted {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private Slider adapter;
private ViewPager viewPager;
public static final String ARG_SECTION_NUMBER = "section_number";
Button thumbUpBut;
Button thumbDownBut;
Button captureButton;
ImageView genImage;
TextView genCaption;
private Camera mCamera;
private CameraPreview mPreview;
private static File mediaFile;
private ProgressDialog progress;
private static String imageSaveLocation;
private static String file_name_without_extension;
private ImageView imageView;
private Button uploadButton;
private Button cancelButton;
private Collection<Place> places = null;
private Collection<Happenings> events = null;
private Collection<General> general = null;
private ArrayList<String> sections;
public int getNumberOfPages(){
return sections.size();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
FeedRequest task = new FeedRequest(this);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
captureButton = (Button) rootView.findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
thumbUpBut = (Button) rootView.findViewById(R.id.thumbUp);
thumbUpBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressUp");
thumb("up");
}
});
thumbDownBut = (Button) rootView.findViewById(R.id.thumbDown);
thumbDownBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressDown");
thumb("down");
}
});
//allocating the activity one to the camera
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
mCamera = getCameraInstance();
mPreview = new CameraPreview(this.getActivity(), mCamera);
FrameLayout preview = (FrameLayout)rootView.findViewById(R.id.camera_preview);
preview.addView(mPreview);
//hide buttons
thumbDownBut.setVisibility(rootView.INVISIBLE);
thumbUpBut.setVisibility(rootView.INVISIBLE);
}else{
thumbDownBut.setVisibility(rootView.VISIBLE);
thumbUpBut.setVisibility(rootView.VISIBLE);
captureButton.setVisibility(rootView.INVISIBLE);
}
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
return rootView;
}
//take photo function
private void takePhoto() {
//get coordinates of the location
UserLocation userLocation = new UserLocation();
userLocation.getUserLocation(getActivity());
coordinates[0] = userLocation.longitude;
coordinates[1] = userLocation.latitude;
PictureCallback pictureCB = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera cam) {
new SavePhotoAndMetadata().execute(data);
cam.startPreview();
}
};
mCamera.takePicture(null, null, pictureCB);
}
//get camera instance
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
//get the media out
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
file_name_without_extension = "IMG_" + timeStamp;
imageSaveLocation = mediaFile.toString();
return mediaFile;
}
//saving the image and metadata together
class SavePhotoAndMetadata extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... data) {
File picFile = getOutputMediaFile();
if (picFile == null) {
return null;
}
byte[] photoData = data[0];
try {
//save the image
FileOutputStream fos = new FileOutputStream(picFile);
fos.write(photoData);
fos.close();
} catch (FileNotFoundException e) {
e.getStackTrace();
} catch (IOException e) {
e.getStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Saving Picture..Please wait...");
progress.show();
}
#Override
protected void onPostExecute(String s) {
progress.dismiss();
imagePreviewDialog();
}
}
//save image metadata in async task
class SaveMetadataTask extends AsyncTask<Void, String, Void> {
#Override
protected Void doInBackground(Void... params) {
serializeDeserialize.serializeData("This is for testing", file_name_without_extension, Double.toString(coordinates[0]), Double.toString(coordinates[1]), deviceId, deviceEmail);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void v) {
}
}
//image preview dialog and its functionality
private void imagePreviewDialog(){
//setting the bitmap
Bitmap bmp = BitmapFactory.decodeFile(mediaFile.toString());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Image Preview");
builder.setCancelable(false);
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup vg = (ViewGroup)inflater.inflate(R.layout.sanp_preview_layout, null);
ImageView image = (ImageView) vg.findViewById(R.id.imageView);
image.setImageBitmap(rotateBitmap(bmp));
builder.setView(vg);
//buttons
builder.setPositiveButton("Upload",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(checkInternetConnection.haveNetworkConnection(sContext)){
//upload the image
uploadImage();
//save image metadata
new SaveMetadataTask().execute();
}else{
Toast.makeText(sContext, "Error! No internet connection detected. Image will be uploaded on an active internet connection", Toast.LENGTH_LONG).show();
new SaveMetadataTask().execute();
}
}
});
builder.setNegativeButton("Discard",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
discardImage(mediaFile.toString());
dialog.dismiss();
}
});
builder.show();
}
private Bitmap rotateBitmap(Bitmap image){
int width=image.getHeight();
int height=image.getWidth();
Bitmap srcBitmap=Bitmap.createBitmap(width, height, image.getConfig());
for (int y=width-1;y>=0;y--)
for(int x=0;x<height;x++)
srcBitmap.setPixel(width-y-1, x,image.getPixel(x, y));
return srcBitmap;
}
//device email
private String getDeviceEmail(){
AccountManager accountManager = AccountManager.get(sContext);
Account[] account = accountManager.getAccountsByType("com.google");
//device email
for(Account accLoop : account){
deviceEmail = accLoop.name;
}
return deviceEmail;
}
//upload image to the server
private void uploadImage(){
//save metadata
//call upload service
Intent intent = new Intent(sContext, HttpUploader.class);
Bundle loc = new Bundle();
loc.putDoubleArray("ss", coordinates);
intent.putExtra("url", PHOTO_UPLOAD);
intent.putExtra("paths", mediaFile.toString());
intent.putExtra("deviceid", deviceId);
intent.putExtra("deviceemail", getDeviceEmail());
intent.putExtra("posttext", "This is for testing");
intent.putExtra("filename", file_name_without_extension);
intent.putExtra("geo", loc);
sContext.startService(intent);
Toast.makeText(getActivity(), "Your image is being uploaded", Toast.LENGTH_LONG).show();
}
//discard image when the discard button is pressed
private void discardImage(String imagePath){
File file = new File(imagePath);
try{
file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
#Override
public void onTaskCompleted(boolean status, String message) {
// TODO Auto-generated method stub
Log.e("onTaskCompleted", "success" + status);
if (message == "tumb UP success") {
thumbUpBut.setSelected(true);
thumbDownBut.setSelected(false);
Log.e("tumb", "tumb");
} else if (message == "tumb DOWN success") {
thumbDownBut.setSelected(true);
thumbUpBut.setSelected(false);
Log.e("tumb", "tumb");
}
}
//listener for fetching main objects
#Override
public void onFeedCompleted(ArrayList<Posts> postArray, Multimap<String, Object> multiMap) {
// TODO Auto-generated method stub
numberOfPages = postArray.size();
adapter = new Slider(getActivity(), postArray, getContext());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(postArray.size());
//saving the keyset
Set<String> keys = multiMap.keySet();
sections = new ArrayList<String>();
//sorting the categories and creating the category list
for(String key:keys){
//getting category list
if(!sections.contains(keys)){
sections.add(key);
}
//sorting categories
if(key.equals("Place")){
places.add((Place) multiMap.get(key));
}else if(key.equals("Events")){
events.add((Happenings) multiMap.get(key));
}else if(key.equals("General")){
general.add((General) multiMap.get(key));
}
}
}
//adding the pages to the adaptor dynamically
public void addPagesDynamically(){
}
}
//create the parent directory
private void createParentDiectory(){
File dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap");
if(!(dir.exists() && dir.isDirectory())) {
dir.mkdirs();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_post:
openPost();
return true;
case R.id.action_settings:
// openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openPost() {
/*
Intent i = new Intent(getApplicationContext(), PhotoActivity.class);
startActivity(i);
*/
}
public static void thumb(String type) {
SectionFragment d = new SectionFragment();
PostThumb task = new PostThumb(type, d);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
//broadcast receiver for picture upload
public class MyWebRequestReceiver extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "asia.ceynet.intent.action.PROCESS_RESPONSE";
#Override
public void onReceive(Context context, Intent intent) {
//String responseString = intent.getStringExtra(HttpUploader.RESPONSE_STRING);
String reponseMessage = intent.getStringExtra(HttpUploader.RESPONSE_MESSAGE);
String responseStatus = intent.getStringExtra(HttpUploader.RESPONSE_STATUS);
String file_to_be_deleted = intent.getStringExtra(HttpUploader.FILE_NAME_WITHOUT_EXTENSION);
Toast.makeText(getApplicationContext(), reponseMessage + " - " + file_to_be_deleted + ".jpg", Toast.LENGTH_LONG).show();
//if uploaded successfully delete or image and metadata
if(responseStatus.equals("true")){
File temp_image_dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".jpg");
File metadata_file = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".ser");
try{
temp_image_dir.delete();
metadata_file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
}
}
When you finnish pulling the async data, provide the adapter with the new data and call .notifyDataSetChanged() on that adapter instance and the framework will update the pages and count by itself.
If you wish a more detailed explanation post your FragmentPagerAdapter implementation.
First of all, let me apologize if I'm not making myself clear enough because this is one of my first participation(s) here. But I'll be always here to answer queries related to this answer and clear any confusions arose by my statements.
Since you're using fragments, so I'm assuming you must have included your fragments inside an activity (lets say MainActivity.java).
What you need, can be done inside that activity containing fragment.
Here is the example code of onCreate method inside the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
//Instance of viewpager included inside activity_main.xml
viewPager = (ViewPager) findViewById(R.id.vpMain);
SectionsPagerAdapter adapter = new SectionsPagerAdapter (fragmentManager);
//Adding some fragments right from the beginning, you could ignore it if not needed.
addFragments();
//This `OnPageChangeListener` will do the trick for you.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//Show the title of fragment
Toast.makeText(MainActivity.this, adapter.screens.get(position), Toast.LENGTH_SHORT).show();
//If fragment being loaded is later than the first one,
// then add one more fragment after the last fragment to the adapter.
// integer currentPosition is declared as a field, outside onCreate method and initially set to 0.
if(position>currentPosition){
currentPosition+=1;
adapter.addFragment(new SectionFragment(), "Fragment"+String.valueOf(position+3));
adapter.notifyDataSetChanged();
}else{
currentPosition--;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
} // onCreate ends here.
Create this method inside your MainActivity (just to add 3 fragments to give your application a head-start.
private void addFragments(){
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
}
Then modify your SectionsPagerAdapter's getItem and getCount methods as below:
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return screens.get(position);
}
#Override
public int getCount() {
return screens.size();
}
//This method will dynamically add a fragment each time it is called.
public void addFragment(Fragment fragment) {
screens.add(fragment);
}
Now, no work related to "adding new fragment to the list" needs to be done inside your SectionFragment class.
I have a listview in which I'm loading all the images (as previews) from the user's SD card. I have a custom SimpleCursorAdapter and when I override the getView() method, I try to start background threads for the image loading.
What I'm trying to do is basically "lazy loading" the image previews into the listview using background threads or something. I'm open for new solutions. The main problem is that scrolling is ungodly slow since loading images is so expensive an operation.
Here's the relevant code I'm trying:
public class listOfImages extends SimpleCursorAdapter {
private Cursor c;
private Context context;
public listOfImages(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.image_item, null);
}
this.c.moveToPosition(pos);
int columnIndex = this.c.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
String name = this.c.getString(columnIndex);
columnIndex = this.c.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
String size = this.c.getString(columnIndex);
columnIndex = this.c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String data = this.c.getString(columnIndex); //gives the filename
TextView sTitle = (TextView) v.findViewById(R.id.image_title);
sTitle.setText(name);
imagePreviewLoader ipl = new imagePreviewLoader(v, data);
ipl.mainProcessing();
v.setTag(data);
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Image: " + v.getTag(), Toast.LENGTH_SHORT).show();
String filename = (String) v.getTag();
Intent intent = new Intent(context, ViewImage.class);
intent.putExtra("filename", filename);
context.startActivity(intent);
}
});
return v;
}
}
And now the background threading that I'm trying:
public class imagePreviewLoader {
private Handler handler = new Handler();
private View v;
private String data;
public imagePreviewLoader(View v, String data) {
this.v = v;
this.data = data;
}
protected void mainProcessing() {
Thread thread = new Thread(null, doBackground, "Background");
thread.start();
}
private Runnable doBackground = new Runnable() {
public void run() {
backgroundThreadProcessing();
}
};
private void backgroundThreadProcessing() {
handler.post(doUpdateGUI);
}
private Runnable doUpdateGUI = new Runnable() {
public void run() {
updateGUI();
}
};
private void updateGUI() {
ImageView img = (ImageView) v.findViewById(R.id.image_view);
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 30;
bfo.inTargetDensity = 50;
Bitmap bm = BitmapFactory.decodeFile(data, bfo);
img.setImageBitmap(bm);
}
}
The issue is that everything tries to load at once when you scroll, so scrolling is really slow. I thought what would happen is the imageview would just stay blank (or a placeholder) until the thread has loaded the appropriate image. I guess not though.
Thanks for any help.
Have a look at my answer to this question, it has a sample project which shows how to do it but downloading images from the net. You should be able to modify it quite easily to work for you getting images from the SD card.
I have an easy to use library under a basically public domain license that you can check out... It will cancel loading for rows that aren't displaying and uses two threads to do image loading.
You can check it out on my GitHub: https://github.com/tbiehn/Android-Adapter-Image-Loader