Android, string resource not found - android

I'm working on an App, and I am getting weired errors. I put in some String resource in res/values/strings and saved it. Now If I want to access it in an Activity I get an error like this
07-13 11:16:20.050: ERROR/AndroidRuntime(5883): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f060006
And I can't figure out why.
Resource looks like this:
<string name="dialog_download_text">please wait while downloading</string>
and I want to Access it like
public void onCreate(Bundle b){
super.onCreate(b);
String s = getResources().getString(R.string.dialog_download_text);
}
I also looked into R.java and found my Entry
public static final class string {
public static final int dialog_download_cancel=0x7f060005;
public static final int dialog_download_text=0x7f060007;
public static final int dialog_download_title=0x7f060006;
}
I don't know what to do, because I never had a problem like this before.
Please help me. Thanks all.

Sometimes I get this error (once every 2 days), and it's because eclipse is not compiling the new code and it's deploying the old apk.
I fix this by
doing a clean on eclipse (Project -> clean)
closing the emulator
restarting the adb server by running adb kill-server and adb start-server from the command line

Most likely there's an extra import android.R; Then your string can't be found there. Otherwise, clean the project and rebuild it, try again, then report back.

what i had was
import android.R;
instead of
import com.example.project.R;
android.R does not have your resources it only has the general android resources.

Checkout this thread, it fixed my problem.
R cannot be resolved - Android error

Clean the project in eclipse, and try running.If this doesn't resolve your issue, from a already running emulator uninstall the app, and run it again from eclispe.

I am currently writing the "net.superlinux.tcltktutorials" you can find it on play store now.
now in the application, I want to use the standard way of using locales instead of my way of doing locales. I had to add for Arabic /res/vlaues-ar and I have the default for English /res/values.
The app is about ad based YouTube Playlist TCL/Tk programming language tutorials. now the playlist can be in Arabic and in English. What I noticed is that if you have in the default /res/values 36 entries and in /res/values-ar 35 entries for the same playlist, this will make the ResourceNotFound exception. All you have to do is add the missing entry as empty at the bottom of your list just to make it equal in numbers in English and Arabic, Even if the English playlist is less in numbers.
This was my method of adding to the playlist formed inside the list activity, and also a clever way of using the resources as xml built in data:
package net.superlinux.tcltktutorials;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListOfVideos extends ListActivity {
List<String> model = new ArrayList<String>();
ArrayAdapter<String> adapter = null;
List<String> filename = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
adapter = new ArrayAdapter<String> (this, R.layout.list_item, model);
load_playlist();
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String selected_youtube_video=filename.get(position);
try {Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+selected_youtube_video));
startActivity(i);
}
catch(Exception e){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v="+selected_youtube_video+"&loop=1&autoplay=1")));
e.printStackTrace();
}
}
void load_playlist()
{
int display_id=0;
int file_id=0;
//loop forever until nothing has to be added to the ListView or stop if the list item
// to be added does not exist.
for (int i=0;;i++){
display_id=getResources().getIdentifier("display_"+i, "string", getPackageName());
if (display_id!=0 && getString(display_id).length()!=0)
adapter.add(getString(display_id));
else {
Log.e("string id not found or empty","R.string.display_"+i );
return;
}
file_id=getResources().getIdentifier("file_"+i, "string", getPackageName());
if (file_id!=0 && getString(file_id).length()!=0){
filename.add(getString(file_id));
}
else {
Log.e("string id not found or empty","R.string.file_"+i );
return;
}
}
}
}

I also met this problem and it is very wired at first.
1: I make sure I import the correct R into my class
2: I checked R.java in the gen folder and the resource id is there.
3: I cleaned my project and remove from my phone and relaunch it
the exception still there.
Finally I found the reason:
I just added my resource string into the strings.xml in language-specific folder(say values-zh) but missed it in the default strings.xml in the default values folder.
then it is solved.

There are two cases you may get this error
1.your strings.xml file is not referred correctly?
Ans:give the correct package name for R.java file as per you application?
2.if you kept correct string.xlm path you may get still error?
Ans:once clean and build the projector restart the eclipse or android studio.
Thanks
krishh

For Kotlin use
this->context.resources.getString(R.string.your_string)

Related

Installation did not succeed. The application could not be installed [duplicate]

