Cannot make a static reference to a non-static method - java

I'm trying to call 4 methods to use as arguments in another. I'm getting a "Cannot make a static reference to a non-static method" error. My problem is that I understand why my methods aren't already static.
Origin class:
public class IotdHandler extends DefaultHandler {
private String url = "http://www.nasa.gov/rss/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;
public void processFeed() {
try {
SAXParserFactory factory =
SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e)
{ }
}
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) { return null; }
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("url")) { inUrl = true; }
else { inUrl = false; }
if (localName.startsWith("item")) { inItem = true; }
else if (inItem) {
if (localName.equals("title")) { inTitle = true; }
else { inTitle = false; }
if (localName.equals("description")) { inDescription = true; }
else { inDescription = false; }
if (localName.equals("pubDate")) { inDate = true; }
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(chars); }
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; }
}
calling method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_image);
IotdHandler handler = new IotdHandler();
handler.processFeed();
resetDisplay(IotdHandler.getTitle(), IotdHandler.getDate(),
IotdHandler.getImage(), IotdHandler.getDescription());
}

Use handler instead of IotdHandler for accessing non-static methods from IotdHandler class same as you are accessing processFeed() method from IotdHandler.:
resetDisplay(handler.getTitle(), handler.getDate(),
handler.getImage(), handler.getDescription());

You have to call.
resetDisplay(handler.getTitle(), handler.getDate(),
handler.getImage(), handler.getDescription());

Related

How to merge, create tags and put an ascending order the feeds of more RSS Feed links like on Yahoo Pipes?

