File not found exception in Android for message toast - java

I am actually trying to search for given string in the text file which I have stored in the assets folder inside my Android application. The code that I have written is:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button;
final EditText obedittext;
button =(Button)findViewById(R.id.button1);
obedittext =(EditText)findViewById(R.id.editText1);
button.setOnClickListener(
new View.OnClickListener()
{
boolean textfound;
public void onClick(View view)
{
textfound = searchtext(obedittext.getText().toString());
if(textfound)
maketoast(obedittext.getText().toString());
else
maketoast("Unsuccessfull");
}
});
}
protected boolean searchtext(String string) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("mneumo.txt"));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.equals(string)) {
return true;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
finally{
}
return false;
}
private void maketoast(String string) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, string , Toast.LENGTH_SHORT);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
the error which I received was:
03-06 01:17:01.330: W/System.err(1170): java.io.FileNotFoundException: /mneumo.txt: open failed: ENOENT (No such file or directory)
03-06 01:17:01.330: W/System.err(1170): at libcore.io.IoBridge.open(IoBridge.java:409)
03-06 01:17:01.330: W/System.err(1170): at java.io.FileInputStream.<init>(FileInputStream.java:78)
03-06 01:17:01.340: W/System.err(1170): at java.io.FileInputStream.<init>(FileInputStream.java:105)
03-06 01:17:01.340: W/System.err(1170): at java.io.FileReader.<init>(FileReader.java:66)
03-06 01:17:01.340: W/System.err(1170): at com.example.demo.MainActivity.searchtext(MainActivity.java:60)
03-06 01:17:01.340: W/System.err(1170): at com.example.demo.MainActivity$1.onClick(MainActivity.java:41)
The sample file is,
SPINAL ANESTHESIA AGENTS
XYLOCAINE: WHERE NOT TO USE WITH EPINEPHRINE
GENERAL ANAESTHESIA: EQUIPMENT CHECK PRIOR TO INDUCING
If the string is found, it is supposed to show a toast with that string. But it always says "file not found". And I am total newbie.
This is for an app that is similar to a dictionary.
I did refer to other questions in this site but I still can't figure out what the problem is. Should I use assetmanager or something else?

Your code statement
br = new BufferedReader(new FileReader("mneumo.txt"));
refers to the wrong location. Hence, it can't read the file. Instead, replace your above line by following
br = new BufferedReader(new InputStreamReader(getAssets().open("mneumo.txt")));
This way, your file should be found and opened. Files stored in the app's asset folder should always read that way and not via hard-coded directory strings or app-relative paths.