I was getting the message
> Installation failed with message Failed to establish session.
so following some responses to the problem I disabled Instant Run and I started getting
> Installation failed with message Error: android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space.
I´ve tried rebuilding, cleaning the project, to disable and enable Instant Run and to build APK but nothing solves the problem.
This is my build.gradle (Module:app).
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.gabriel.justmeet"
minSdkVersion 21
targetSdkVersion 28
versionCode 9
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
useLibrary 'org.apache.http.legacy'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.volley:volley:1.1.0'
}
and this is the build.gradle(Project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven { url 'http://repo1.maven.org/maven2' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'http://repo1.maven.org/maven2' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
This started when I modified my RegisterActivity, so it might help
package com.example.gabriel.paska;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
public static final String REGISTER_URL ="http://justmeet.000webhostapp.com/php/register.php";
public static final String KEY_USERNAME ="username";
public static final String KEY_PASSWORD="password";
public static final String KEY_NAME ="name";
public static final String KEY_AGE="age";
public static final String REGISTER_SUCCESS ="RegisterSuccess";
public static final String SHARED_PREF_NAME="tech";
public static final String USERNAME_SHARED_PREF="username";
public static final String LOGGEDIN_SHARED_PREF="loggedin";
private boolean loggedIn=false;
EditText etAge;
EditText etName;
EditText etPassword;
EditText etUsername;
Button bRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etAge = findViewById(R.id.etAgeR);
etName = findViewById(R.id.etNameR);
etPassword = findViewById(R.id.etPwordR);
etUsername = findViewById(R.id.etUsernameR);
bRegister = findViewById(R.id.btRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register();
}
});
}
private void register() {
final String name = etName.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
final String username = etUsername.getText().toString().trim();
final String age = etAge.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equalsIgnoreCase(REGISTER_SUCCESS)){
SharedPreferences sharedPreferences = RegisterActivity.this.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(LOGGEDIN_SHARED_PREF, true);
editor.putString(USERNAME_SHARED_PREF, name);
editor.apply();
Intent intent = new Intent(RegisterActivity.this, UserActivity.class);
startActivity(intent);
}else{
Toast.makeText(RegisterActivity.this, "Register Failed" + response.trim(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> prams = new HashMap<>();
prams.put(KEY_USERNAME, username);
prams.put(KEY_PASSWORD, password);
prams.put(KEY_NAME, name);
prams.put(KEY_AGE, age);
return prams;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_NAME,Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(LOGGEDIN_SHARED_PREF, false);
if(loggedIn){
Intent intent = new Intent(RegisterActivity.this, UserActivity.class);
startActivity(intent);
}
}
}
This issue is about your storage in the emulator. Default AndroidStudio value of 2Gb is not enough for modern Android versions.
Solution
Step 1: close the emulator.
Step 2: Wipe the emulator.
Step 3: change the internal storage and SD Card to 4098MB.
Step 4: Run the Emulator.
This is simply the virtual device running out of space. Each install on a virtual device uses up a bit of space each time you run your app. Over time the space fills up until it's all used up. You can increase the space as suggested by some answers - which will work initially but eventually that space will get used up too.
From the virtual device's Settings app you can view how much space you have left. Here you can see that almost a whole GB is used up, but the apps themselves only use 132MB, clearly something is off.
Go to the AVD Manager and in the Actions for your device there is the option to 'Wipe Data' - do that.
Heading back to the Settings app you can now see that the space is freed up and your app has room to be installed - till the next time it runs out at which point you just repeat this process.
that file-system has no space:
java.io.IOException: Requested internal only, but not enough space.
the issue is:
android:installLocation="internalOnly"
either remove it, or replace it with:
android:installLocation="preferExternal"
or make some space on the device / emulator by uninstalled or deleting something -
or simply assign some more megabytes to the virtual SD card.
If you are using phone this error comes due to less storage.
Make some space and try again it should work.
In Android Studio, open the AVD Manager and edit the problematic emulator. Inside the edit screen, you might need to click on 'Show Advanced Settings'. Scroll down and increase internal memory and SD card memory. After I did this I could install my app again.
The problem is with your storage space on your device which it is running. Try Installing Clearing the space or install it on an emulator.
Your app is trying to install on internal space of your virtual device, and it doesn't have enough space. If you run the emulator, go to config/storage and you'll see you have no space.
Sometimes, the emulator is created with 800Mb of internal space, and Android Oreo (for example) occupies all that space, and it is not possible to install anything.
Furthermore, even when you config your app to "prefer external", the app keep trying to install on internal storeage, so you can not solve the problem with that.
The only solution that worked for me was increasing the internal space of the emulator, you can do that by following one of these options:
A) Go to Android SDK -> ADV Manager, locate your emulator, edit preferences and increase the space, duplicate it, or what you want.
B) Go to the folder with the config of your emulator (In Windows C:/Users/your_user/.android/avd/your_emulator) and edit the *.ini files, you can see values related to space, memory, and so on, just increase that values and save.
Visual Studio 2017 has an aweful integration with Android SDK/ADV Manager, so you need to do this 100% manually, furthermore you don't receive any info or instructions when the error happens, so it's really annoying to fix it :( And it is always the same with the 99% of Xamarin problems!
it simply means the device that you wanna test the app or do debugging on does not have enough space. So clear off some memory, and then try again.
When running on emulator I found that even when I increased Internal disk space it didn't worked and stayed same size, I had to re-create emulator.
I uninstalled all the apps I ran and got installed on the virtual device and the error went away.
Create space on your phone or emulator and it should work.

Log.e not working even after android.util.Log is imported

Am a beginner I dont understand, Why its not working even i imported android.util.Log. I am using android studio.
package com.sai.myapplication;
import android.util.Log; // showing full gray
public class Fan {
protected String fanName;
protected boolean isOn;
public String getFanName() {
return this.fanName;
}
public void BreakFan(){
log.e(getFanName(),"BANg, CRASH!......OOPPs");// "log" is showing in red
}
}
Log 'L' show be Caps. Please check it. You are using wrong one.
Log.e(getFanName(),"BANg, CRASH!......OOPPs");// "log" is showing in red
Its Log not log(with capital L). If I am not wrong log was giving you compile time error. So please use Log as below.
Log.e(getFanName(),"BANg, CRASH!......OOPPs");

Import R (android)

I have a problem with my code which refuses to go away. This is the first half of my code:
public class SampleGame extends AndroidGame {
public static String map;
boolean firstTimeCreate = true;
#Override
public Screen getInitScreen() {
if (firstTimeCreate) {
Assets.load(this);
firstTimeCreate = false;
}
InputStream is = getResources().openRawResource(R.raw.map1);
map = convertStreamToString(is);
return new SplashLoadingScreen(this);
}
An error message is generated on the line
InputStream is = getResources().openRawResource(R.raw.map1)
The error message says I should add the line "import android.R", but when I do this, a second error message is generated which says "map1 cannot be resolved or is not a field." Can someone please give me any suggestions on how to solve this intractable problem?
Be sure that there is map1 in Raw folder.If it exists,then try clean/build your project or close and reopen eclipse.It may be solved.
Try updating your Eclipse android ADT to the latest, restart it.
Im not very good at android but if yours does have an onCreate some where make sure u reference your Resources after it has done the onCreate stuff.

Static Keyword , Reinstallation Required

In my application I have an Activity" Model" in which i get a value 'n' from an edit text , I have declared this value n as static int . So , that i can access it inside any class of the Application.
The problem is that when I restart my application without reinstalling it , the value of 'n' remains the same as it was in the first case . And this affects my output.
I cannot use intent to send values because , the value is accessed randomly in the application even in classes that are not activities.
Can u please tell , where I m wrong.??
package com.integrated.mpr;
import java.io.File;
import android.app.Activity;
import android.app.Dialog;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Model extends Activity implements OnClickListener{
EditText etPos;
Button bmodel;
static int n;//static variable to be used in other classes
File folder ;
File subfolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.inputpage);
etPos = (EditText) findViewById(R.id.etpos);
bmodel = (Button) findViewById(R.id.bModel);
bmodel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bModel:
String check = etPos.getText().toString();
String check1 = etNs.getText().toString();
n = Integer.parseInt(check);
Intent openAlternative = new Intent("com.integrated.mpr.ALTERNATIVE");
startActivity(openAlternative);
break;
}
}
}
If i first install my app , and enter value in the edittext as 2 , the value of n =2 ; If second time i run my app without installing it , even if i enter 3 in the edittext , value of n remains 2
Where is the twist??
Kumar,
The behavior you are seeing is the result of using a static member. static members do not require an instance and are therefore set upon first access (regardless of whether an instance was created or not) and stays in memory until Android decides it is no longer valid. In essence, it is doing exactly what it was supposed to. The proper use of static variables is a topic of extensive discussion among veteran and novice programmers alike, but essentially always leads to "be choosy about where and how you use static members".
That said, your need to access this from another component is a common problem, however, and there are a number of ways to solve it. If you need to have each instance have a different value, then it should not be static. Instead you will have to find a way to pass the instance of the Activity.
If each instance need not be different, but the value need to change according to some other parameter, simply find the appropriate place to change the value. If you can access it from anywhere in your application, you may also change it from anywhere in your application.
Solution 1: Passing by Intent
This solution is useful when the information is subject to change and must be sent to another component and the classes that it uses exlusively. You may pass virtually any value via an Intent extra.
openAlternative.putExtra("MyValue", Integer.parseInt(check));
In your responding component, you may retrieve the value by:
Intent myIntent = getIntent();
int n = myIntent.getIntExtra("MyValue", 0); //0 is the default if no value is sent.
From here, you may easily pass the retrieved value to any class being utilized by that component. An example:
MyClass.setN(n);
Solution 2: Storing outside of the LifeCycle
A safer alternative is to move the value to an extended Application. This is not subject to UI or LifeCycle processing.
public class MyApplication extends Application
{
static int n;
}
Adjust your AndroidManifest.xml...
<application android:name=".MyApplication" ... >
<!-- All of your components -->
</application>
Now, you can set the variable this way:
MyApplication.n = Integer.parseInt();
And you can get it by
int myN = MyApplication.n;
This solution has gotten me through many a troubled day. However, it should really be used for non-instance related data.
Solution 3: The REALLY UNSAFE method
This solution only works if you can guarantee a single instance of the component. This requires that singleTask is set. Be very careful with this
Change n to non-static
int n;
Change Activity to Singleton
static private Model myInstance;
In OnCreate, set myInstance
myInstance = this;
Create a getter:
static public Model getStaticInstance()
{
return myInstance;
}
This is unreliable (at best) and can cause huge memory leaks if not managed correctly.
Hope this helps,
FuzzicalLogic