I need to take the feeds of more RSS Feed urls that I have to aggregate and show the news in descending order.
Some links don't have an xml tag for <category> so I need to create one: I have to know where feeds come from so that I can categorize them.
This is what I'm trying to achieve: ( for Source n I mean the category)
[![enter image description here][1]][1]
I used to use Yahoo!Pipes to make all these changes.
My attempt was to create a CustomListView for each url and then execute the AsyncTasks all at once but that is not working correctly - the feeds are not displayed in ascending order.
MainActivity
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private RSSFeed myRssFeed = null;
String[] urlFeed = {"url1", "url2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i = 0; i < urlFeed.length; i++) {
News news = new News(i);
news.execute();
}
}
#Override
public void onRefresh() {
for (int i = 0; i < urlFeed.length; i++) {
News news = new News(i);
news.execute();
}
}
private class News extends AsyncTask<Object, Void, Void> {
protected int number;
public News(int urlNumber) {
number = urlNumber;
}
#Override
protected Void doInBackground(Object... arg0) {
String data = "";
InputStream iStream;
try{
URL url = new URL(urlFeed[number]);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sbf = new StringBuilder();
String line;
while( ( line = br.readLine()) != null){
sbf.append(line);
}
data = sbf.toString();
br.close();
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(url.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (ParserConfigurationException | IOException | SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (myRssFeed != null) {
NestedListView list = (NestedListView)findViewById(android.R.id.list);
list.setVisibility(View.VISIBLE);
CustomList adapter = new CustomList(MainActivity.this, myRssFeed.getList());
adapter.addAll();
list.setAdapter(adapter);
} else
Toast.makeText(MainActivity.this, "Error",
Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
RSSFeed
public class RSSFeed {
private String title = null;
private String description = null;
private String link = null;
private String pubdate = null;
private String image = null;
private String enclosure = null;
private String author = null;
private List<RSSItem> itemList;
RSSFeed(){
itemList = new Vector<RSSItem>(0);
}
void addItem(RSSItem item){
itemList.add(item);
}
RSSItem getItem(int location){
return itemList.get(location);
}
List<RSSItem> getList(){
return itemList;
}
}
RSSItem
public class RSSItem {
private String title = null;
private String description = null;
private String link = null;
private String pubdate = null;
private String image = null;
private String enclosure = null;
private String author = null;
}
CustomList
public class CustomList extends ArrayAdapter<RSSItem> {
private static Activity context = null;
private final List<RSSItem> web;
public CustomList(Activity context, List<RSSItem> web) {
super(context, R.layout.new_listview, web);
CustomList.context = context;
this.web = web;
}
#SuppressLint("SetTextI18n")
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
#SuppressLint({"ViewHolder", "InflateParams"}) final View rowView = inflater.inflate(R.layout.new_listview, null, true);
ImageView imageView = (ImageView)rowView.findViewById(R.id.image);
Picasso.with(context).load(web.get(position).getImage()).into(imageView);
TextView textView = (TextView)rowView.findViewById(R.id.title);
textView.setText(Html.fromHtml(web.get(position).getTitle()));
TextView textView1 = (TextView)rowView.findViewById(R.id.description);
textView1.setText(web.get(position).getDescription());
TextView textView2 = (TextView)rowView.findViewById(R.id.pubdate);
textView2.setText(pubdate);
return rowView;
}
}
RSSHandler
public class RSSHandler extends DefaultHandler {
final int state_unknown = 0;
final int state_title = 1;
final int state_description = 2;
final int state_link = 3;
final int state_pubdate = 4;
final int state_enclosure = 6;
final int state_image = 5;
final int state_author = 7;
int currentState = state_unknown;
String url;
RSSFeed feed;
RSSItem item;
boolean itemFound = false;
RSSHandler(){
}
RSSFeed getFeed(){
return feed;
}
#Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
feed = new RSSFeed();
item = new RSSItem();
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
itemFound = true;
item = new RSSItem();
currentState = state_unknown;
}
else if (localName.equals("enclosure")) {
url = attributes.getValue("url");
currentState = state_image;
}
else if (localName.equalsIgnoreCase("title")){
currentState = state_title;
}
else if (localName.equalsIgnoreCase("description")){
currentState = state_description;
}
else if (localName.equalsIgnoreCase("link")){
currentState = state_link;
}
else if (localName.equalsIgnoreCase("pubdate")){
currentState = state_pubdate;
}
else if (localName.equalsIgnoreCase("author")){
currentState = state_author;
}
else{
currentState = state_unknown;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
if (localName.equalsIgnoreCase("item")){
feed.addItem(item);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
String strCharacters = new String(ch,start,length);
if (itemFound){
// "item" tag found, it's item's parameter
switch(currentState){
case state_enclosure:
item.setEnclosure(strCharacters);
break;
case state_title:
item.setTitle(strCharacters);
break;
case state_image:
item.setImage(url);
break;
case state_description:
item.setDescription(strCharacters);
break;
case state_link:
item.setLink(strCharacters);
break;
case state_pubdate:
item.setPubdate(strCharacters);
break;
case state_author:
item.setAuthor(strCharacters);
break;
default:
break;
}
}
else{
// not "item" tag found, it's feed's parameter
switch(currentState){
case state_enclosure:
feed.setEnclosure(strCharacters);
break;
case state_title:
feed.setTitle(strCharacters);
break;
case state_image:
feed.setImage(url);
break;
case state_description:
feed.setDescription(strCharacters);
break;
case state_link:
feed.setLink(strCharacters);
break;
case state_pubdate:
feed.setPubdate(strCharacters);
break;
case state_author:
feed.setAuthor(strCharacters);
break;
default:
break;
}
}
currentState = state_unknown;
}
The solution requires more than one change. The first thing you need to do is make each News task that finishes adds its data to the one big list. That list can then be sorted which requires a Comparator.
You also need a list of the names to show in the placeholder youve called Source n in your image and lastly, so that you can compare them, you need to parse the dates as actual dates.
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private List<RSSItem> totalRssFeed = new ArrayList<>();
String[] urlFeed = {"MyURL", "MyUrl2", "MyUrl3"};
String[] names = {"Name", "Name2", "Name3"}
private CustomList adapter;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
ListView list = (ListView) findViewById(android.R.id.list);
adapter = new CustomList(MainActivity.this);
list.setAdapter( adapter );
}
#Override
protected void onResume() {
// do this here and you dont need to repeat it in refresh and create
for (int i = 0; i < urlFeed.length; i++) {
News news = new News(i);
news.execute();
}
}
public class CustomList extends ArrayAdapter<RSSItem> {
...
public CustomList(Activity context) { //dont start with default data
super(context, R.layout.new_listview, null);
}
...
}
private class News extends AsyncTask<Object, Void, Void> {
protected int number;
public News(int urlNumber) {
number = urlNumber;
}
#Override
protected Void doInBackground(Object... arg0) {
try {
//no need to do the input stuff you were doing before here?
URL url = new URL(urlFeed[number]);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler(names[number]);
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(url.openStream());
myXMLReader.parse(myInputSource);
totalRssFeed.addAll(myRSSHandler.getFeed());
Collections.sort(totalRssFeed);
} catch (ParserConfigurationException | IOException | SAXException e) { /* stuff */ }
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.clear();
adapter.addAll(totalRssFeed);
}
}
public class RSSItem implements Comparable<RSSItem> {
public String tag;
public Date pubdate; //just public so i didnt need setters in this example
public RSSItem(String defaultTagToUse) {
//You should set the default to whatever you want displayed
//when the tag for <category> is missing, and just update it normally otherwise
tag = defaultTagToUse;
}
void setPubDate(Date date) {
pubdate = date;
}
...
#Override
public int compareTo(#NonNull RSSItem another) {
int res;
if (pubdate == null) {
if (another.pubdate == null) {
res = 0;
} else {
res = -1;
}
} else {
if (another.pubdate == null || pubdate.getTime() > another.pubdate.getTime()) {
res = 1;
} else {
res = -1;
}
}
return res;
}
}
public class RSSHandler extends DefaultHandler {
...
List<RSSItem> feed;
RSSItem item;
String mName;
public RssHandler(String name) {
mName = name;
}
List<RSSItem> getFeed() {
return feed;
}
#Override
public void startDocument() throws SAXException {
feed = new ArrayList<>();
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equalsIgnoreCase("item")) {
itemFound = true;
item = new RSSItem( name );
currentState = state_unknown;
} else ...
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("item")) {
feed.add(item);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
...
case state_pubdate:
SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); //make sure you match the format from your XML
item.setPubdate( formatter.parse(stringCharacters) );
break;
...
}
}
}
All the ...'s jsut mean leave everything as it was in those places

unable to decode stream java.io.FileNotFoundException /storage/emulated/0

hello i'm trying to save pictures taken from url on my application, but when i try to access the memory to place the data, an error comes out
unable to decode stream java.io.FileNotFoundException /storage/emulated/0 open failed:ENOENT(No such file or directory)
this is my DownloadManager Class
public static ArrayList<String> urls = new ArrayList<String>();
public static OnDownloadCompleteListener downloadCompleteListener;
public static void copyFile(String sourceFile, String destinationFile) {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void initialize() {
downloadCompleteListener = new OnDownloadCompleteListener() {
#Override
public void onDownloadComplete(String url, String localPath) {
Log.i("LOG", "Image Download Complete, Original URL: " + url + ", Save Path: " + localPath);
String newPath = localPath.replace("/temp/", "/final/");
copyFile(localPath, newPath);
String filename = HelperString.getFileName(localPath);
new File(localPath).delete();
Set<ImageView> imageViews = AdapterSerials.imageMap.keySet();
for (ImageView imageView: imageViews) {
if (AdapterSerials.imageMap.get(imageView).equals(filename)) {
if (imageView != null) {
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(newPath, options);
imageView.setImageBitmap(bitmap);
}
}
}
}
};
}
public static void addToDownloadList(String url, ImageView imgLogo) {
String filename = HelperString.getFileName(url);
AdapterSerials.imageMap.put(imgLogo, filename);
if (urls.contains(url)) {
return;
}
if (new File(G.DIR_FINAL + "/" + filename).exists()) {
return;
}
urls.add(url);
DownloadRequest downloadRequest = new DownloadRequest()
.downloadPath("http://87.236.215.180/mazi/" + url)
.filepath(G.DIR_TEMP + "/" + filename)
.listener(downloadCompleteListener)
.download();
}
this is my DownloadRequest Class :
public class DownloadRequest {
private int downloadedSize;
private int totalSize;
private int percent;
public int getDownloadedSize() {
return downloadedSize;
}
public int getTotalSize() {
return totalSize;
}
public int getPercent() {
return percent;
}
public DownloadRequest download() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(downloadPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
totalSize = connection.getContentLength();
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = new FileOutputStream(filepath);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
downloadedSize += len;
percent = (int) (100.0f * (float) downloadedSize / totalSize);
if (percent == 100 && listener != null) {
G.HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onDownloadComplete(downloadPath, filepath);
}
});
}
if (simulate) {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
outputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return this;
}
private String downloadPath;
private String filepath;
private OnDownloadCompleteListener listener;
private boolean simulate;
public DownloadRequest downloadPath(String value) {
downloadPath = value;
return this;
}
public DownloadRequest filepath(String value) {
filepath = value;
return this;
}
public DownloadRequest listener(OnDownloadCompleteListener value) {
listener = value;
return this;
}
public DownloadRequest simulate(boolean value) {
simulate = value;
return this;
}
And this is my G class :
public class G extends Application {
public static Context context;
public static final String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String DIR_APP = SDCARD + "/serial";
public static final String DIR_CACHE = DIR_APP + "/cache";
public static LayoutInflater inflater;
public static final Handler HANDLER = new Handler();
public static Activity currentActivity;
public static StructSerials selectedSerials;
public static StructFavSerials selectedFavSerials;
public static ArrayList<StructComment> rates = new ArrayList<StructComment>();
public static final int DOWNLOAD_BUFFER_SIZE = 8 * 1024;
public static final String DIR_FINAL = DIR_APP + "/final";
public static final String DIR_TEMP = DIR_APP + "/temp";
public static String android_id;
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
preferences = PreferenceManager.getDefaultSharedPreferences(context);
initImageLoader(getApplicationContext());
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
new File(DIR_APP).mkdirs();
new File(DIR_CACHE).mkdirs();
new File(DIR_TEMP).mkdirs();
new File(DIR_FINAL).mkdirs();
DownloadManager.initialize();
}
remember add this permission into your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Writing custom Android ViewAction to take screenshot

I'm trying to take a screenshot before I perform an action in Android using espresso.
protected T performAction(ViewAction viewAction) {
ViewAction screenShotAction = new ScreenShotAction();
viewInteraction.perform(screenShotAction);
viewInteraction.perform(viewAction);
return returnGeneric();
}
For example if in my test I perform a click() then I would take a screenshot of the device before I performed the click().
This is the code for taking the screenshot in the ScreenShotAction class
#Override
public void perform(UiController uiController, View view) {
View rootView = view.getRootView();
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
File picDir = new File(Environment.getExternalStorageDirectory() + "app_" + "test");
if (!picDir.exists()) {
picDir.mkdir();
}
rootView.setDrawingCacheEnabled(true);
rootView.buildDrawingCache(true);
Bitmap bitmap = rootView.getDrawingCache();
String fileName = "test.jpg";
File picFile = new File(picDir + "/" + fileName);
try {
picFile.createNewFile();
FileOutputStream picOut = new FileOutputStream(picFile);
bitmap = Bitmap.createBitmap(rootView.getWidth(), rootView.getHeight(), Bitmap.Config.ARGB_8888);
boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, picOut);
if (saved) {
// good
} else {
// error
throw new Exception("Image not saved");
}
picOut.flush();
picOut.close();
} catch (Exception e) {
e.printStackTrace();
}
rootView.destroyDrawingCache();
}
}
I do not see any image files in the phone's Pictures directory or any other directory. I believe the screenshot method is solid but am unsure if I am calling the method correctly.
Is viewInteraction.perform(screenShotAction) the corret way to call my custom view action?
Please help and thank you in advance.
You can do the following:
public class CaptureImage {
#SuppressWarnings("unused")
private static final String TAG = CaptureImage.class.getSimpleName();
private static final String NAME_SEPARATOR = "_";
private static final String EXTENSION = ".png";
private static final Object LOCK = new Object();
private static boolean outputNeedsClear = true;
private static final Pattern NAME_VALIDATION = Pattern.compile("[a-zA-Z0-9_-]+");
public static void takeScreenshot(View currentView, String className,
String methodName, #Nullable String prefix) {
methodName = methodName.replaceAll("[\\[\\](){}]", "");
if (!NAME_VALIDATION.matcher(methodName).matches()) {
throw new IllegalArgumentException(
"Name must match " + NAME_VALIDATION.pattern() +
" and " + methodName + " was received.");
}
Context context = InstrumentationRegistry.getTargetContext();
MyRunnable myRunnable = new MyRunnable(context, currentView, className, methodName, prefix);
Activity activity =
((Application)context.getApplicationContext()).getCurrentActivity();
activity.runOnUiThread(myRunnable);
}
private static class MyRunnable implements Runnable {
private View mView;
private Context mContext;
private String mClassName;
private String mMethodName;
private String mPrefix;
MyRunnable(Context context, View view, String className, String methodName, String prefix) {
mContext = context;
mView = view;
mClassName = className;
mMethodName = methodName;
mPrefix = prefix;
}
#TargetApi(VERSION_CODES.JELLY_BEAN_MR2)
public void run() {
UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
if (uiAutomation == null) {
return;
}
OutputStream out = null;
Bitmap bitmap = null;
try {
String timestamp = new SimpleDateFormat("MM_dd_HH_mm_ss", Locale.ENGLISH)
.format(new Date());
File screenshotDirectory = getScreenshotFolder();
int statusBarHeight = getStatusBarHeightOnDevice();
bitmap = uiAutomation.takeScreenshot();
Bitmap screenshot = Bitmap.createBitmap(bitmap, 0, statusBarHeight,
mView.getWidth(), mView.getHeight() - statusBarHeight);
String screenshotName = mMethodName + NAME_SEPARATOR +
(mPrefix != null ? (mPrefix + NAME_SEPARATOR) : "") +
timestamp + EXTENSION;
Log.d("YOUR_TAG", "Screenshot name: " + screenshotName);
File imageFile = new File(screenshotDirectory, screenshotName);
out = new FileOutputStream(imageFile);
screenshot.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
} catch (Throwable t) {
Log.e("YOUR_LOG", "Unable to capture screenshot.", t);
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {
}
if (bitmap != null) {
bitmap.recycle();
}
}
}
private int getStatusBarHeightOnDevice() {
int _StatusBarHeight = 0;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
mView.setDrawingCacheEnabled(true);
Bitmap screenShot = Bitmap.createBitmap(mView.getDrawingCache());
mView.setDrawingCacheEnabled(false);
if (screenShot != null) {
int StatusColor = screenShot.getPixel(0, 0);
for (int y = 1; y < (screenShot.getHeight() / 4); y++) {
if (screenShot.getPixel(0, y) != StatusColor) {
_StatusBarHeight = y - 1;
break;
}
}
}
if (_StatusBarHeight == 0) {
_StatusBarHeight = 50; // Set a default in case we don't find a difference
}
Log.d("YOUR_TAG", "Status Bar was measure at "
+ _StatusBarHeight + " pixels");
return _StatusBarHeight;
}
private File getScreenshotFolder() throws IllegalAccessException {
File screenshotsDir;
if (Build.VERSION.SDK_INT >= 21) {
// Use external storage.
screenshotsDir = new File(getExternalStorageDirectory(),
"screenshots");
} else {
// Use internal storage.
screenshotsDir = new File(mContext.getApplicationContext().getFilesDir(),
"screenshots");
}
synchronized (LOCK) {
if (outputNeedsClear) {
deletePath(screenshotsDir);
outputNeedsClear = false;
}
}
File dirClass = new File(screenshotsDir, mClassName);
File dirMethod = new File(dirClass, mMethodName);
createDir(dirMethod);
return dirMethod;
}
private void createDir(File dir) throws IllegalAccessException {
File parent = dir.getParentFile();
if (!parent.exists()) {
createDir(parent);
}
if (!dir.exists() && !dir.mkdirs()) {
throw new IllegalAccessException(
"Unable to create output dir: " + dir.getAbsolutePath());
}
}
private void deletePath(File path) {
if (path.isDirectory() && path.exists()) {
File[] children = path.listFiles();
if (children != null) {
for (File child : children) {
Log.d("YOUR_TAG", "Deleting " + child.getPath());
deletePath(child);
}
}
}
if (!path.delete()) {
// log message here
}
}
}
Then you can call it from a ViewAction or from the test case class directly:
View Action Class:
class ScreenshotViewAction implements ViewAction {
private final String mClassName;
private final String mMethodName;
private final int mViewId;
private final String mPrefix;
protected ScreenshotViewAction(final int viewId, final String className,
final String methodName, #Nullable final String prefix) {
mViewId = viewId;
mClassName = className;
mMethodName = methodName;
mPrefix = prefix;
}
#Override
public Matcher<View> getConstraints() {
return ViewMatchers.isDisplayed();
}
#Override
public String getDescription() {
return "Taking a screenshot.";
}
#Override
public void perform(final UiController aUiController, final View aView) {
aUiController.loopMainThreadUntilIdle();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + 2000;
final Matcher<View> viewMatcher = ViewMatchers.withId(mViewId);
do {
for (View child : TreeIterables.breadthFirstViewTraversal(aView)) {
// found view with required ID
if (viewMatcher.matches(child)) {
CaptureImage.takeScreenshot(aView.getRootView(), mClassName,
mMethodName, mPrefix);
return;
}
}
aUiController.loopMainThreadForAtLeast(50);
}
while (System.currentTimeMillis() < endTime);
}
}
Now from your test case class, create the following static methods:
public static void takeScreenshot(int prefix) {
View currentView = ((ViewGroup)mActivity
.getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);
String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();
String testClassName = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String testMethodName = Thread.currentThread().getStackTrace()[3].getMethodName();
CaptureImage.takeScreenshot(currentView, testClassName, testMethodName,
String.valueOf(prefix));
}
public static ViewAction takeScreenshot(#Nullable String prefix) {
String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();
String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
return new ScreenshotViewAction(getDecorView().getId(), className, methodName, prefix);
}
Or you can invoke it from the perform view action:
takeScreenshot(0);
onView(withContentDescription(sContext
.getString(R.string.abc_action_bar_up_description)))
.perform(
ScreenshotViewAction.takeScreenshot(String.valueOf(1)),
click()
);

Android Shoutcast internet Radio Streaming

I developed Shoutcastinternet Radio Streaming and I'm able to stream and play Successfully.
But the problem is: when i execute my application,I'm able to stream and play Continuously for halfanhour,after that the stream is getting stopped(not able to play, after that if i click on again play the stream Continues and again after some time FileNotFoundException)?
I logged the Error, after Stream get stopped.
The Error is :
java.io.FileNotFoundException: /data/data/com.torilt/cache/downloadingMediaFile430 (No such file or directory)
Can't find file. Android must have deleted it on a clean up
Getting Exception in setupplayer()
Source Code:
public class StreamingMediaPlayer extends Service {
final static public String AUDIO_MPEG = "audio/mpeg";
final static public String BITERATE_HEADER = "icy-br";
public int INTIAL_KB_BUFFER ;
private Handler handler;
//= 96*10/8
final public int BIT = 8;
final public int SECONDS = 60;
int bitrate = 56;
public File downloadingMediaFile;
final public String DOWNFILE = "downloadingMediaFile";
public Context context;
public int counter;
public int playedcounter;
public int preparecounter;
public MediaPlayer mp1;
public MediaPlayer mp2;
public boolean mp1prepared;
public boolean mp2prepared;
public boolean mp1preparing;
public boolean mp2preparing;
public boolean downloadingformp1;
public boolean downloadingformp2;
public boolean prepareState;
public String SONGURL = "";
// playing is "true" for mp1 and "false" for mp2
public boolean mp1playing;
public boolean started;
public boolean processHasStarted;
public boolean processHasPaused;
public boolean regularStream;
public BufferedInputStream stream;
public URL url;
public URLConnection urlConn;
public String station;
public String audiourl;
public Intent startingIntent = null;
public boolean stopping;
Thread preparringthread;
boolean waitingForPlayer;
// Setup all the variables
private void setupVars() {
counter = 0;
playedcounter = 0;
preparecounter = 0;
mp1 = new MediaPlayer();
mp2 = new MediaPlayer();
mp1prepared = false;
mp2prepared = false;
mp1preparing = false;
mp2preparing = false;
downloadingformp1 = false;
downloadingformp2 = false;
prepareState = true;
mp1playing = false;
started = false;
processHasStarted = false;
processHasPaused = true;
regularStream = false;
stream = null;
url = null;
urlConn = null;
station = null;
audiourl = null;
stopping = false;
preparringthread = null;
waitingForPlayer = false;
}
// This object will allow other processes to interact with our service
private final IStreamingMediaPlayer.Stub ourBinder = new IStreamingMediaPlayer.Stub() {
// String TAG = "IStreamingMediaPlayer.Stub";
public String getStation() {
// Log.d(TAG, "getStation");
return station;
}
public String getUrl() {
// Log.d(TAG, "getUrl");
return audiourl;
}
public boolean playing() {
// Log.d(TAG, "playing?");
return isPlaying();
}
public boolean pause() {
// Log.d(TAG, "playing?");
return isPause();
}
public void startAudio() {
// Log.d(TAG, "startAudio");
Runnable r = new Runnable() {
public void run() {
onStart(startingIntent, 0);
}
};
new Thread(r).start();
}
public void stopAudio() {
// Log.d(TAG, "stopAudio");
stop();
}
};
#Override
public void onCreate() {
super.onCreate();
context = this;
}
#Override
public void onStart(Intent intent, int startId) throws NullPointerException {
super.onStart(intent, startId);
// final String TAG = "StreamingMediaPlayer - onStart";
context = this;
setupVars();
if (intent.hasExtra("audiourl")) {
raiseThreadPriority();
processHasStarted = true;
processHasPaused = false;
audiourl = intent.getStringExtra("audiourl");
station = intent.getStringExtra("station");
downloadingMediaFile = new File(context.getCacheDir(), DOWNFILE+ counter);
downloadingMediaFile.deleteOnExit();
Runnable r = new Runnable() {
public void run() {
try {
startStreaming(audiourl);
} catch (IOException e) {
// Log.d(TAG, e.toString());
}
}
};
Thread t = new Thread(r);
t.start();
}
}
#Override
public void onDestroy() {
super.onDestroy();
mp1.stop();
mp2.stop();
}
#Override
public IBinder onBind(Intent intent) {
startingIntent = intent;
context = this;
return ourBinder;
}
#Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
stopSelf();
return true;
}
/**
* Progressivly download the media to a temporary location and update the
* MediaPlayer as new content becomes available.
*/
public void startStreaming(final String mediaUrl) throws IOException {
try {
url = new URL(mediaUrl);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setReadTimeout(1000 * 20);
urlConn.setConnectTimeout(1000 * 5);
//The getContentType method is used by the getContent method to determine the type of the remote object; subclasses may find it convenient to override the getContentType method.
String ctype = urlConn.getContentType();
if (ctype == null) {
ctype = "";
} else {
ctype = ctype.toLowerCase();
}
if (ctype.contains(AUDIO_MPEG) || ctype.equals("")) {
String temp = urlConn.getHeaderField(BITERATE_HEADER);
if (temp != null) {
bitrate = new Integer(temp).intValue();
}
} else {
stopSelf();
return;
}
}
catch(NullPointerException ne)
{
}
catch (IOException ioe) {
// Log.e(TAG, "Could not connect to " + mediaUrl);
stopSelf();
return;
}
if (!regularStream) {
INTIAL_KB_BUFFER = bitrate * SECONDS / BIT;
Runnable r = new Runnable() {
public void run() {
try {
downloadAudioIncrement(mediaUrl);
Log.i("TAG12344444", "Unable to play");
stopSelf();
return;
} catch (IOException e) {
Log.i("TAG123", "Unable to initialize the MediaPlayer for Audio Url = "+mediaUrl, e);
stopSelf();
return;
} catch (NullPointerException e) {
stopSelf();
return;
}
}
};
Thread t = new Thread(r);
t.start();
}
}
/**
* Download the url stream to a temporary location and then call the
* setDataSource for that local file
*/
public void downloadAudioIncrement(String mediaUrl) throws IOException{
int bufsizeForDownload = 8 * 1024;
int bufsizeForfile = 64 * 1024;
stream = new BufferedInputStream(urlConn.getInputStream(),bufsizeForDownload);
Log.i("bufsize",Integer.toString(urlConn.getInputStream().available()));
try{
if(stream == null || stream.available() == 0){
stopSelf();
Log.i("unable to create ","stream null");
return;
}
}catch (NullPointerException e) {
stopSelf();
Log.i("return1","return1");
return;
}
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(downloadingMediaFile), bufsizeForfile);
byte buf[] = new byte[bufsizeForDownload];
int totalBytesRead = 0, totalKbRead = 0, numread = 0;
do {
if (bout == null) {
counter++;
downloadingMediaFile = new File(context.getCacheDir(), DOWNFILE+ counter);
downloadingMediaFile.deleteOnExit();
bout = new BufferedOutputStream(new FileOutputStream(downloadingMediaFile), bufsizeForfile);
}
try {
numread = stream.read(buf);
} catch (IOException e) {
Log.d("Downloadingfile", "Bad read. Let's quit.");
// stop();
Log.i("return2","return2");
stopSelf();
// return;
}
catch (NullPointerException e) {
// Let's get out of here
e.printStackTrace();
break;
}
if (numread < 0) {
bout.flush();
stopSelf();
Log.i("Bad read from stream", "Bad read from stream3");
if(stream == null){
urlConn = new URL(mediaUrl).openConnection();
urlConn.setConnectTimeout(1000 * 30);
urlConn.connect();
stream = new BufferedInputStream(urlConn.getInputStream(),bufsizeForDownload);
}else{
handler.post(new Runnable() {
public void run() {
Log.i("Bad read from stream", "Bad read from xyz");
context.stopService(startingIntent);
Log.i("return3","return3");
return;
}
});
}
} else if (numread >= 1) {
bout.write(buf, 0, numread);
totalBytesRead += numread;
totalKbRead += totalBytesRead / 1000;
}
if (totalKbRead >= INTIAL_KB_BUFFER && stopping != true) {
bout.flush();
bout.close();
bout = null;
if (started == false) {
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
}
totalBytesRead = 0;
totalKbRead = 0;
}
if (stopping == true) {
stream = null;
}
} while (stream != null);
}
/** oncompletelister for media player **/
class listener implements MediaPlayer.OnCompletionListener {
public void onCompletion(MediaPlayer mp) {
waitingForPlayer = false;
long timeInMilli = Calendar.getInstance().getTime().getTime();
long timeToQuit = (1000 * 30) + timeInMilli; // add 30 seconds
if (mp1playing)
{
mp1.reset();
removefile();
mp1prepared = false;
// Log.d(TAG, "mp1 is Free.");
if (downloadingformp2) {
if (mp2preparing && stopping == false) {
waitingForPlayer = true;
}
while (mp2preparing && stopping == false) {
if (timeInMilli > timeToQuit) {
stopSelf();
}
timeInMilli = Calendar.getInstance().getTime().getTime();
}
}
} else {
mp2.reset();
removefile();
mp2prepared = false;
if (downloadingformp1) {
if (mp1preparing && stopping == false) {
waitingForPlayer = true;
}
while (mp1preparing && stopping == false) {
if (timeInMilli > timeToQuit) {
stopSelf();
}
timeInMilli = Calendar.getInstance().getTime().getTime();
}
}
}
if (waitingForPlayer == true) {
// we must have been waiting
waitingForPlayer = false;
}
if (stopping == false) {
if (mp1playing) {
mp2.start();
mp1playing = false;
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
} else {
mp1.start();
mp1playing = true;
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
}
}
}
}
/** OnPreparedListener for media player **/
class preparelistener implements MediaPlayer.OnPreparedListener {
public void onPrepared(MediaPlayer mp) {
if (prepareState) {
prepareState = false;
mp1preparing = false;
mp1prepared = true;
if (started == false) {
started = true;
mp1.start();
mp1playing = true;
Runnable r = new Runnable() {
public void run() {
setupplayer();
}
};
Thread t = new Thread(r);
t.start();
}
} else {
prepareState = true;
mp2preparing = false;
mp2prepared = true;
}
}
};
/**
* Set Up player(s)
*/
public void setupplayer() {
final String TAG = "setupplayer";
Runnable r = new Runnable() {
public void run() {
try {
if (!mp1preparing && !mp1prepared) {
while (true) {
downloadingformp1 = true;
if (started == false)
break;
if (counter > preparecounter)
break;
}
File f = new File(context.getCacheDir(), DOWNFILE+ preparecounter);
FileInputStream ins = new FileInputStream(f);
mp1.setDataSource(ins.getFD());
mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);//playing for live streaming
mp1.setOnCompletionListener(new listener());
mp1.setOnPreparedListener(new preparelistener());
if (started == false || waitingForPlayer == true){
}
mp1.prepareAsync();// .prepare();
mp1preparing = true;
downloadingformp1 = false;
preparecounter++;
} else if (!mp2preparing && !mp2prepared) {
while (true) {
downloadingformp2 = true;
if (started == false)
break;
if (counter > preparecounter)
break;
}
File f = new File(context.getCacheDir(), DOWNFILE+ preparecounter);
FileInputStream ins = new FileInputStream(f);
mp2.setDataSource(ins.getFD());
mp2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp2.setOnCompletionListener(new listener());
mp2.setOnPreparedListener(new preparelistener());
mp2.prepareAsync();
mp2preparing = true;
downloadingformp2 = false;
preparecounter++;
// }
} else
Log.d(TAG, "No Media player is available to setup.");
return;
} catch (FileNotFoundException e) {
Log.e(TAG, e.toString());
Log.e(TAG,"Can't find file. Android must have deleted it on a clean up ");
stop();
return;
} catch (IllegalStateException e) {
Log.e(TAG, e.toString());
stop();
} catch (IOException e) {
Log.e(TAG, e.toString());
stop();
}
}
};
preparringthread = new Thread(r);
preparringthread.start();
try {
preparringthread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void removefile() {
File temp = new File(context.getCacheDir(), DOWNFILE + playedcounter);
temp.delete();
playedcounter++;
}
public boolean stop() {
final String TAG = "STOP";
stopping = true;
try {
if (mp1.isPlaying()){
if (!(stream == null)) {
Log.i("IN STOP", "MP1 is nill");
stopSelf();
}
mp1.stop();
}
if (mp2.isPlaying()){
Log.i("IN STOP", "MP2 is nill");
if (!(stream == null)){
stopSelf();
}
mp2.stop();
}
} catch (Exception e) {
Log.e(TAG, "error stopping players");
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e(TAG, "error closing open connection");
}
}
stream = null;
processHasStarted = false;
processHasPaused = true;
if (preparringthread != null) {
preparringthread.interrupt();
}
stopSelf();
return true;
}
public boolean isPlaying() {
return processHasStarted;
}
public boolean isPause() {
return processHasPaused;
}
private void raiseThreadPriority() {
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
}
}
you should call release(), to free the resources. If not released, too many MediaPlayer instances may result in an exception
Write this code when on youe Service
Updated
private void releaseMediaPlayer() {
if (mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
You can see this

Testing class with input-output stream and Handler in android

I have this code and i would like to test if i will set up Handler and called method run with outputstream and inputstream that this class is good working. And i mean by it that i will recieved something on input stream then change it to something else and send it on output stream and then check if message send by Handler is right. How can i do it or can i mock output-input stream and handler?
TestClass that i would like to test.
import android.os.Handler;
import android.util.Log;
public class TestClass {
protected String description;
protected String responce;
protected String valueResponce;
protected int done;
protected Handler listener;
protected int identifier;
protected int target;
public static final int STATE_GOOD = 0;
public static final int STATE_FAILED = 1;
public static final int STATE_ATDPN = 2;
public void addListener(Handler listener) {
this.listener = listener;
}
protected void preparation() {
identifier = Integer.parseInt(this.getRequest(), 16);
target = HandlerLabels.MESSAGE_DATA;
}
protected void send(OutputStream outStream) {
String mes = this.getRequest() + '\r';
byte[] send = mes.getBytes();
try {
outStream.write(send);
} catch (IOException e) {
done = STATE_FAILED;
}
}
protected void read(InputStream inStream) {
try {
int data = inStream.read();
String output = "";
while (data != 62) {
if (data != 10) {
if (data != 13) {
output += (char) data;
}
}
data = inStream.read();
}
responce = output;
} catch (IOException e) {
done = STATE_FAILED;
}
}
protected void noticeListener() {
if (listener == null) {
Log.d(tag, "listener null");
} else {
listener.obtainMessage(target, identifier, -1, valueResponce)
.sendToTarget();
}
}
protected boolean control(String value){
if(value.length() == 0){
done = STATE_FAILED;
return false;
}
return true;
}
public int run(InputStream inStream, OutputStream outStream) {
preparation();
if (done == STATE_GOOD)
send(outStream);
if (done == STATE_GOOD)
read(inStream);
if (control(responce))
valueResponce = calculateValue(responce);
if (done == STATE_GOOD)
noticeListener();
return done;
}
protected String calculateValue(String value) {
String[] arr = value.split(" ");
int A = Integer.parseInt(arr[2], 16);
return String.valueOf(((A*100)/255));
}
public String getRequest() {
return "01041";
}
public String getDescription() {
return description;
}
public int isDone() {
return done;
}
public void setDone(int done) {
this.done = done;
}
public String getResponce() {
return responce;
}
public void setResponce(String responce) {
this.responce = responce;
}
}

Categories