App works fine when video is in the raw folder with media controllers. But when I put an embed src value from a Youtube video inside setVideoPath paranthesis, the app crashes. Please help!
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.VideoView;
import android.widget.MediaController;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView vid = (VideoView) findViewById(R.id.videoView);
vid.setVideoPath("https://www.youtube.com/embed/8iPFYfXuygk");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(vid);
vid.setMediaController(mediaController);
vid.start();
}
}
This Example code working fine for youetube Video play using videoview
package com.truiton.videoview;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
public class VideoViewActivity extends Activity {
private VideoView videoView;
private MediaController mController;
private Uri uriYouTube;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_view);
videoView = (VideoView) findViewById(R.id.videoView1);
mController = new MediaController(this);
videoView.setMediaController(mController);
videoView.requestFocus();
/*Uri uri = Uri.parse("android.resource://" + this.getPackageName() + "/"
+ R.raw.sample);
videoView.setVideoURI(uri);
videoView.start();*/
if (savedInstanceState != null) {
int loc = savedInstanceState.getInt("Loc");
Log.i("Loaction: ", loc + "");
uriYouTube = Uri.parse(savedInstanceState.getString("url"));
videoView.setVideoURI(uriYouTube);
videoView.seekTo(loc);
videoView.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.v("onPrepared", "ok");
mp.start();
}
});
} else {
RTSPUrlTask truitonTask = new RTSPUrlTask();
truitonTask.execute("http://www.youtube.com/watch?v=2zNSgSzhBfM");
}
}
void startPlaying(String url) {
uriYouTube = Uri.parse(url);
videoView.setVideoURI(uriYouTube);
videoView.start();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("Loc", videoView.getCurrentPosition());
outState.putString("url", uriYouTube.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.video_view, menu);
return true;
}
private class RTSPUrlTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = getRTSPVideoUrl(urls[0]);
return response;
}
#Override
protected void onPostExecute(String result) {
startPlaying(result);
}
public String getRTSPVideoUrl(String urlYoutube) {
try {
String gdy = "http://gdata.youtube.com/feeds/api/videos/";
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
String id = extractYoutubeId(urlYoutube);
URL url = new URL(gdy + id);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
Document doc = dBuilder.parse(connection.getInputStream());
Element el = doc.getDocumentElement();
NodeList list = el.getElementsByTagName("media:content");
String cursor = urlYoutube;
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node != null) {
NamedNodeMap nodeMap = node.getAttributes();
HashMap<String, String> maps = new HashMap<String, String>();
for (int j = 0; j < nodeMap.getLength(); j++) {
Attr att = (Attr) nodeMap.item(j);
maps.put(att.getName(), att.getValue());
}
if (maps.containsKey("yt:format")) {
String f = maps.get("yt:format");
if (maps.containsKey("url"))
cursor = maps.get("url");
if (f.equals("1"))
return cursor;
}
}
}
return cursor;
} catch (Exception ex) {
return urlYoutube;
}
}
public String extractYoutubeId(String url) throws MalformedURLException {
String query = new URL(url).getQuery();
String[] param = query.split("&");
String id = null;
for (String row : param) {
String[] param1 = row.split("=");
if (param1[0].equals("v")) {
id = param1[1];
}
}
return id;
}
}
}
Add add permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Related
I build an application to inserting the data into the file and saved in the internal memory and I used MediaScannerConnection class to visible the files in system while connecting the mobile to PC But if i deleted any file it is not effected to the mobile instantly
Here is my code:
package com.example.uhf.activity;
import android.app.Activity;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uhf.R;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
public class Main3Activity extends Activity {
ArrayList<String> sel=new ArrayList<String>();
ArrayList<String> arrayList=new ArrayList<String>();
Button button,mergeandexport;
File myExternalFile;
private String filepath = "Folder";
ArrayList<String> FilesInFolder ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
button=(Button)findViewById(R.id.button);
mergeandexport=(Button)findViewById(R.id.mergeandexport);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
ListView list=(ListView)findViewById(R.id.listview);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
FilesInFolder = GetFiles("/sdcard/Folder");
ArrayAdapter<String> aa=new ArrayAdapter<String> (this,R.layout.rowlayout,R.id.checked,FilesInFolder.toArray(new String[0]));
list.setAdapter(aa);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String string = ((TextView) view).getText().toString();
if(sel.contains(string)){
sel.remove(string);
}
else {
sel.add(string);
}
}
});
mergeandexport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
marged();
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
//f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=files.length-1; i>=0; i--)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
public void marged(){
try {
BufferedReader br=null;
String line;
for (int i=0;i<sel.size();i++){
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/sdcard/" + filepath,sel.get(i).toString()))));
while ((line = br.readLine()) != null) {
arrayList.add(line);
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
if(arrayList.size()==0){
Toast.makeText(this,"Choose more than one files",Toast.LENGTH_SHORT).show();
}
else if(arrayList.size()==1){
Toast.makeText(this,"Choose more than one files",Toast.LENGTH_SHORT).show();
}
else {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH-mm-ss");
String filename = formatter.format(Calendar.getInstance().getTime()).replace(" ", "_") + ".txt";
myExternalFile = new File("/sdcard/" + filepath, "Merged " + filename);
try {
// add elements to al, including duplicates
Set<String> hs = new HashSet<String>();
hs.addAll(arrayList);
arrayList.clear();
arrayList.addAll(hs);
FileOutputStream fos = new FileOutputStream(myExternalFile);
MediaScannerConnection.scanFile(this, new String[] {myExternalFile.toString()}, null, null);
for (int i = 0; i < arrayList.size(); i++) {
String extra = arrayList.get(i) + "\n";
fos.write(extra.getBytes());
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}``
Toast.makeText(this, "File is saved in "+filepath, Toast.LENGTH_LONG).show();
}
}
}
As title suggests, here is the format of the JSON:
http://prntscr.com/elb4fz. Now I'm not sure if I have the parse method working properly as I think that SearchResults is the array and it'll show each individual result as an object.
I have my networkutils code as such:
package companionsdirect.practice;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Albedo on 3/17/2017.
*/
public class NetworkingUtil {
private static final String TAG = "NetworkUtils";
List<Product> items = new ArrayList<>();
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() +
": with " + urlSpec);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrlString(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
public List<Product> fetchItems(String url) {
try {
String jsonString = getUrlString(url);
Log.i(TAG, "Received JSON: " + jsonString);
JSONObject jsonBody = new JSONObject(jsonString);
parseItems(items, jsonBody);
} catch (IOException ioe) {
Log.i(TAG, "Failed to fetch items", ioe);
} catch (JSONException je) {
Log.e(TAG, "Failed to parse JSON", je);
}
return items;
}
public List<Product> getProdList() {
return items;
}
private void parseItems(List<Product> items, JSONObject jsonBody) throws IOException, JSONException {
//JSONObject reviewItem = jsonBody.getJSONObject();
JSONArray reviewArray = jsonBody.getJSONArray("SearchResults");
for(int i = 0;i<reviewArray.length();i++) {
JSONObject reviewItem = reviewArray.getJSONObject(i);
Product currentProductReview = new Product();
currentProductReview.setmSummary(reviewItem.getString("Summary"));
currentProductReview.setmTitle(reviewItem.getString("Title"));
currentProductReview.setmRecordType(reviewItem.getString("RecordType"));
items.add(currentProductReview);
}
}
}
And this is the activity with the asynctask:
package companionsdirect.practice;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ReturnReviewsActivity extends AppCompatActivity {
public String builtURL;
List<Product> prodList;
private static final String TAG = "ReturnReviewsActivity";
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_return_reviews);
Intent intent = getIntent();
String url = intent.getStringExtra(MainActivity.EXTRA_MSG);
prodList = new ArrayList<Product>();
builtURL = url;
new FetchItemsTask().execute();
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
tv.setText(x.getmTitle() + " " + x.getRating() + " \n");
}
}
private class FetchItemsTask extends AsyncTask<Void, Void, Void> {
private List<Product> list;
#Override
protected Void doInBackground(Void... params) {
NetworkingUtil productData = new NetworkingUtil();
list = productData.fetchItems(builtURL);
return null;
}
}
}
What gives? The log shows that the json is being received,but I try to set the textview to whatever is in the list and nothing shows.
Try this
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
//append the text view
tv.append(x.getmTitle() + " " + x.getRating() + " \n");
}
Currently I am developing a Popular Movies app by udacity and stuck at loading images from the MovieDb api. I have also took reference from this thread Picasso Images are not loading in Gridview Android but no use.
Here is my fragment file:
package com.akshitjain.popularmovies;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
ImageAdapter mMoviesAdapter;
public MainActivityFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.grid_view_movies);
mMoviesAdapter = new ImageAdapter(getActivity());
gridview.setAdapter(mMoviesAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getActivity(), "" + position,
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_mainfragment,menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_refresh){
String sortOrder = "popularity.desc";
new FetchMoviesTask().execute(sortOrder);
return true;
}
return super.onOptionsItemSelected(item);
}
public class FetchMoviesTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private String[] getMoviesDataFromJson(String moviesJsonStr)
throws JSONException {
final String TMDB_RESULTS = "results";
final String TMDB_POSTER = "poster_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray moviesArray = moviesJson.getJSONArray(TMDB_RESULTS);
String[] resultStrs = new String[moviesArray.length()];
for(int i=0;i<moviesArray.length();++i) {
JSONObject movieObject = moviesArray.getJSONObject(i);
resultStrs[i] = movieObject.getString(TMDB_POSTER);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJsonStr;
String apiKey = BuildConfig.THE_MOVIE_DB_API_KEY;
try {
// Construct the URL for the TheMovieDb query
// Possible parameters are available at TheMovieDb API page
final String MOVIES_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String API_KEY = "api_key";
Uri builtUri = Uri.parse(MOVIES_BASE_URL).buildUpon()
.appendQueryParameter(SORT_PARAM,params[0])
.appendQueryParameter(API_KEY,apiKey)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG,"BuiltUri: " + builtUri.toString());
// Create the request to TheMovieDb, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
moviesJsonStr = buffer.toString();
Log.v(LOG_TAG,"Movies Json String: " + moviesJsonStr);
} catch (IOException e) {
Log.e("MainActivityFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivityFragment", "Error closing stream", e);
}
}
}
try{
return getMoviesDataFromJson(moviesJsonStr);
}catch (JSONException e){
Log.e(LOG_TAG,e.getMessage(),e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
if(strings != null){
mMoviesAdapter.clear();
for(String moviesStr:strings){
mMoviesAdapter.add(moviesStr);
}
}
mMoviesAdapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
Here is my custom adapter file:
package com.akshitjain.popularmovies;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ImageAdapter extends BaseAdapter {
private final String LOG_TAG = ImageAdapter.class.getSimpleName();
private Context mContext;
List<String> list = new ArrayList<>();
public ImageAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item_movies, parent, false);
}
final String POSTER_BASE_URL = " http://image.tmdb.org/t/p/";
final String POSTER_SIZE = "w185";
ImageView moviePoster = (ImageView) convertView.findViewById(R.id.grid_item_movie_image);
final String POSTER_FINAL_URL = POSTER_BASE_URL + POSTER_SIZE + list.get(position);
Log.v(LOG_TAG,"Poster Urls: " + POSTER_FINAL_URL);
Picasso.with(mContext).load(POSTER_FINAL_URL).into(moviePoster);
return convertView;
}
public void add(String s) {
list.add(s);
}
public void clear() {
list.clear();
}
}
There is no error in the code. App runs successfully. But images are not loading.
final String POSTER_BASE_URL = " http://image.tmdb.org/t/p/";
The space at the beginning of the string was the issue. Picasso will try and load url with space at front.
So String.trim() will remove the space from the beginning as well as the end of a String.
Picasso.with(mContext).load(POSTER_FINAL_URL.trim()).into(moviePoster)
In my code ,display youtube video in video viewer.
I am successfully done but end of the video display dialogue "Can't not play video"
here my code
package com.example.videodemo;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity {
private VideoView videoViewer;
private ProgressBar mProgressBar;
String videoUrl ="http://podcast.20min-tv.ch/podcast/20min/199733.mp4";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoViewer=(VideoView)findViewById(R.id.videoView1);
//videoViewer.setVideoPath("/sdcard/documentariesandyou.mp4");
/* Uri uri=Uri.parse(path1);
http://www.youtube.com/watch?v=Hxy8BZGQ5Jo
videoViewer.setVideoURI(uri); */
mProgressBar = (ProgressBar) findViewById(R.id.Progressbar);
mProgressBar.setProgress(0);
mProgressBar.setMax(100);
mProgressBar.setVisibility(View.INVISIBLE);
videoViewer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(MainActivity.this, "End Video", Toast.LENGTH_LONG).show();
}
});
new YourAsyncTask().execute();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(MainActivity.this, "Pause Video", Toast.LENGTH_LONG).show();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(MainActivity.this, "Stop Video", Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
//Toast.makeText(MainActivity.this, "Destroy Video", Toast.LENGTH_LONG).show();
/*WifiManager wifiManager = null;
wifiManager.disconnect();*/
}
private class YourAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
}
#Override
protected Void doInBackground(Void... params)
{
try
{
String url = "https://www.youtube.com/watch?v=SyrO83x7g-E";
videoUrl = getUrlVideoRTSP(url);
Log.e("Video url for playing=========>>>>>", videoUrl);
}
catch (Exception e)
{
Log.e("Login Soap Calling in Exception", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
try {
progressDialog.dismiss();
videoViewer.setVideoURI(Uri.parse(videoUrl));
MediaController mc = new MediaController(MainActivity.this);
//videoViewer.setMediaController(mc);
videoViewer.requestFocus();
videoViewer.start();
mc.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static String getUrlVideoRTSP(String urlYoutube)
{
try
{
String gdy = "http://gdata.youtube.com/feeds/api/videos/";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String id = extractYoutubeId(urlYoutube);
URL url = new URL(gdy + id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Document doc = documentBuilder.parse(connection.getInputStream());
Element el = doc.getDocumentElement();
NodeList list = el.getElementsByTagName("media:content");///media:content
String cursor = urlYoutube;
for (int i = 0; i < list.getLength(); i++)
{
Node node = list.item(i);
if (node != null)
{
NamedNodeMap nodeMap = node.getAttributes();
HashMap<String, String> maps = new HashMap<String, String>();
for (int j = 0; j < nodeMap.getLength(); j++)
{
Attr att = (Attr) nodeMap.item(j);
maps.put(att.getName(), att.getValue());
}
if (maps.containsKey("yt:format"))
{
String f = maps.get("yt:format");
if (maps.containsKey("url"))
{
cursor = maps.get("url");
}
if (f.equals("1"))
return cursor;
}
}
}
return cursor;
}
catch (Exception ex)
{
Log.e("Get Url Video RTSP Exception======>>", ex.toString());
}
return urlYoutube;
}
protected static String extractYoutubeId(String url) throws MalformedURLException
{
String id = null;
try
{
String query = new URL(url).getQuery();
if (query != null)
{
String[] param = query.split("&");
for (String row : param)
{
String[] param1 = row.split("=");
if (param1[0].equals("v"))
{
id = param1[1];
}
}
}
else
{
if (url.contains("embed"))
{
id = url.substring(url.lastIndexOf("/") + 1);
}
}
}
catch (Exception ex)
{
Log.e("Exception", ex.toString());
}
return id;
}
}
Use this method to extract videoid
public String extractYoutubeId(String videoUrl) {
String video_id = "";
if (videoUrl != null && videoUrl.trim().length() > 0) {
String expression = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*";
CharSequence input = videoUrl;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String groupIndex1 = matcher.group(7);
if (groupIndex1 != null && groupIndex1.length() == 11)
video_id = groupIndex1;
}
}
return video_id;
}
UPDATE add one more listener
videoview.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// hadle the error
return true;
}
});
package com.example.nasadailyimage;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class NasaDailyImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nasa_daily_image);
IotdHandler handler = new IotdHandler();
System.out.println("handler object created");
Log.d("NasaDailyImage","handler object created");
new ConfigParser().execute();//here i have called execute on my AsyncTaskclass
// handler.processFeed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nasa_daily_image, menu);
return true;
}
}
and my ConfigParser class
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.os.AsyncTask;
import android.util.Log;
public class ConfigParser extends AsyncTask<Void, Void,Void > {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
IotdHandler handler=new IotdHandler();
reader.setContentHandler(handler);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
}
catch (Exception e)
{
Log.d("IotdHandler", "Exception");
e.printStackTrace();
}
return null;
}
}
and my IotdHandler Class
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class IotdHandler extends DefaultHandler {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
private String imageUrl;
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (IOException ioe)
{ ioe.printStackTrace(); }
return null;
}
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if (localName.equals("enclosure"))
{ inUrl = true;
imageUrl=attributes.getValue("url");
System.out.println(imageUrl);
}
else { inUrl = false; }
if (localName.startsWith("item"))
{ inItem = true; }
else if (inItem) {
if (localName.equals("title"))
{ inTitle = true;
System.out.println("invtitle");}
else { inTitle = false; }
if (localName.equals("description"))
{ inDescription = true;
System.out.println("indiscription");}
else { inDescription = false; }
if (localName.equals("pubDate"))
{ inDate = true;
System.out.println("dtae");}
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(imageUrl); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
So basically I want to get daily image updates from NASA, but in my program everything is returning null I don't know what I am trying wrong, my xml file is not parsing to avoid the NetworkOnMainTHread I have also used Async class, any help.
Here is the code parsing xml rss feed...
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class XMLParsingDOMExample extends Activity {
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> pubDate;
ItemAdapter adapter1;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ListView list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
pubDate = new ArrayList<String>();
parse();
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("description");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
description.add(((Node) websiteList.item(0)).getNodeValue());
NodeList websiteList1 = fstElmnt.getElementsByTagName("pubDate");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
pubDate.add(((Node) websiteList1.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView date_text;
}
public ItemAdapter(Context context) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.date_text = (TextView) view.findViewById(R.id.date_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+Html.fromHtml(description.get(position)));
holder.date_text.setText(""+pubDate.get(position));
return view;
}
}
}
I posted a Gist on how to do this using the android-rss library with the droidQuery library:
final RSSHandler handler = new RSSHandler(new RSSConfig());
$.ajax(new AjaxOptions().url(options.url())
.type("GET")
.dataType("XML")
.context(this)
.SAXContentHandler(handler)
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
RSSFeed feed = handler.feed();
//TODO: handle feed here.
}
}));
Make an interface in your project first
public interface mMyInterface {
void processFinish(String response);
}
Then in your AsyncTaskClass do the following modifications
public class ConfigParser extends AsyncTask<Void, Void,Void > {
public mMyInterface delegate=null;
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
//Log.i("inJSONPARSERCLASS","success");
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
HttpResponse httpResponse=client.execute(post);
HttpEntity entity=httpResponse.getEntity();
is=entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.e("Connection Error", "Error " + e.toString());
}
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
xml=sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("main XML",""+xml);
return xml;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
delegate.processFinish(result);
}
}
Now in your class which is extending the activity , implement the interface mMyInterface , this will override its method processFinish(String response), now use "response" as a string and pass it to the class where the parsing is being done
#Override
public void processFinish(String response) {
String xml=response;
//do SAXparsing stuff here, parse this xml string which contains the whole data u need to
parse
}
I hope this hint will work out for you very well. :)