Im getting E/AndroidRuntime: FATAL EXCEPTION: main at com.test.megatest.Main4Activity$1.onClick(Main4Activity.java:37).
Ive read tons of posts on this forum but I cant figure out what Im missing,
This is the Main4Activity.java:
package com.test.megatest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main4Activity extends AppCompatActivity {
EditText inputText;
TextView response;
Button saveButton, readButton;
private String filename = "SampleFile.txt";
private String filepath ="MyFileStorage";
File myExternalFile;
String myData ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
inputText = (EditText) findViewById(R.id.myInputText);
response = (TextView) findViewById(R.id.response);
saveButton =(Button) findViewById(R.id.saveExternalStorage);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile); //LINE 37
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText("");
response.setText("SampleFile.txt saved to somewhere..");
}
});
}
}
Can someone here just point me in the right direction? :)
The file you try to open an output stream for is NULL.
You declared it as a member but never initialized it.
Initialize file as
File myExternalFile=new File("SampleFile.txt");
Your Main4Activity has a "File" variable:
File myExternalFile;
But without assigning any object/value to that variable You are trying to use it in:
FileOutputStream fos = new FileOutputStream(myExternalFile);
Obviously you will get an Exception for that :P
You should initialise "myExternalFile" using any of the 4 public constructors specified at java.io.File (depending on your use case).
For example:
// If you need a "Persistent" file in private directory of your application
//
myExternalFile = new File(this.getFilesDir() ,"name_of_your_file.txt");
//
// or
// If you need a "Cache" file
myExternalFile = new File(this.getCacheDir() ,"name_of_your_file.txt");
Locations of above files on your Android filesystem is:
# Persistent: /data/data/com.test.megatest/files or
(Any File Manager App) /Android/data/com.test.megatest/files
# Cache: /data/data/com.test.megatest/cache or
(Any File Manager App) /Android/data/com.test.megatest/files
Reference:
1) java.io.FileOutputStream -> FileOutputStream (File file) public constructor
"Creates a file output stream to write to the file represented by the specified File object"
Related
I'm trying to get some data from Word Readable Shared Preferences of another application.
I'm sure that other application Shared Preferences is World Readable and name is present.
But I'm retrieving empty string.
Here is my code:
package com.example.sharedpref;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.content.SharedPreferences;
public class MainActivity extends AppCompatActivity {
private TextView appContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContent = (TextView) findViewById(R.id.test1);
appContent.setText("Test Application\n");
appContent.setText(getName(this));
}
protected String getName(Context context){
Context packageContext = null;
try {
packageContext = context.createPackageContext("com.application", CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = packageContext.getSharedPreferences("name_conf", 0);
String name = sharedPreferences.getString("name", "");
return name; //HERE IS WHERE I PUT BREAKPOINT
}
catch (PackageManager.NameNotFoundException e) {
return null;
}
}
}
Here is some debug I retrieve from debug mode:
and piece of code from the app that I'm trying to access shared preferences:
/* access modifiers changed from: protected */
#SuppressLint({"WorldReadableFiles"})
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_welcome);
Editor edit = getApplicationContext().getSharedPreferences("name_conf", 0).edit();
edit.putBoolean("FIRSTRUN", false);
edit.putString("name", "Eddie");
edit.commit();
new DBHelper(this).getReadableDatabase();
PS. I Cant edit code of second app im trying access to!
Something im missing?
You can not edit it from another apps,
if you want, you can use FileWriter to create a txt file and use it in other apps
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to build a simple app for Android can't figure out why my app keeps crashing I have traced it down to this line of code
<code>WG.setRandomWord(words.get(rand.nextInt(words.size())));</code>
I have check my logcat and it showing that my word file is not even being detected com.sagproductions.gamertaggenerator W/System.err: java.io.FileNotFoundException: words.txt: open failed: ENOENT (No such file or directory) but I have my file word file in the document structure.
for more context here is my code:
JAVA wordGenerator
package com.sagproductions.gamertaggenerator;
public class WordGenerator {
private String mRandomWord;
private int mRandomNum;
public WordGenerator(String randomWord, int randomNum){
mRandomNum=randomNum;
mRandomWord=randomWord;
}
public int getRandomNum(){
return mRandomNum;
}
public void setRandomNum(int randomNum){
mRandomNum=randomNum;
}
public String getRandomWord(){
return mRandomWord;
}
public void setRandomWord(String randomWord){
mRandomWord=randomWord;
}
}
Java MainActivity
package com.sagproductions.gamertaggenerator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.lang.String;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
WordGenerator WG;
private Button mSingleWordGenerator;
private Button mTwoWordGenerator;
private Button mThreeWordGenerator;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSingleWordGenerator = (Button)findViewById(R.id.button);
mSingleWordGenerator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generateWord();
editText=(EditText)findViewById(R.id.editText);
editText.setText(WG.getRandomWord(),TextView.BufferType.EDITABLE);
}
});
mTwoWordGenerator = (Button)findViewById(R.id.button2);
mTwoWordGenerator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mThreeWordGenerator = (Button)findViewById(R.id.button3);
mThreeWordGenerator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void generateWord(){
final File file = new File("words.txt");
ArrayList<String> words= new ArrayList<String>();
Random rand=new Random();
try(final Scanner scanner=new Scanner(file)){
while(scanner.hasNextLine()){
String line = scanner.nextLine();
words.add(line);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}
WG.setRandomWord(words.get(rand.nextInt(words.size())));
}
}
The WG field is never initialized, so it's null. So you're probably getting a NullPointerException when you call that method. You should initialize it somewhere, perhaps when you declare it (so WordGenerator WG; would be replaced by something like WordGenerator WG = new WordGenerator(INITIAL_RANDOM_WORD, INITIAL_RANDOM_VALUE);, where INITIAL_RANDOM_WORD and INITIAL_RANDOM_VALUE are some values you define elsewhere).
Edit: It seems that that line is causing the problem because words.size() is 0, which is because of the FileNotFoundException. The correct way to read that file will depend on where you're putting it. See the answers to this question (and the pages they link to) for different ways to correctly read text files in Android.
I've seen this question, it's not my case, since I don't have backslashes in my url,
I have simple URL like, https://url.com/login
My Code,
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
URL url = new URL("https://url.net/login/");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FloatingActionButton btn = (FloatingActionButton) findViewById(R.id.submitbtn);
EditText edtxt = (EditText) findViewById(R.id.usernm);
EditText edtxt2 = (EditText) findViewById(R.id.usrpwd);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(i);
}
});
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
}
}
Screen shot:
When I hover on new URL();, I get error as:
Unhandled Exception: java.net.MalformedURLException
That's why I'm getting another error at line,
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
in stack Trace I'm getting error as,
Error:(48, 13) error: cannot find symbol method readStream(InputStream)
When I hover on new URL();, I get error as:
The URL() constructor throws java.net.MalformedURLException. You need to wrap that constructor call in a try/catch block.
That's why I'm getting another error at line,
That is because getInputStream() also throws checked exceptions. You need to wrap that code in a try/catch block.
That's the line of error and I'm getting error as Error:(48, 13) error: cannot find symbol method readStream(InputStream)
That is because you did not implement a method named readStream() on this class.
All of this is covered in any decent book or course on Java programming.
Eventually, once you get past these compile errors, your code will crash at runtime with a NetworkOnMainThreadException, as you cannot perform network I/O on the main application thread. You will need to move this HTTP code to a background thread, either one that you create yourself or by using an HTTP client API that can handle it for you (e.g., OkHttp).
I was trying to set the default wallpaper by using a button but for some reason when i set the InputStream in the OnCreate Method, i get this error "expected resource of type raw". I am referencing the drawable folder and using the icon.png image which is in the drawable folder. I was following the tutorials in the NewBoston Series and it seems to work fine for Travis but for some reason mine doesnt work in Android Studio. What could be the error? Thanks
Camera.java:
package com.example.user.cameraapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by user on 16-08-2015.
*/
public class Camera extends Activity implements View.OnClickListener{
ImageView iv;
Button b1,b2;
ImageButton img;
Intent i;
final static int cameractivity = 0;
Bitmap b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
inititalize();
InputStream is = getResources().openRawResource(R.drawable.icon);
b = BitmapFactory.decodeStream(is);
}
private void inititalize() {
iv = (ImageView)findViewById(R.id.iView1);
img = (ImageButton)findViewById(R.id.imgbtn);
b1 = (Button)findViewById(R.id.btn1);
b2 = (Button)findViewById(R.id.btn2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn1:
try {
getApplicationContext().setWallpaper(b);
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.imgbtn:
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,cameractivity);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK)
{
Bundle extras = data.getExtras();
b = (Bitmap)extras.get("data");
iv.setImageBitmap(b);
}
}
}
Image:
The error occurred because Android Studio expected a resource file of type raw.
Solution 1:
Create a new folder in your "res" folder called "raw", and put your icon there. The raw folder should contain all your media files of your app.
Then replace
InputStream is = getResources().openRawResource(R.drawable.icon);
with
InputStream is = getResources().openRawResource(R.raw.icon);
Solution 2:
Another solution is to do it like this. This doesn't require you to create a raw folder:
InputStream is = getResources().openRawResource(+ R.drawable.icon);
Replace
InputStream is = getResources().openRawResource(R.drawable.icon);
With
InputStream is = getResources().openRawResource(+ R.drawable.icon);
Let's look at documentation for openRawResource
Open a data stream for reading a raw resource. This can only be used
with resources whose value is the name of an asset files -- that is,
it can be used to open drawable, sound, and raw resources; it will
fail on string and color resources.
So the solution - leave it as it is, i. e.
InputStream is = getResources().openRawResource(R.drawable.icon);
The inspection in Android Studio is just wrong. You can add
#SuppressWarnings("ResourceType")
to hide the error.
Note
Using + R.drawable.icon just fools the inspection, because it can no longer determine which kind of resource it is.
first I want to apologize for my bad english, I am from Slovakia ;)
So there is my problem
My friend wants to create a very simple translate aplication, very very very simple. We are beginners in programming for android and at all in java. The problem is, that our apk works great in Eclipse so we decided to create apk file and install it in our device. So when we installed it and there was a problem, our apk in device doesnt read file where are our words. So we tried it again in eclipse emulator and doesnt work too, but before creating apk it was fully working. Our file is in res/raw/dictionary
Here is our code
package com.example.dictionary;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView Vstup;
TextView Vystup;
Button presun;
String slovo;
String word;
String found;
Boolean click;
int i;
int j;
String sub;
String strf;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vstup = (TextView)findViewById(R.id.editText1);
Vystup = (TextView)findViewById(R.id.textView2);
presun = (Button)findViewById(R.id.button1);
presun.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
slovo = Vstup.getText().toString();
InputStream is = getResources().openRawResource(R.raw.dictionary);
InputStreamReader inputStreamReader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
while((strf = bufferedReader.readLine()) != null)
{
i = strf.indexOf(":"); // vrati prvu poziciu retazca
j = strf.indexOf(",");
sub = strf.substring(0,i); //vyberie zo stringu podretazec od indexu 0 po i
if(slovo.equals(sub))
{
found = strf.substring(i+1,j);
word = ("Výstup: " + found);
Vystup.setText(word.toString());
}
else {
word = ("Výstup: Word not found");
Vystup.setText(word.toString());
}
}
bufferedReader.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
});
}
#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;
}
}
error logcat
error opening trace file: no such file or directory(2)
getResources().openRawResource() gets an InputStream for a file in the res/raw/ directory of your Android project. The argument to openRawResource() is an int named R.raw.filename where filename is the name of the file without the extension.
So, the file won't be in the res/assets/ directory.
Although you can doublecheck that the file you're trying to read is actually in res/raw, it seems odd to me that you could build the APK and get an R.raw.filename entry if the file wasn't actually there. I'd use a debugger to step through the code and check the variables.