Android Eclipse jUnit does not see superclass

This may be a simple answer.
1) Create a jar file with this code:
package com.myCompany.base;
public class Dex1 {
public String getTerm1() {
return "Term 1";
}
}
This is compiled to Dex1.jar using NetBeans.
2) Created a 'Hello world' android application in Eclipse. Add the code for Dex2 that extends Dex1. Copy and add Dex1.jar to the java build path.
package com.myCompany;
import com.myCompany.base.Dex1;
public class Dex2 extends Dex1 {
public String getTerm2() {
return getTerm1() + " Term 2";
}
}
in my onCreate() call:
editText.setText(dex2.getTerm2());
Everything works Great! I get the correct string displayed on the android screen. Yea!
Now the problem starts:
3) Create a jUnit 3 test case using Eclipse command File -> New -> Project -> Android Text Project command and add the code:
package com.myCompany.test;
import junit.framework.TestCase;
import com.myCompany.Dex2;
public class Dex2Test extends TestCase {
protected void setUp() throws Exception {
super.setUp();
dex2 = new Dex2();
}
protected void tearDown() throws Exception {
super.tearDown();
}
Dex2 dex2;
public void testGetTerm2() {
/*line 21 */ assertEquals("Term 1 Term 2", dex2.getTerm2());
}
public void testGetTerm1() {
/* line 25 */ assertEquals("Term 1", dex2.getTerm1());
}
}
On Line 25 the compiler gives a 'method undefined' error for getTerm1(). I don't understand why this is an error?
I tried to add the Dex1.jar to the java Build path of the test project, it compiles but we receive a run time error 'NoClassDefFoundError'. Yuch!
More Information 16Mar2012
I set this up using Plan Java classes, same jar file, to remove Android and it worked. This makes me conclude there must be some anomaly in Android/DalvikVM (aka DavrosVM).
More Information 16Mar2012 End
Am I missing something?
Is the jar file built incorrectly (didn't think that was possible)?
Am I importing the jar file incorrectly?
Is it just crazy to expect to import and override a class in a jar file?
Thank you for reading, please reply.
Fish
Take a look at Android Testing: External libraries which I guess have the solution to your problem.
What you may be doing wrong is not exporting your library in Order and Export under Java Build Path.

Categories

Resources