You want to read from assets, right? You need to use AssetManager to pull that off. See below:
InputStream is;
try {
is = getAssets().open("myfile.txt");
byte[] buffer = new byte[is.available()];
is.read(buffer);
is.close();
Toast.makeText(this, new String(buffer, "UTF-8"), Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
}

Related

Getting android view for static class

Ive been trying to get a class in my android app to be able to post snackbars. The class is a manager for a bluetooth connection, and ive needed to make it static in my main activity to achieve this. For this reason i cant send android context classes to it or store within in, making me unable to get the view needed to make a snackbar. All throughout the bluetooth service class i use the method runOnUiThread(() -> snackbarMsg to try to show snackbars. It used to work when i sent view as a parameter of the constructor, but only for the first time the main screen showed, if i switched activity and back it would stop working, and this also caused a memory leak. Any other way to solve this? Any help is appreciated.
Currently code looks like this in main activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Initialise some static variables needed across the whole program
private static BluetoothService bluetoothService;
private static final String TAG = MainActivity.class.getSimpleName();
protected static ArrayList<LocationData> locations = new ArrayList<>();
protected static List<String> categories = new ArrayList<>();
Spinner spinner;
private static boolean doneFirstRun = false;
protected static LocationData selectedLocation = new LocationData();
MainActivity instance = this;
public MainActivity() {
}
/*
TODO: view in bluetooth service causes memory leak
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
if (!doneFirstRun){
//Getting storage
readFromFile(MainActivity.this);
//adding example location
if (locations.size()==0){
LocationData spaceRay = new LocationData();
spaceRay.setName("SpaceRay");
spaceRay.setLatitude(59.40384);
spaceRay.setLongitude(17.95228);
spaceRay.setInclination(-85);
spaceRay.setDirection(200);
spaceRay.setAltitude(99990);
locations.add(spaceRay);
}
//Checking and asking for relevant permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
#SuppressLint("InlinedApi") String[] permissions = {Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN};
ActivityCompat.requestPermissions(instance, permissions, 1);
}
bluetoothService = new BluetoothService();
//starting bluetooth networking activity on new thread
startBluetoothService();
doneFirstRun = true;
}
} catch (Exception exception){
Log.e(TAG, "Failed to do first run through of code: ", exception);
}
...
protected void startBluetoothService(){
try {
Log.i(TAG, "New thread started");
bluetoothService.run(MainActivity.this);
} catch (Exception e) {
Log.e(TAG, "Bluetooth service failed: ", e);
snackbarMsg("Bluetooth service failed");
}
}
and like this is bluetooth_service class:
public class BluetoothService extends AppCompatActivity{
private static final String TAG = BluetoothService.class.getSimpleName();
private OutputStream outputStream;
private InputStream inputStream;
private BluetoothSocket socket;
private boolean writing = false;
public BluetoothService(){
}//constructor
...
//method to show snackbar message at the bottom of the screen
public Runnable snackbarMsg (String msg){
try {
View view = findViewById(R.id.btn_connect);
Snackbar snackbar = Snackbar.make(view, msg, BaseTransientBottomBar.LENGTH_SHORT);
snackbar.show();
} catch (Exception exception){
Log.e(TAG, "Could not show snackbar", exception);
}
return null;
}
Error message looks like this:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:190)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:809)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:852)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:819)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:261)
at antennalocator.util.BluetoothService.snackbarMsg(BluetoothService.java:204)
at antennalocator.util.BluetoothService.lambda$write$4$antennalocator-util-BluetoothService(BluetoothService.java:159)
at antennalocator.util.BluetoothService$$ExternalSyntheticLambda5.run(Unknown Source:4)
at java.lang.Thread.run(Thread.java:1012)
Managed to get around this issue. The way i solved this was by sending the view as a parameter in each method that needed to post snackbars: for example the write method:
public void write(String s, View view) {
if (!writing){
new Thread(() -> {
try {
writing = true;
outputStream.write(s.getBytes());
runOnUiThread(snackbarMsg("Sent data", view));
lockout(3000);
writing = false;
} catch (Exception exception) {
writing = false;
Log.e(TAG, "Error occurred when sending data, restarting bluetooth service", exception);
runOnUiThread(() -> snackbarMsg("Could not send data, restarting bluetooth service", view));
disconnect();
}
}).start();
} else{
runOnUiThread(snackbarMsg("Please wait a bit before sending data", view));
}
}
in main:
bluetoothService.write(ConvertToString(selectedLocation), findViewById(R.id.btn_connect));

Recorder not working more than once (Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference)

I've looked around here but none of the solutions I've found work for me.
Basically, what I'm trying to do is start recording when the ImageButton is held down, stop recording when the ImageButton is released and be able to record again, this time, overwriting the old recording, without first closing the app. When I try to record more than once (hold down the ImageButton again), the app crashes and gives me a:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference
at com.myname.audiorecorder.MainActivity.startRecording(MainActivity.java:86)
at com.myname.audiorecorder.MainActivity$1.onTouch(MainActivity.java:61)
This is my code (Both errors have comments with **)
public class MainActivity extends Activity {
Button play;
private MediaRecorder myAudioRecorder;
private String outputFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.button3);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
// handles "record" and "stop"
ImageButton roundButton = (ImageButton) findViewById(R.id.fab_button);
roundButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event)
{
Vibrator vb = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
vb.vibrate(50);
Log.i("Touched", "Recording");
startRecording(); // ** ERROR (MainActivity.java:86)
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
stopRecording();
Log.i("Released", "Stopped");
vb.vibrate(50);
}
return false;
}
});
// play recording
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
playRecording();
}
});
}
// start recording voice
public void startRecording()
{
try {
myAudioRecorder.prepare(); // ** ERROR (MainActivity.java:61)
myAudioRecorder.start();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
// stop recording voice
public void stopRecording()
{
myAudioRecorder.stop();
myAudioRecorder.reset();
myAudioRecorder.release();
myAudioRecorder = null;
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
// play recorded voice
public void playRecording()
{
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
}
Any ideas as to what is going on? I've tried some solutions I saw here and a few I came up with on my own but nothing worked. Thank you very much.
EDIT
Here's the rest of the error in the logcat
at android.view.View.dispatchTouchEvent(View.java:8470)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2407)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2407)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2407)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2407)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2049)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2369)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1719)
at android.app.Activity.dispatchTouchEvent(Activity.java:2752)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2330)
at android.view.View.dispatchPointerEvent(View.java:8671)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4193)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4059)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3604)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3657)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3623)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3740)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3631)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3797)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3604)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3657)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3623)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3631)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3604)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5912)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5851)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5822)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6002)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:192)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:143)
at android.os.Looper.loop(Looper.java:122)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
You are initialising AudioRecorder in oncreate. This means Instance will be created when you open that activity. So better is Initialize AudioRecorder on ClickListener, so when you click on ImageView each and every time new Instance will be created.
You should initialize AudioRecorder before calling startRecording() inside onTouch(), otherwise the second time you call it it will be null because your setting it to null after releasing it inside stopRecording();

java.net.UnknownHostException : api.openweathermap.org

I'm following a course on udacity 'Developing Android Apps'. Following is the code of ForecastFragment class which is suppose to get data in json format from the url(http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric).
public class ForecastFragment extends Fragment {
public ForecastFragment() {
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] data = {
"Today-Sunny-34", "Tommorow-Rainy-233", "Wednesday-Cloudy-21", "Thursday-Monayblue-18", "Frida-Rainy-23", "Saturday-Rainy-22", "Sunday-Strorm-100"
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
inflater.inflate(R.menu.forecastfragment, menu);
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id==R.id.action_refresh){
FetchWeatherTask fetch = new FetchWeatherTask();
fetch.execute();
return true;}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<Void,Void,Void>{
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) return null;
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG,"Forecast Json String" + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error", e);
return null;
} finally {
if (urlConnection != null) urlConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("placeholder fragment", "error closing stream", e);
}
}
}
return null;
}
}
}
However, I'm repeatedly getting this error.
07-20 12:49:14.063 2392-2486/com.example.android.sunshine.app E/FetchWeatherTask﹕ Error
java.net.UnknownHostException: api.openweathermap.org
at java.net.InetAddress.lookupHostByName(InetAddress.java:512)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:300)
at java.net.InetAddress.getAllByName(InetAddress.java:259)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:119)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1027)
Following are the things I've already checked:-
mobile phone has internet access.
AndroidManifest.xml declares the permission for internet usage.
The url works fine in the browser,but I'm clueless as to why this error is coming up.
Also, I'm running the app on my android phone(api 10).
If anyone could please provide a solution or point me in the right direction,it would be great. Thank you.
I had the same issue. Yet I did not turn WiFi on on my mobile phone. Activating wifi solved the problem for me.
I copied your Async class as-is and ran it in a new project on a KitKat VM on my Mac machine. Here are the results:
07-19 14:40:32.070 1670-1683/centerorbit.com.myapplication V/FetchWeatherTask﹕ Forecast Json String{"city":{"id":1273294,"name":"Delhi","coord":{"lon":77.216667,"lat":28.666668},"country":"IN","population":0},"cod":"200","message":0.0095,"cnt":7,"list":[{"dt":1437285600,"temp":{"day":29,"min":28.21,"max":29,"night":28.21,"eve":29,"morn":29},"pressure":984.15,"humidity":88,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"speed":1.66,"deg":64,"clouds":36},{"dt":1437372000,"temp":{"day":29.15,"min":25.17,"max":31.21,"night":27.92,"eve":31.21,"morn":26.55},"pressure":986.25,"humidity":95,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":3.22,"deg":86,"clouds":88,"rain":10.65},{"dt":1437458400,"temp":{"day":30.46,"min":25.15,"max":31.57,"night":27.94,"eve":31.1,"morn":25.15},"pressure":988.81,"humidity":83,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":6.41,"deg":111,"clouds":68,"rain":0.45},{"dt":1437544800,"temp":{"day":30.63,"min":26.12,"max":32.69,"night":28.12,"eve":32.69,"morn":26.12},"pressure":991.01,"humidity":81,"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"speed":3.57,"deg":118,"clouds":64},{"dt":1437631200,"temp":{"day":34.27,"min":25.81,"max":35.34,"night":27.1,"eve":33.11,"morn":25.81},"pressure":989.86,"humidity":78,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":2.06,"deg":74,"clouds":8,"rain":3.94},{"dt":1437717600,"temp":{"day":31.12,"min":25.71,"max":31.12,"night":26.68,"eve":30.83,"morn":25.71},"pressure":991.3,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.06,"deg":184,"clouds":13,"rain":7.82},{"dt":1437804000,"temp":{"day":31.68,"min":25.88,"max":32.17,"night":27.01,"eve":32.17,"morn":25.88},"pressure":989.57,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.28,"deg":226,"clouds":52,"rain":5.89}]}
It appears that your code is fine, and something is not right with your system/network. I would recommend restarting your phone/computer to see if that fixes the issue. If not, try using a different network (disconnect from your home WiFi and use Cell network).
You have registered permission in androidManifest to access Internet
<uses-permission android:name="android.permission.INTERNET"/>
Append APIKey at the end of URL
To get APIKey you have to create acount on openweathermap.org
e.g. http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric&appid=yourapiid"
Detail Process to Get APIKey is

How can I determine which app was used, whilst pasting to the Android clipboard?

I have produced the below android code to attain code pasted to the Android clipboard. And although it works, I would like to determine which android application was being utilized whilst this data was pasted to the clipboard.
How can I accomplish this?
Android Code:
#SuppressLint("NewApi")
public String readFromClipboard(Context context) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(context.CLIPBOARD_SERVICE);
return clipboard.getText().toString();
} else {
ClipboardManager clipboard = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
// Gets a content resolver instance
ContentResolver cr = context.getContentResolver();
// Gets the clipboard data from the clipboard
ClipData clip = clipboard.getPrimaryClip();
if (clip != null) {
String text = null;
String title = null;
// Gets the first item from the clipboard data
ClipData.Item item = clip.getItemAt(0);
// Tries to get the item's contents as a URI pointing to a note
Uri uri = item.getUri();
// If the contents of the clipboard wasn't a reference to a
// note, then
// this converts whatever it is to text.
if (text == null) {
text = coerceToText(context, item).toString();
}
return text;
}
}
return "";
}
#SuppressLint("NewApi")
public CharSequence coerceToText(Context context, ClipData.Item item) {
// If this Item has an explicit textual value, simply return that.
CharSequence text = item.getText();
if (text != null) {
return text;
}
// If this Item has a URI value, try using that.
Uri uri = item.getUri();
if (uri != null) {
// First see if the URI can be opened as a plain text stream
// (of any sub-type). If so, this is the best textual
// representation for it.
FileInputStream stream = null;
try {
// Ask for a stream of the desired type.
AssetFileDescriptor descr = context.getContentResolver()
.openTypedAssetFileDescriptor(uri, "text/*", null);
stream = descr.createInputStream();
InputStreamReader reader = new InputStreamReader(stream,
"UTF-8");
// Got it... copy the stream into a local string and return it.
StringBuilder builder = new StringBuilder(128);
char[] buffer = new char[8192];
int len;
while ((len = reader.read(buffer)) > 0) {
builder.append(buffer, 0, len);
}
return builder.toString();
} catch (FileNotFoundException e) {
// Unable to open content URI as text... not really an
// error, just something to ignore.
} catch (IOException e) {
// Something bad has happened.
Log.w("ClippedData", "Failure loading text", e);
return e.toString();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
// If we couldn't open the URI as a stream, then the URI itself
// probably serves fairly well as a textual representation.
return uri.toString();
}
To be clear, I don't want to have to have a service running whilst this data is first pasted instead I'd like to determine the origin of the pasting after the fact.

Download Manager Unable to Resume Download in case of Internet Disconnection and System Reboot

I have created a simple application which is supposed to download large zip files. After some R&D I came to the conclusion that I have to use Download Manager to achieve this. I want the download to resume automatically if the device is restarted or in case of unstable internet connectivity. Right now, the code is able to download large files as expected, but in case of internet connectivity fluctuations or system restart, it stops downloading.
The activity:
public class MainActivity extends ActionBarActivity {
String Download_path = "http://wickedbrains.com/map/mumbai.zip";
String Download_ID = "DOWNLOAD_ID";
SharedPreferences preferenceManager;
DownloadManager downloadManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Button btnDownload = (Button)findViewById(R.id.download);
btnDownload.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// Locate storage location
String filepath = "";
File folder = new File(
Environment.getExternalStorageDirectory() + "/osmdroid");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
filepath = Environment.getExternalStorageDirectory()
.getPath() + "/osmdroid";
// Deleting if zip file exists
File folder2 = Environment.getExternalStorageDirectory();
String fileName = folder2.getPath() + "/osmdroid/mumbai.zip";
File myFile = new File(fileName);
if(myFile.exists())
myFile.delete();
}
//Starting download manager to download file
Uri Download_Uri = Uri.parse(Download_path);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
long download_id = downloadManager.enqueue(request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Test")
.setDescription("Map Download")
.setDestinationInExternalPublicDir("/osmdroid","mumbai.zip"));
// long download_id = downloadManager.enqueue(request);
//Save the download id
Editor PrefEdit = preferenceManager.edit();
PrefEdit.putLong(Download_ID, download_id);
PrefEdit.commit();
}});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(downloadReceiver);
}
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(preferenceManager.getLong(Download_ID, 0));
Cursor cursor = downloadManager.query(query);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
int reason = cursor.getInt(columnReason);
if(status == DownloadManager.STATUS_SUCCESSFUL){
//Retrieve the saved download id
long downloadID = preferenceManager.getLong(Download_ID, 0);
ParcelFileDescriptor file;
try {
file = downloadManager.openDownloadedFile(downloadID);
Toast.makeText(MainActivity.this,
"File Downloaded: " + file.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this,
e.toString(),
Toast.LENGTH_LONG).show();
}
}else if(status == DownloadManager.STATUS_FAILED){
Toast.makeText(MainActivity.this,
"FAILED!\n" + "reason of " + reason,
Toast.LENGTH_LONG).show();
}else if(status == DownloadManager.STATUS_PAUSED){
Toast.makeText(MainActivity.this,
"PAUSED!\n" + "reason of " + reason,
Toast.LENGTH_LONG).show();
}else if(status == DownloadManager.STATUS_PENDING){
Toast.makeText(MainActivity.this,
"PENDING!",
Toast.LENGTH_LONG).show();
}else if(status == DownloadManager.STATUS_RUNNING){
Toast.makeText(MainActivity.this,
"RUNNING!",
Toast.LENGTH_LONG).show();
}
}
}
};
}
Where am I going wrong? What should I do to enable the resume capability of the download?
Quoting from docs,
The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.
I guess Download Manager, by default takes cares of retries.
If you are having issues you can use DownloadManager.Query class and query for COLUMN_STATUS and COLUMN_REASON to get the download status
Edit:
Starting a download
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request( YOUR_DOWNLOAD_URL );
long enqueue = dm.enqueue(request);
enqueue is more like a download reqeust id. You can use that enqueue to fetch the download progress/status
Querying the download Status
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int downloadStatus = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (DownloadManager.STATUS_SUCCESSFUL == downloadStatus) {
// download succeded
} else if (DownloadManager.STATUS_FAILED == downloadStatus){
String failedReason = c.getString(c.getColumnIndex(DownloadManager.COLUMN_REASON));
// handle failures
}
}
Haven't tested the code myself. But it should work.
I confirm that this problem still exists in 2020, when testing in an emulator and having WiFi enabled, this error consistently appears (even with Android 10).
Switching off WiFi in the emulator seems to solve the problem.
Try to get the reason for the failed download.
e.g does it work on network switch wifi->data
(If your error reason is 1008- there seems to be a reported bug here
https://code.google.com/p/android/issues/detail?id=18462,
further:
http://papaya-backend.net/2013/04/12/why-http-etag-header-may-cause-your-downloading-apps-on-android-failed/)

Categories