R library in Android error - java

I have been using this Android Guide
While it has been a pleasant experience so far, I am experiencing my first problem. I copied all the code from the source that is in the link, and pasted it to the project folder, replacing all old files. Before starting to understand what I had pasted, I thought it would be logical to run the code first to check for problems. The project wouldn't run because of an R object missing. After importing it (Eclipse's solution to the problem), more errors popped up. I tried searching for an answer, both on the Internet and in the book, but to no avail. Since my software is up to date, I doubt this is a problem on the software's side. And since the code is available online, I think the problem would have popped up and been fixed.
Thank you in advance for the help. For extra details please ask in the comments.
The code:
MainActivity.java
package com.dummies.android.silentmodetoggle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private AudioManager mAudioManager;
private boolean mPhoneIsSilent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
checkIfPhoneIsSilent();
setButtonClickListener();
Log.d("SilentModeApp", "This is a test");
}
private void setButtonClickListener() {
Button toggleButton = (Button)findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mPhoneIsSilent) {
// Change back to normal mode
mAudioManager
.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mPhoneIsSilent = false;
} else {
// Change to silent mode
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
mPhoneIsSilent = true;
}
// Now toggle the UI again
toggleUi();
}
});
}
/**
* Checks to see if the phone is currently in silent mode.
*/
private void checkIfPhoneIsSilent() {
int ringerMode = mAudioManager.getRingerMode();
if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
mPhoneIsSilent = true;
} else {
mPhoneIsSilent = false;
}
}
/**
* Toggles the UI images from silent
* to normal and vice versa.
*/
private void toggleUi() {
ImageView imageView =
(ImageView) findViewById(R.id.phone_icon);
Drawable newPhoneImage;
if (mPhoneIsSilent) {
newPhoneImage =
getResources().getDrawable(R.drawable.phone_silent);
} else {
newPhoneImage =
getResources().getDrawable(R.drawable.phone_on);
}
imageView.setImageDrawable(newPhoneImage);
}
#Override
protected void onResume() {
super.onResume();
checkIfPhoneIsSilent();
toggleUi();
};
}

Try cleaning your project, this will rebuild your R file. If there is still no R file in your file-tree then you may have an error in one your xml layout files. Eclipse may not tell you this so be vigilant and check through all the files in the /res folder. Also, never import R when this happens.

Did you check if there is a variable named action_settings in /res/values/string.xml if it does not exist please create one and then clean using projects -> clean makesure that build Automatically is checked

Related

.setText() being called but screen not updateing while in a while(true) loop

