"can't video play error display" after playing video in android - android

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;
}
});

Related

Progress Dialog not displaying using Context in Android

I have a dialog fragment Java class which showing a dialog box it works so fine but the only problem is that the progressDialog is not showing while waiting for the response, this is different from the dialog box, this progressDialog works in AsyncTask while getting the response from the http.
here is my code:
package com.example.kapoyei.hatidtubigan.helper;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.kapoyei.hatidtubigan.R;
import com.example.kapoyei.hatidtubigan.other.Http;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class AddStation extends AppCompatDialogFragment implements View.OnClickListener {
public static String jsonObject; // THIS WILL BE THE HANDLER OF JSON LATER
Button btnCreate; // GET THE BUTTON
EditText etStationName, etAddress, etContact; // GET THE INPUT TEXT
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// CREATE A DIALOG BOX
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// GET THE LAYOUT
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_addstation, null);
builder.setView(view);
builder.setCancelable(true);
// GET THE VALUES
etStationName = (EditText) view.findViewById(R.id.etStationName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etContact = (EditText) view.findViewById(R.id.etContact);
btnCreate = (Button) view.findViewById(R.id.btnCreate);
// SET CLICK LISTENER OF THE BUTTON
btnCreate.setOnClickListener(this);
return builder.create();
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
Thread stationThread = new Thread() {
#Override
public void run() {
Looper.prepare();
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
}
};
stationThread.start();
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}
public class StoreStation extends AsyncTask<String, Void, String> {
ProgressDialog pd;
private Context mContext;
public StoreStation(Context c) {
mContext = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(mContext);
pd.setMessage("Adding station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
getResponse(result);
}
#Override
protected String doInBackground(String... url) {
String data = "";
jsonObject = "";
try {
String link = (String) url[0];
URL getURL = new URL(link);
HttpURLConnection huc = (HttpURLConnection) getURL.openConnection();
huc.setReadTimeout(10000);
huc.setConnectTimeout(15000);
huc.setRequestMethod("GET");
huc.setDoInput(true);
huc.connect();
InputStream is = huc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private void getResponse(String json) {
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("station");
String result = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
result = obj.getString("result");
}
if(result.equalsIgnoreCase("done")) {
Toast.makeText(mContext, "Successfully save!", Toast.LENGTH_LONG).show();
}
if(result.equalsIgnoreCase("exists")) {
Toast.makeText(mContext, "Station is already exists!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(mContext, "Connection problem", Toast.LENGTH_LONG).show();
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
}
In Android, only Main thread /UI thread can update UI
Other thread cannot update UI but your code is trying to run asynch task(which is a thread which run off/on UI accordingly, awesome!) in a worker thread which is causing the issues.
Solution: Execute Asynch task on UI thread
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}

how can I implement the onProgressUpdate method in this AsynTask Class

I'm working on a network scanner, and for that I'm sending the scan to the background using an AsyncTask class. But I'm having problems implementing the onProgressUpdate() method. I'm passing an ArrayList of type string to the TaskScanNetwork class. This array will have a list of all life host on network. Any help appreciated. Thanks
package com.example.android.droidscanner;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button btnRead;
Button btnScan;
TextView textResult;
ListView listViewNode;
ArrayList<Node> listNote;
ArrayList<String> listNetwork;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRead = (Button)findViewById(R.id.readhost);
btnScan = (Button) findViewById(R.id.readnet);
textResult = (TextView)findViewById(R.id.result);
listViewNode = (ListView)findViewById(R.id.nodelist);
listNote = new ArrayList<>();
listNetwork = new ArrayList<>();
//initidating adapter for host only
ArrayAdapter<Node> adapterHost = new ArrayAdapter<Node>(
MainActivity.this,
android.R.layout.simple_list_item_1,
listNote);
listViewNode.setAdapter(adapterHost);
//initiating adapter for network scan
ArrayAdapter<String> adapterNetwork = new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_list_item_1,
listNetwork);
listViewNode.setAdapter(adapterNetwork);
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskReadAddresses(listNote, listViewNode).execute();
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TaskScanNetwork(listNetwork, listViewNode).execute();
}
});
}
private class TaskReadAddresses extends AsyncTask<Void, Node, Void> {
ArrayList<Node> array;
ListView listView;
TaskReadAddresses(ArrayList<Node> array, ListView v){
listView = v;
this.array = array;
array.clear();
textResult.setText("querying...");
}
#Override
protected Void doInBackground(Void... params) {
readAddresses();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
textResult.setText("Done");
}
#Override
protected void onProgressUpdate(Node... values) {
listNote.add(values[0]);
((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
}
private void readAddresses() {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
Node thisNode = new Node(ip, mac);
publishProgress(thisNode);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* Asynctask to scan the network
* */
private class TaskScanNetwork extends AsyncTask<Void, ArrayList<String>, Void> {
String network;
ListView listView;
String lowBoundIp;
ArrayList<String> allNetwork;
TaskScanNetwork(ArrayList<String> array, ListView v){
listView = v;
allNetwork = array;
textResult.setText("Scanning...");
}
#Override
protected Void doInBackground(Void... params) {
scanNetwork();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
textResult.setText("Done");
}
#Override
protected void onProgressUpdate(ArrayList<String>... values) {
allNetwork.add(values);
((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
}
private void scanNetwork() {
try {
InetAddress localHost = InetAddress.getLocalHost();
lowBoundIp = localHost.getHostAddress();
int lastDot = lowBoundIp.lastIndexOf(".");
String host = lowBoundIp.substring(0, lastDot);
Process ping;
for(int i = 1; i < 255; i++) {
host = host + "." + Integer.toString(i);
try {
ping = Runtime.getRuntime().exec("ping -n 1 " + host);
int returnVal = ping.waitFor();
if(returnVal == 0) {
publishProgress(allNetwork);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Video Source file from YouTube crashes app in Android Studio

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"/>

Cannot display toast in a catch

package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.

Reading xml from rss feed

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. :)

Categories

Resources