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.
Related
One of the functions in my app is sending email. The email list is generated by querying from SQLite database table. So sending email and query data from SQLite database at the same activity. It is not working. Sending email code works if I apply the code in a simple app. Query works. It is not working when I put them all together. After reading online, my feeling is that I need to create a new thread that handle the SQLite database query. I am very new for android and java and don't know how to create a new thread (background).
Could somebody help me? Many many thanks!!!!!
my activity code as following:
package jhapps.com.demographics;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class PromotionEmailMonthTop10 extends Activity {
private EditText subjectGroupTop10,bodyGroupTop10;
private Button btnMonthTop10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promotion_email_month_top10);
subjectGroupTop10=(EditText)findViewById(R.id.subjectMonthTop10);
bodyGroupTop10=(EditText)findViewById(R.id.bodyMonthTop10);
btnMonthTop10=(Button)findViewById(R.id.btnMonthTop10);
btnMonthTop10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EmailMonthTop10();
// after sending the email, clear the fields
subjectGroupTop10.setText("");
bodyGroupTop10.setText("");
}
});
}
//get month top 10 email list
protected void EmailMonthTop10() {
DataBaseHelper dataBaseHelper=new DataBaseHelper(PromotionEmailMonthTop10.this);
String[] emailGroupTop10=new String[dataBaseHelper.eMailListMonthTop10().size()];
for(int i=0;i<dataBaseHelper.eMailListMonthTop10().size();i++){
emailGroupTop10[i]=dataBaseHelper.eMailListMonthTop10().get(i);
}
String subjects=subjectGroupTop10.getText().toString();
String bodytext=bodyGroupTop10.getText().toString();
//start email intent
Intent email = new Intent(Intent.ACTION_SENDTO);
// prompts email clients only
email.setType("message/rfc822");
email.setData(Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL,emailGroupTop10 );
// email.putExtra(Intent.EXTRA_EMAIL,new String []{"junrudeng#gmail.com","huangji8#gmail.com"});
email.putExtra(Intent.EXTRA_SUBJECT, subjects);
email.putExtra(Intent.EXTRA_TEXT, bodytext);
try {
// the user can choose the email client
startActivity(Intent.createChooser(email, "Choose an email client from..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(PromotionEmailMonthTop10.this, "No email client installed.",
Toast.LENGTH_LONG).show();
}
}
}
You should never execute database queries or network calls on the main thread. If you want to query a database to display data you probably want to you a AsyncTask for that.
Something like the following should work:
public class PromotionEmailMonthTop10 extends Activity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
btnMonthTop10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new SendEmailTop10Task().execute();
}
});
}
class SendEmailTop10Task extends AsyncTask<Void, Void, Void> {
// This is called on a seperate thread
#Override
protected Void doInBackground(Void... voids) {
EmailMonthTop10();
}
// This is called on the main thread
#Override
protected void onPostExecute(Integer status) {
subjectGroupTop10.setText("");
bodyGroupTop10.setText("");
}
}
}
Please consider renaming your method taking the java naming conventions under consideration
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
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
Basically I am creating buttons within a for loop, I need each button to return a different value when pressed.
I had thought that creating my own onClickListener() and passing in the data needed as a parameter when it is initialized would work. It appears there are no syntax errors with what I came up with but when a button is clicked at run time the app crashes.
Heres a simplified version of what I've got thus far.
int counter = 1;
for( Program element : someList)
{
//some other code for dynamically creating textviews to stick the buttons in
//code which creates the buttons on the fly
moreInfo = new Button(this);
moreInfo.setText("More Info");
moreInfo.setOnClickListener(new DynamicOnClickListener(counter));
counter++;
}
The custom listener class
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class DynamicOnClickListener implements OnClickListener
{
int counter;
public DynamicOnClickListener(int acounter) {
this.counter = acounter;
}
public void onClick(View v) {
Log.v("DynamicOnClickListener","1");
Toast.makeText(v.getContext(), counter, Toast.LENGTH_LONG).show();
}
}
So in theory if this worked each button would return a different number, hope that makes sense.
Toast.makeText takes string resource id as a second argument. Your counter value is not a valid resource id that's way you are getting an error. You need to pass a String instead of int and it will work.
Toast.makeText(v.getContext(), String.valueOf(counter), Toast.LENGTH_LONG).show();
Instead of creating multiple listeners you can use setTag()
moreInfo = new Button(this);
moreInfo.setText("More Info");
moreInfo.setTag(new Integer(counter));
moreInfo.setOnClickListener(new DynamicOnClickListener();
then, in your listener
public void onClick(View v) {
Log.v("DynamicOnClickListener","1");
Toast.makeText(v.getContext(), ((Integer)v.getTag()).toString(), Toast.LENGTH_LONG).show();
}
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.