I've been running into this bug and I can't seem to figure out how to fix it as I'm fairly new to java and android development so I would really appreciate any help I could get with this!
The bug I'm running into is that when I'm using .setText() to update a TextView element periodically the text displayed on screen never actually changes.
I believe this is due to the while(true) loop in the startCrunching() method I'm using to run the main calculation process as before I start that method the screen updates fine with the test data I'm feeding it.
I also know that when the while loop starts the updateScreen() method is only being called from the while loop and not the repeating handler I have as the handler stops posting logs to the logcat when the method starts but then the while loop logs start being posted.
What I want to achieve is the while(true) loop running as quickly as possible while every so often (as a variable of time and not cycles of the while loop) updating the screen with information regarding the process in the while loop.
I know the while loop is running and the updateScreen() method is being called.
Full source below:
package com.example.android.collatzconjecturepathcruncher;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
TextView longestPathDisplay;
TextView longestPathSeedDisplay;
TextView currentSeedDisplay;
EditText startingNumberDisplay;
BigInteger longestPathSeed= BigInteger.ONE;
int longestPath=0;
BigInteger currentSeed=BigInteger.ZERO;
int currentPath=0;
BigInteger workingSeed=BigInteger.ONE;
boolean run;
int temp =0;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
longestPathDisplay = findViewById(R.id.longest_path);
longestPathSeedDisplay = findViewById(R.id.longest_path_seed);
currentSeedDisplay = findViewById(R.id.current_seed_display);
startingNumberDisplay = findViewById(R.id.starting_number_display);
longestPathDisplay.setText(getString(R.string.longest_path_display,longestPath));
longestPathSeedDisplay.setText(getString(R.string.longest_path_seed_display,longestPathSeed));
currentSeedDisplay.setText(getString(R.string.current_seed_display,currentSeed));
mHandler = new Handler();
startRepeatingTask();
}
#Override
public void onDestroy(){
super.onDestroy();
stopRepeatingTask();
}
public void startCrunching(View view){
String value = startingNumberDisplay.getText().toString();
currentSeed = new BigInteger(value);
workingSeed=currentSeed;
run=true;
while(run){
if(workingSeed.compareTo(BigInteger.ONE)==0){
if(currentPath>longestPath){
longestPath=currentPath;
longestPathSeed=currentSeed;
}
currentSeed= currentSeed.add(BigInteger.ONE);
workingSeed=currentSeed;
Log.d("end", "startCrunching: Finished "+(currentSeed.subtract(BigInteger.ONE))+" at "+currentPath+". Starting "+currentSeed);
currentPath=0;
updateScreen();
}
if (workingSeed.mod(new BigInteger("2")).compareTo(BigInteger.ZERO)==0){
workingSeed=workingSeed.divide(new BigInteger("2"));
}else{
workingSeed=(workingSeed.multiply(new BigInteger("3"))).add(BigInteger.ONE);
}
currentPath++;
}
}
public void updateScreen() {
//longestPathDisplay.setText(getString(R.string.longest_path_display, longestPath));
//longestPathSeedDisplay.setText(getString(R.string.longest_path_seed_display, longestPathSeed));
//currentSeedDisplay.setText(getString(R.string.current_seed_display, currentSeed));
longestPathDisplay.setText(getString(R.string.longest_path_display, temp));
longestPathSeedDisplay.setText(getString(R.string.longest_path_seed_display, temp));
currentSeedDisplay.setText(getString(R.string.current_seed_display, temp));
Log.d("update","requested screen update. Temp currently: "+temp);
temp++;
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try{
updateScreen();
Log.d("repeat","Tried Updating Screen");
}finally {
mHandler.postDelayed(mStatusChecker,5000);
}
}
};
void startRepeatingTask(){
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
}
Thanks in advance!
-Michael
Maybe I missed it, but I Don't see where you actual call your crunchnumber method.
startCrunching() this method is never called. I guess you need to change you execution sequence

When I change the page orientation it come at the beginning of page [duplicate]

This question already has answers here:
When I change the page orientation come at the beginning of page
(2 answers)
Closed 5 years ago.
I am using barteksc-AndroidPdfViewer. I am using this code
package com.epubtest.hxfy.epubtest;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;
public class PDFReaderActivity2 extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener, OnDrawListener, OnErrorListener, OnPageScrollListener {
private PDFView pdfview;
private SharedPreferences pdfReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfreader2);
pdfReader = this.getSharedPreferences("PDFReader", Context.MODE_PRIVATE);
pdfview = (PDFView) findViewById(R.id.pdfView);
pdfview.fromAsset("test4.pdf")
.defaultPage(pdfReader.getInt("pages",0))
.onPageChange(this)
.swipeHorizontal(false)
.enableAnnotationRendering(true)
.scrollHandle(null)
.onLoad(this)
.onDraw(this)
.enableSwipe(true)
.onError(this)
.enableDoubletap(true)
.onPageScroll(this)
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
SharedPreferences.Editor edit = pdfReader.edit();
edit.putInt("pages",page);
edit.commit();
}
#Override
public void loadComplete(int nbPages) {
}
#Override
public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {
}
#Override
public void onError(Throwable t) {
}
#Override
public void onPageScrolled(int page, float positionOffset) {
}
}
to change the orientation of the page. But if I have to assume if the portrait mode and page number 15 in change page orientation of the page when we started the landscape.
SharedPreferences is not working. It can't keep record last page where we were. Please help me in this regard, Please help me about this.
Don't use SharePreferences for this. When you change screen orientation, system recalls onCreate() method again and it redraws your views. For solution of this problem, you have 2 ways. First one is forcing to save state in manifest file.
<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>
If you write this parameter no need to handle in Activity , the framework will take care of rest of things. It will retain the state of the screen or layout if orientation is changed.
Another way is recommended by google developers which is better way for handling this problems in orientation changes. You can get more information in thislink. It will be better for reading this article also. It is about lifecycle of activity.
If you want source example, i can share my source with you. Enjoy!
For handling orientation changes, add this few lines to your source.
Configurator.onRender(new OnRenderListener() {
#Override
public void onInitiallyRendered(int pages, float pageWidth, float pageHeight) {
pdfView.fitToWidth(); // optionally pass page number
}
});

