Many responses over stackoverflow advised to import R. I did that and I made sure to rebuild/clean my path over 10 times before asking this question.
Here are how my files are arranged:
We can all clearly see the error lies somewhere between MainActivity file or XML file.
Here is the code for the MainActivity file , it is pretty much a copy from Google's git hub account and the ONLY error is it cannot identity what "R" is.:
package com.eatwithme;
/*
* Copyright (C) 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.eatwithme.activities.SampleActivityBase;
import com.eatwithme.logger.Log;
import com.eatwithme.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
public class MainActivity extends SampleActivityBase
implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
/**
* GoogleApiClient wraps our service connection to Google Play Services and provides access
* to the user's sign in state as well as the Google's APIs.
*/
protected GoogleApiClient mGoogleApiClient;
private PlaceAutocompleteAdapter mAdapter;
private AutoCompleteTextView mAutocompleteView;
private TextView mPlaceDetailsText;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up the Google API Client if it has not been initialised yet.
if (mGoogleApiClient == null) {
rebuildGoogleApiClient();
}
setContentView(R.layout.activity_main);
// Retrieve the AutoCompleteTextView that will display Place suggestions.
mAutocompleteView = (AutoCompleteTextView)
findViewById(R.id.autocomplete_places);
// Register a listener that receives callbacks when a suggestion has been selected
mAutocompleteView.setOnItemClickListener(mAutocompleteClickListener);
// Retrieve the TextView that will display details of the selected place.
mPlaceDetailsText = (TextView) findViewById(R.id.place_details);
// Set up the adapter that will retrieve suggestions from the Places Geo Data API that cover
// the entire world.
mAdapter = new PlaceAutocompleteAdapter(this, android.R.layout.simple_list_item_1,
BOUNDS_GREATER_SYDNEY, null);
mAutocompleteView.setAdapter(mAdapter);
// Set up the 'clear text' button that clears the text in the autocomplete view
Button clearButton = (Button) findViewById(R.id.button_clear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAutocompleteView.setText("");
}
});
}
/**
* Listener that handles selections from suggestions from the AutoCompleteTextView that
* displays Place suggestions.
* Gets the place id of the selected item and issues a request to the Places Geo Data API
* to retrieve more details about the place.
*
* #see com.google.android.gms.location.places.GeoDataApi#getPlaceById(com.google.android.gms.common.api.GoogleApiClient,
* String...)
*/
private AdapterView.OnItemClickListener mAutocompleteClickListener
= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
Retrieve the place ID of the selected item from the Adapter.
The adapter stores each Place suggestion in a PlaceAutocomplete object from which we
read the place ID.
*/
final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i(TAG, "Autocomplete item selected: " + item.description);
/*
Issue a request to the Places Geo Data API to retrieve a Place object with additional
details about the place.
*/
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
Toast.makeText(getApplicationContext(), "Clicked: " + item.description,
Toast.LENGTH_SHORT).show();
Log.i(TAG, "Called getPlaceById to get Place details for " + item.placeId);
}
};
/**
* Callback for results from a Places Geo Data API query that shows the first place result in
* the details view on screen.
*/
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
= new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
// Request did not complete successfully
Log.e(TAG, "Place query did not complete. Error: " + places.getStatus().toString());
return;
}
// Get the Place object from the buffer.
final Place place = places.get(0);
// Format details of the place for display and show it in a TextView.
mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(),
place.getId(), place.getAddress(), place.getPhoneNumber(),
place.getWebsiteUri()));
Log.i(TAG, "Place details received: " + place.getName());
}
};
private static Spanned formatPlaceDetails(Resources res, CharSequence name, String id,
CharSequence address, CharSequence phoneNumber, Uri websiteUri) {
Log.e(TAG, res.getString(R.string.place_details, name, id, address, phoneNumber,
websiteUri));
return Html.fromHtml(res.getString(R.string.place_details, name, id, address, phoneNumber,
websiteUri));
}
/**
* Construct a GoogleApiClient for the {#link Places#GEO_DATA_API} using AutoManage
* functionality.
* This automatically sets up the API client to handle Activity lifecycle events.
*/
protected synchronized void rebuildGoogleApiClient() {
// When we build the GoogleApiClient we specify where connected and connection failed
// callbacks should be returned, which Google APIs our app uses and which OAuth 2.0
// scopes our app requests.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0 /* clientId */, this)
.addConnectionCallbacks(this)
.addApi(Places.GEO_DATA_API)
.build();
}
/**
* Called when the Activity could not connect to Google Play services and the auto manager
* could resolve the error automatically.
* In this case the API is not available and notify the user.
*
* #param connectionResult can be inspected to determine the cause of the failure
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
// TODO(Developer): Check error code and notify the user of error state and resolution.
Toast.makeText(this,
"Could not connect to Google API Client: Error " + connectionResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
// Disable API access in the adapter because the client was not initialised correctly.
mAdapter.setGoogleApiClient(null);
}
#Override
public void onConnected(Bundle bundle) {
// Successfully connected to the API client. Pass it to the adapter to enable API access.
mAdapter.setGoogleApiClient(mGoogleApiClient);
Log.i(TAG, "GoogleApiClient connected.");
}
#Override
public void onConnectionSuspended(int i) {
// Connection to the API client has been suspended. Disable API access in the client.
mAdapter.setGoogleApiClient(null);
Log.e(TAG, "GoogleApiClient connection suspended.");
}
}
Also, Here is my my Android Manifest file (with my key removed). Please notice my activity's name. I did so cause if I remove the com.eatwithme before the activity's name, it gives me an error.
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google.playservices.placecomplete"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19"/>
<!-- PlacePicker also requires OpenGL ES version 2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AnLE"/>
<activity
android:name="com.eatwithme.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
I have personally tried my level best but sadly, I am unable to resolve this conflict. The only three sources of error in my opinion could be
1) Have no R file
2) AndoridManifest file is not right
3) Main file isnt right
4) The order of file isnt right
Any guidance on this issue?
The problem lies in your xml manifest here:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
Wrong --> package="com.example.google.playservices.placecomplete"
android:versionCode="1"
android:versionName="1.0">
It needs to be the exact package name of your project which is:
package="com.eatwithme"
not the google sample package name.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google.playservices.placecomplete"
Change this package name to your package name i.e.com.eatwithme package.
I didn't read through all your code - sorry :)
I recommend removing your import of R. If you're sure you have all your files in the right places, do as #AbhishekVasisht suggested and "clean project" (in Android Studio you click Build > Clean Project; I forget where it is in Eclipse).
If that doesn't work, you can also try what's called "invalidate caches and restart." This is a little extreme because it gets rid of your local history for the project, but it sounds like you've reached a point of desperation. In Android Studio, you click File > Invalidate Caches / Restart... and you want to select the option that invalidates AND restarts all in the same action.
As a last resort, you could try to import your existing code as a new Android project. This is a crap shoot but it's worked for me a couple times in the past.
Good luck! Sorry man, I know how frustrating this one can be.
if you are beginner in udacity android app development and learning lesson 2A /5th topic and problem occur in running MainActivity.java code compiletion then put below code in MainActivity.java
code is given below
package com.example.android.justjava;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void submitOrder(View view) {
display(1);
}
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quanity_text_view);
quantityTextView.setText("" + number);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I don't have enough references to add comments, otherwise this would be a comment.
From my personal experience, try doing a "clean and rebuild", this sometime clears this error.
Hope some other people can back me up with this
Make sure all your XML files have valid resources, images and stuff and Clean project.
I updated my project from GitBucket and one .png was missing somehow so i got that error and that R was missing. I concentrated on resolving R issue and wasted couple of hours on that and when i put random .png instead the missing one and cleaned the project, the R got back.
Late answer, and another solution. Thought anyone need it.
I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.
classpath 'com.android.tools.build:gradle:3.2.1'
I faced the same problem. My solution was that the directory path under which I saved my project was too long.
Related
I have the following code , im receiving an error :
enter image description here
package com.example.photopicker;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button addimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addimage=findViewById(R.id.button_pick_photo);
addimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Registers a photo picker activity launcher in single-select mode.
ActivityResultLauncher<PickVisualMediaRequest> pickMedia =
registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
// Callback is invoked after the user selects a media item or closes the
// photo picker.
if (uri != null) {
Log.d("PhotoPicker", "Selected URI: " + uri);
} else {
Log.d("PhotoPicker", "No media selected");
}
});
// Include only one of the following calls to launch(), depending on the types
// of media that you want to allow the user to choose from.
// Launch the photo picker and allow the user to choose images and videos.
pickMedia.launch(new PickVisualMediaRequest.Builder()
**.setMediaType(new ActivityResultContracts.PickVisualMedia.ImageAndVideo())**
.build());
}
});
}
}
This code i got it from the Android developer Website :
https://developer.android.com/training/data-storage/shared/photopicker
but Doesnt seem to work , and im not able to find any online solution.
Try replacing:
new ActivityResultContracts.PickVisualMedia.ImageAndVideo()
with:
ActivityResultContracts.PickVisualMedia.Companion.getImageAndVideo()
ImageAndVideo is a Kotlin object — it is not a class that you instantiate yourself. However, the source code lacks the #JvmField annotation, so I think that just referring to ActivityResultContracts.PickVisualMedia.ImageAndVideo will fail, as outlined in the docs.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my application I noticed these three things:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The problem is I don't want the user to click on Back at a certain point in my application. I don't want to disable the back button completely in my application, only when one intent is called. How can I do that?
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my application, some of the toast notifications are residual and are popping outside of my application. Is there a reason for that? Did I miss something in the activity lifecycle to handle the cancellation of toasts at a certain point?
Lastly, this one is rather tough to solve. How do I lock my screen so that when the user rotates the device, that the activity doesn't not get called again and the asynctask can still resume without starting over again?
Thanks a lot for your time. Just curious why these things happen and what should I look into?
Here's my code:
//Main Activity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.*;
public class MainActivity extends Activity {
//fields
private ProgressDialog progressBar;
private Context context;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;
//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Executes the AsyncTask
new RetrieveInfoTask().execute();
//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public class RetrieveInfoTask extends AsyncTask<Void, Void, Void> {
//Called on the UI thread to execute progress bar
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage(MainActivity.this.getString(R.string.retrieve_info));
progressBar.show();
}
//Methods that retrieves information from the user device. This is performed in the Background thread
private void retrieveInfo() {
try {
//Reading the drawable resource line by line
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//doInBackground calls retrieveInfo() to perform action in Background
#Override
protected Void doInBackground(Void... params) {
retrieveInfo();
return null;
}
//When the background task is done, dismiss the progress bar
#Override
protected void onPostExecute(Void result) {
if (progressBar!=null) {
progressBar.dismiss();
}
}
}
}
//RetrieveInfoActivity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class RetrieveInfoActivity extends Activity {
private static String TAG = "RetrieveInfoActivity";
private Context context;
String fileLastSync = "09-18-2014 03:47 PM";
#Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieve_info);
//Once the new activity is launched, the setup is complete
Toast.makeText(getApplicationContext(), "Setup Complete!",
Toast.LENGTH_LONG).show();
//Gets the 'last synced' string and sets to datetime of the last sync
Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
//calls registerReceiver to receive the broadcast for the state of battery
this.registerReceiver(this.mBatInfoReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
//Battery level
int level = intent.getIntExtra("level", 0);
//Dynamically sets the value of the battery level
TextView batteryTextView = ((TextView) findViewById(R.id.battery) );
batteryTextView.setText("Battery Level: " + String.valueOf(level)+ "%");
//If the battery level drops below 25%, then announce the battery is low
//TODO: Add 25 to constants file.
if(level < 25) {
Toast.makeText(getApplicationContext(), "Low Battery!",
Toast.LENGTH_LONG).show();
}
//Plugged in Status
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//Battery Status
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//If the device is charging or contains a full status, it's charging
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
//If the device isCharging and plugged in, then show that the battery is charging
if(isCharging && plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Charging.." + String.valueOf(level)+ "%",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unplugged!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(this.mBatInfoReceiver);
}
catch (Exception e) {
Log.e(RetrieveInfoctivity.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
}
//StartSetupActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartSetupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
//FragmentsActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentsActivity extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
}
First of all whenever you want to disable back press just override onBackPressed() method and remove super. like this:
#Override
public void onBackPressed() {
//super.onBackPressed();
}
Second you'r using application context to show toast. use activity context.
Toast.makeText(this or YourActivity.this, "Setup Complete!", Toast.LENGTH_LONG).show();
Third just add this attribute into your manifest class. This will avoid recrating your activity when orientation change
android:configChanges="orientation"
I'll answer these in order:
Back Button
You can override onBackPressed in your Activity and determine if you want to consume it or let Android process it.
#Override
public void onBackPressed()
{
// Set this how you want based on your app logic
boolean disallowBackPressed = false;
if (!disallowBackPressed)
{
super.onBackPressed();
}
}
Toasts
Toasts are enqueued with the Notification Manager. If you show multiple Toasts in a row, they get queued up and shown one at a time until the queue is empty.
Locking Orientation For Activity
Use android:screenOrientation="landscape" or android:screenOrientation="portrait" on your activity element in your manifest to lock the orientation.
I think that these questions should be asked separately, because the answer in detail to every item of your question is too long, but I hope this helps:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The
problem is I don't want the user to click on Back at a certain point
in my application. I don't want to disable the back button completely
in my application, only when one intent is called. How can I do that?
You can override the onBackPressed on the activities you don't want the user to go back.
#Override
public void onBackPressed() {
//Leave it blank so it doesn't do anything
}
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my
application, some of the toast notifications are residual and are
popping outside of my application. Is there a reason for that? Did I
miss something in the activity lifecycle to handle the cancellation of
toasts at a certain point?
I think that the reason behind that is that toast go into a que, and are showed in order, even if the app is no longer visible.
Lastly, this one is rather tough to solve. How do I lock my screen so
that when the user rotates the device, that the activity doesn't not
get called again and the asynctask can still resume without starting
over again?
For this, you can use the following code in your manifest
android:configChanges="orientation|screenSize"/>
However this is NOT recommended by google, I suggest you read the following link to get a little more information on how to handle orientation changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html
Just making a test application that should display a log message on changing orientation, but when i change orientation using ctrl + f11, there is nothing shown in the logcat.
what is the issue in the coding
A Part From Manifest
<activity
android:name="com.example.orientationtest.MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize" >
A part from Java
package com.example.orientationtest;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Configuration;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
Log.d("error", " orientation changes");
}
}
try this if target api 13 and above
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
or
android:configChanges="orientation|keyboardHidden|screenLayout"
for lower than 13 ..... this will help you... :)
Using configChanges is not a good idea if you only want to know if the screen rotated. It basically means that you plan to handle the whole rotation change by yourself in the code.
If you don't plan to do this, just check what is the current rotation when your Activity is created:
int currentOrientation = getResources().getConfiguration().orientation;
Then just do whatever you want using this check:
if(currentOrientation == Configuration.ORIENTATION_LANDSCAPE){
//if landscape
} else {
//if portrait
}
This way you don't need to touch your manifest file and you let your app manage the configuration changes by itself.
You can keep the previous orientation used in the activity saved instance if you need to compare the previous and the current one.
The issue is that you prevented the android from changing its orientation
android:configChanges="orientation|screenSize"
that line of code is preventing it to configuration change and that why your not getting any response..
I am a PHP developer, who is new to Android development and Java so please bear with me.
I am developing an extremely simple app for testing and learning purposes.
when the user clicks my app icon, they are presented with a loading screen. I have a TextView with a progress bar underneath.
TextView XML code:
<TextView
android:id="#+id/loadingMessage1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/progressBar1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:text="#string/loading1" />
The value is set to the string loading1 in strings.xml
<string name="loading1">Loading Message 1</string>
In my loadingscreen.java i have:
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class LoadingScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_screen);
TextView loadingMessage1 = (TextView)this.findViewById(R.id.loadingMessage1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_loading_screen, menu);
return true;
}
}
Notice I have the code:
TextView loadingMessage1 = (TextView)this.findViewById(R.id.loadingMessage1);
Which I think references the text view.
What I want to happen is that every 3 seconds a different message appears.
So loading message 1... (3 secs) loading message 2... (3 secs) loading message 3..
after loading message 3 i would like a button to replace the progress bar.
You can use the Handler class:
final Handler handler = new Handler();
handler.post(new Runnable(){
#Override
public void run(){
// change your text here
handler.postDelayed(this, 3*1000L);
}
});
You might need to use a timer, which executes every 1 second period.. Read this brilliant android dev blog article on periodic execution using timer and Handler.
(Solved) Thanks to NetCat: it was a UI XML problem :)
Today I have started Android development, i'm using a Mac with Eclipse and the Android SDK install and all working (I have successfully managed to get working a few "Hello World" type apps working) and for the Android device i'm using my new HTC Incredible S.
So the code below should work and their are no error is the debugger when I run it on my phone, but each time I do before it even loads, the phone pops up a message saying "The application Count (process com.count) has stopped unexpectedly. Please try agin."
I have re created the project several times with different SDK versions 1.5 and 2.2 but still no luck.
The code is from another tutorial I successfully worked through but i have changed some of the variables to make a slightly different app. Can you tell me what is wrong with the following code:
package com.count;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class count extends Activity implements OnClickListener {
//Declare widgets
Button btnSave, btnUp, btnDown;
TextView lblCurrentCount, lblCountCard;
//Declare variables
int intCount=0;
int intCardCount=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Sets up the link between java and the XML widgets
btnSave = (Button)findViewById(R.id.btnSave);
btnUp = (Button)findViewById(R.id.btnUp);
btnDown = (Button)findViewById(R.id.btnDown);
lblCurrentCount = (TextView)findViewById(R.id.lblCurrentCount);
lblCountCard = (TextView)findViewById(R.id.lblCountCard);
//Initialize widgets
lblCurrentCount.setText(String.valueOf(intCount));
lblCountCard.setText("");
//Define button listeners
btnSave.setOnClickListener(this);
btnUp.setOnClickListener(this);
btnDown.setOnClickListener(this);
}
//When any button is clicked
#Override
public void onClick(View src) {
//Actions when buttons are clicked
switch(src.getId()) {
case R.id.btnSave:
lblCountCard.append("\n#" + intCardCount + " " + intCount);
intCardCount++;
intCount=0;
lblCountCard.setText(String.valueOf(intCount));
break;
case R.id.btnUp:
intCount++;
lblCountCard.setText(String.valueOf(intCount));
break;
case R.id.btnDown:
intCount--;
lblCountCard.setText(String.valueOf(intCount));
break;
}
}
}
Thanks Dave
You must supply a layout_width
attribute.
That's probably it. You've got a layout element without a layout_width (and probably, if you make the same kinds of mistakes I do, a layout_height) attribute. Find it, add the attributes, and see what comes next.