No such instance field

I'm trying to get my application to save some data when the orientation of the screen is changed using the onSaveInstanceState to save a boolean value mCheated.
I've set numerous break points and am getting an error for the mCheated boolean value in the variables view
mCheated= No such instance field: 'mCheated'
I have no idea why as I declare it with a value false when the activity is started and change it to true if a button is pressed. Can anyone help me out?
package com.bignerdranch.android.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Chris on 20/02/2015.
*/
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown";
private static final String KEY_INDEX = "index";
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
private boolean mCheated = false;
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE,false);
if (savedInstanceState != null){
mCheated = savedInstanceState.getBoolean(KEY_INDEX, mCheated);
}
setAnswerShownResult(mCheated);
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
mCheated = true;
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
//Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putBoolean(KEY_INDEX, mCheated);
}
}
It turns out there wasn't a problem with the code and that Android Studio required a restart. I think it was down to the fact I had cloned the project and was possibly using an incorrect file from the previous version.
Check if your build variant in Android Studio has
debuggable as true
proguard is disabled or commented out.
I had the same error.
The solution to the error is to disable the Proguard in build.gradle file.
debug {
minifyEnabled false
}
I got the same error and I wasted my 3-4 hours to resolve same error finally I got to know why that happened and it was interesting
In my case, I changed the code in one file (I declared one variable and initialized it)
I run the apk from my device and attached debugger from android studio
I set debug point to that newly added variable where I assigned data to it
but during debugging it shows me same error
Then I got to know I changed the code in file but I run the apk from device, and I attached debugger I need to compile and run the changes instead of it how it will reflect in apk that was the actual issue
So I compiled and ran the code and installed newly compiled apk on device then I attached debugger and it worked for me
hope this will save someone's time
If you're using pro-guard and obfuscation is true.
you have to comment out obfuscation in build gradle
eg: add this in the pro-guard -dontobfuscate

Android R cannot be resolved in Ubuntu

DatabaseConnect is the name of the Android Application Project that has been created in Eclipse in Ubuntu Platform.
One of the java file Inside DatabaseConnect->src->co.package.datewithme is shown Below.
package com.example.datewithme;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class Login extends Activity{
Intent i=null;
ImageView im=null;
EditText tv1,tv4;
boolean flag=false;
SQLiteDatabase db=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
im=(ImageView)findViewById(R.id.show_hide2);
tv1=(EditText)findViewById(R.id.phone2);
tv4=(EditText)findViewById(R.id.password2);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
// db.execSQL("create table if not exists login(name varchar,mobile_no varchar,email_id varchar,password varchar,flag varchar)");
im.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(flag==false)
{
im.setImageResource(R.drawable.hide);
tv4.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
flag=true;
}
else
{
im.setImageResource(R.drawable.show);
tv4.setInputType(129);
flag=false;
}
}
});
}
public void action(View v)
{
switch(v.getId())
{
case R.id.signin2:
i=new Intent(this,Signin.class);
startActivityForResult(i, 500);
overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_bottom);
finish();
break;
case R.id.start:
String mobile_no=tv1.getText().toString();
String password=tv4.getText().toString();
if(mobile_no==null||mobile_no==""||mobile_no.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(password==null||password==""||password.length()<6)
{
show("Please Enter Correct Password.");
}
else
{
Cursor c=db.rawQuery("select * from login where mobile_no='"+mobile_no+"' and password='"+password+"'",null);
c.moveToFirst();
if(c.getCount()>0)
{
i=new Intent(this,Welcome.class);
startActivityForResult(i,500);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
else
show("Wrong Password or Mobile number.");
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
}
The error message generated is R cannot be resolved to a variable.But i have R.java file in my Project DatabaseConnect->gen->com.example.Databaseconnect->BuilConfig.java,R.java.
The ScreenShot is shown below.
I Searched all the possibilities for the solution by going through these links.
123
But din't got the proper solution.
I came to know the naming convention got some errors like DatabaseConnect and Datewithme. So i kept the same name to both and then clean and run the project but after that its that its taking previous name itself.
An help is appreciated
Here are some TroubleShooting Steps for this issue.First you may clean the project, then run the project. If this does not work then follow the following links:
Here is the best way to solve this problem:Android Development- Where is my R.Java file?
1.R cannot be resolved - Android error
2.R cannot be resolved to a variable
3.R cannot be resolved to a variable -- mailing list entry
4.Fixed: R cannot be resolved to a variable
Most probably It happens when you have an error in any of your xml files under res folder
You should check:
all of your xml files under res folder fix errors like for example (under drawable folder you have not include icon.png and you are using it as #drawable/icon). When you will check and fix all errors in xml files then Build your project or clean it.
Hope you will understand my words.

reverse geocoding getPostalCode on Launch

I’m an experienced AS3 developer and I’ve done quite some stuff with Java for my backends but I’m new to Native Android development so I’m having troubles with some basic Tasks for my first Project.
So hope one of you cracks can help me out here or point me in the right directions, it would be much appreciated and I’ll repay be helping out in the AS3 section. That briefly about me, since it’s my first post. ;)
The task at hand is to get the users postcode on application launch. I’ve been using an AsyncTask for the reverse geocoding and It generally seems to work. But only when I call the ReverseGeocodingTask on a button click, and give it a few seconds before I do so. If I press it immediately it sometimes works and sometimes doesn’t, so obviously when I call it in the onCreate method the app crashes aswell. It also crashes when I turn the internet off on the phone. I reckoned the network provider location should be sufficient and there is no need for the GPS accuracy and the additional permissions.
If the INet is turned off by the user, it should just show a message that the postcode can’t be found and give the user the option to input it manually.
I figured that the currentLocation to pass to the geocoding has not been found yet and is throwing a NullPointerException, so I tried to prevent that by checking it before the call. But that didn’t really help and is no solution for the final version anyways.
Since its always best to show the code so u guys know what’s going on, here goes:
package com.adix.DroidTest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Locale.getDefault;
public class MyActivity extends Activity implements View.OnClickListener {
Button getPostCode, confirm;
TextView tvPostcode;
LocationManager locationManager;
Location currentLocation;
double currentLatitude;
double currentLongitude;
private Handler mHandler;
private static final int UPDATE_ADDRESS = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
AtomicReference<LocationListener> locationListener = new AtomicReference<LocationListener>(new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
private void updateLocation(Location location) {
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}
public void onStatusChanged(
String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
});
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener.get());
//getAddress();
mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_ADDRESS:
tvPostcode.setText((String) msg.obj);
break;
}
}
};
}
private void init() {
getPostCode = (Button)findViewById(R.id.bGetPostCode);
confirm = (Button)findViewById(R.id.bConfirm);
tvPostcode = (TextView)findViewById(R.id.tvPostcode);
getPostCode.setOnClickListener(this);
confirm.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bGetPostCode:
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(currentLocation != null) {
Log.d("TRACE",currentLocation.toString());
Toast.makeText(this, "Suche Postleitzahl", Toast.LENGTH_LONG).show();
(new ReverseGeocodingTask(this)).execute(new Location[]{currentLocation});
}
break;
case R.id.bConfirm:
Intent i = new Intent(MyActivity.this, MainMenu.class);
startActivity(i);
finish();
}
}
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
#Override
protected Void doInBackground(Location... locations) {
try{
Geocoder gcd = new Geocoder(mContext, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(currentLatitude, currentLongitude,100);
Address address = addresses.get(0);
StringBuilder result = new StringBuilder();
result.append(address.getPostalCode());
// tvPostcode.setText(result.toString());
Message.obtain(mHandler, UPDATE_ADDRESS, result.toString()).sendToTarget();
}
catch(IOException ex){
tvPostcode.setText(ex.getMessage().toString());
Message.obtain(mHandler, UPDATE_ADDRESS, ex.getMessage().toString()).sendToTarget();
}
return null;
}
}
}
I gave this a rest since this post to see if someone sees my mistake. Since I hadn't got an answer, I gave it another shot today. And fortunately found the answer quite quick in the end. Obviously I needed to execute the ReverseGeocodingTask in the onLocationChanged method after updateLocation.

Categories

Resources