Hi:
I'm very new at programming in Android (I have programmed extensively PC applications and used Java) and I'm at a loss. I want to create a application that uses fragments. I want to create the Fragment Programaticaly (as the introduction says on Android Developer page) buy my application keeps crashing and I have no Idea as to why.
Here is the code for my main activity:
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fmanager = getFragmentManager();
FragmentTransaction ftransaction = fmanager.beginTransaction();
FileBrowser fbrowser = new FileBrowser();
ftransaction.add(R.layout.main,fbrowser, "FileBrowser");
ftransaction.commit();
fbrowser.test();
}
And here is the code for FileBrowser:
Code:
public class FileBrowser extends ListFragment {
public void test(){
System.err.println("Entre a test!!!");
String[] MyList = {"HOla","Mundo","De","Las","Listas"};
if (getActivity() == null){
System.err.println("I get a NULL Activity");
}
else{
System.err.println("No NULL Activity Attempting to Create an Adapter");
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(), R.layout.file_row, MyList);
}
//setListAdapter(new ArrayAdapter<String>(this.getActivity(), R.layout.file_row, MyList));
}
}
All I wan to do to start is to print the string list MyList in the fragment. However I the program crashes and I get this error:
06-09 19:25:42.920: ERROR/AndroidRuntime(26064): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ccr/com.ccr.Main}: java.lang.IllegalArgumentException: No view found for id 0x7f030001 for fragment FileBrowser{4077d558 #0 id=0x7f030001 FileBrowser}
Thanks for any help!
Related
Hi guys,
I am writing a program which has to display content provided by a web platform. Therefore, I split the program up into four classes. The "Main" class (Activity) just initializes the Controller "AppScheduler" (Intent) which then initializes the "PlatformConnector" (Service) and the "UI" (Activity).
Since I am a newbie in programming apps for Adroid, I am having trouble with getting setup a view in the UI. In case I define a view there, the app returns an exception. Does anyone of you knows what I am doing wrong?
Main Class:
public class Main extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppScheduler controller = new AppScheduler(this);
controller.Initialize();
// everything else happens in AppScheduler class
}
}
-------------------------
AppScheduler Class:
public class AppScheduler extends Intent {
// PLATFORM CONNECTOR ATTRIBUTES
protected PlatformConnector pfconnect = null;
// VIEW ATTRIBUTES
protected UI uiMain = null;
// AppScheduler Constructor
public AppScheduler(Main main) {
// TODO Auto-generated constructor stub
}
public void Initialize (){
//initialize Web Service Connector
pfconnect = new PlatformConnector();
pfconnect.initialize();
// create and initalize GUI
uiMain = new UI();
uiMain.onCreate(null);
}
}
---------------------------
UI Class:
public class UI extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
The Error occurs in case I include "setContentView(R.layout.main);". Note: The main.xml exists and normally runs without any problems.
I don't know why you are using the Intent the way you are. It isn't intended to be used as a controller class base.
An intent is meant invoke an event in the system, and the system figures out the best way to handle it.
Oh and you are trying to instantiate an Activity class and show it; you aren't supposed to do that either. My guess is you haven't done any Android development yet. I recommend starting with the basics and the sample programs.
http://code.google.com/android/intro/hello-android.html
Check this class below,
______ My Code _______
public class Main extends Activity implements OnKeyListener {
DisplayWord currentWord;
TextView wordStatus;
EditText inputWord;
Button okBtn;
int pos = 1;
char currentChar;
char inputChar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
currentWord = (DisplayWord) this.findViewById(R.id.trueWord);
currentWord.setText("Bonjure"); // word from database
wordStatus = (TextView) this.findViewById(R.id.wordStatus);
inputWord = (EditText) this.findViewById(R.id.wordInput);
inputWord.setOnKeyListener(this);
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (inputWord.getText().toString().length() <= currentWord.getText().toString().length()) {
pos = inputWord.getText().toString().length();
currentChar = currentWord.getText().toString().charAt(pos);
inputChar = inputWord.getText().toString().charAt(pos);
} return false;
}
}
_____ END _____
When running this code, upon entering data into the input box it causes an exception straight away and for the program exit unexpectedley.
I am trying to extract the input word from EditText field and the word stored in a TextView and to compare them char by char as those chars are entered into the input box, sort of a word game, where the character will be highlighted green if it is correct and red if it is not.
I have no idea why this behaviour happens, I can see in debugger an StringIndexOutOfBounds exception, and a ResourceNotFound when I have been tampering with different ways of attempting this, access position or the char array, it always seems to throw an exception.
Any advice or links appreciated,
AnthonyI am trying to post a copy and paste of just text, no links but validation error on starting a new thread is telling me that I cannot submit a message with a link in it? I want to show everyone a simple class because of some problem's i'm having.. any ideas?
I'm trying to develop (for the liveview) using an SDK and need to get a bitmap of Google Maps.
Code:
//Map Section
public class myMap extends MapActivity {
MapView mapView;
Bitmap bitmap;
boolean created = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createMap();
}
public void createMap()
{
// build map and mark point
mapView = new MapView(this, "keykeykeykeykeykey");
mapView.setBuiltInZoomControls(false);
GeoPoint point = new GeoPoint(52242730,-884211);
mapView.getController().animateTo(point);
mapView.preLoad();
// copy MapView to canvas
bitmap = Bitmap.createBitmap(400, 800, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
mapView.draw(canvas);
PluginUtils.sendTextBitmap(mLiveViewAdapter, mPluginId, "Loading Map...", 128, 12);
created = true;
}
public void displayMap()
{
if (created == false)
{
createMap();
}
//Display map on device
Bitmap mybit = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888);
for(int i = 0; i < 128; i++)
{
for(int j = 0; j < 128; j++)
{
mybit.setPixel(i, j, bitmap.getPixel(i, j));
}
}
//white pixel for debugging
mybit.setPixel(64, 64, Color.WHITE);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Is what I've got so far, the code in createMap() was in onCreate() but It didn't seem to be called.
Now it just force closes.
Anyone know how to help? Is there a better place to ask development questions?
Thanks.
-=Edit=-
Oh, and here's the routine calling the map thing, every couple of seconds.
Code:
private class Timer implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
myMap theMap = new myMap();
theMap.displayMap();
}
}
Okay, looks like you cant use google street map like this.
Anyone looking for similar solution, I used open street map and downloaded 'slipery tiles' png's. They provide java routines for finding the tile url from lat/lon.
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
Why my items are not redrawn after invoking `invalidateViews()` ?
I ask because i try to refresh `listItems` after a bg-thread notify an image rsc was downloaded.
But nothing is updated. Only after exiting and re-entering the new icons are drawn.
I have an activity with `adapter` of type `SettingValueAdapter extends BaseAdapter`
it has a member:
`private SettingsValue[] values;`
it has two interesting methods:
@override
public View getView(int position, View view, ViewGroup parent) {
AddressItem ai= (AddressItem)getItem(position);
DriveToNativeManager dnm = DriveToNativeManager.getInstance();
if (view == null) {
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.address_item, null);
}
view.setTag(R.id.addressItem,ai);
view.setTag(position);
view.findViewById(R.id.fullAddressItemCol).setVisibility(View.VISIBLE);
view.findViewById(R.id.addressItemTouch).setVisibility(View.GONE);
view.findViewById(R.id.addressItemImage).setVisibility(View.GONE);
if (ai != null) {
...
}
view.findViewById(R.id.addressItemIconLayout).setVisibility(View.VISIBLE);
Drawable icon = ResManager.GetSkinDrawable(ai.getIcon() + ".bin");
((ImageView)view.findViewById(R.id.addressItemIcon)).setImageDrawable(icon);
..
}
I attach a callback to the bg-thread (c language) image downloading process.
The callback switches to the ui-thread and calls this `refreshList`:
public void refreshSearchIconsOnSearchActivity() {
Runnable refreshViewEvent = new Runnable() {
@override
public void run() {
Activity currentActivity = AppService.getActiveActivity();
if (currentActivity instanceof SearchActivity) {
Log.d("w", "refreshSearchIconsOnSearchActivity callback running in thread "
+ Thread.currentThread().getId() );
//results list
((SearchActivity) currentActivity).refreshList();
}
}
};
AppService.Post(refreshViewEvent);
}
However, the images are done downloading and are not refreshed on the activity.
They are refreshed only when I leave an re-enter the activity.
What am I missing?
The article was written in the course of the game's development CLEAR SKY 2
The first part here!
Code
In the main Activity implement two interfaces GameHelperListener, ActionResolver:
public class MainActivity extends AndroidApplication implements GameHelperListener, ActionResolver
GameHelperListener interface is as follows:
Code:
public interface GameHelperListener {
/ **
* Called when an attempt to login. This method can show
* User button «Sign-in» for manual entry
* /
void onSignInFailed ();
/ ** Called when a successful login attempt * /
void onSignInSucceeded ();
}
Interface ActionResolver create ourselves. He needed to call the platform-dependent code. This technique is described in the official wiki libgdx. An example of the interface:
Code:
public interface ActionResolver {
/ ** Check the status of the user input * /
public boolean getSignedInGPGS ();
/ ** Log * /
public void loginGPGS ();
/ ** Send the result in the high score table * /
public void submitScoreGPGS (int score);
/ **
* Unlock achievement
*
*param AchievementId
* ID achievements. Taken from the file games-ids.xml
* /
public void unlockAchievementGPGS (String achievementId);
/ ** Show Activity records to the table * /
public void getLeaderboardGPGS ();
/ ** Show Activity achievements * /
public void getAchievementsGPGS ();
}
Example code main Activity:
Code:
public class MainActivity extends AndroidApplication implements
GameHelperListener, ActionResolver {
// Assistant to work with gaming services
private GameHelper gameHelper;
// Class of our games
private TestGame game;
Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
// CLIENT_ALL instruct you on the use of the API all customers
gameHelper = new GameHelper (this, GameHelper.CLIENT_ALL);
// Disable automatic login when starting the game
gameHelper.setConnectOnStart (false);
gameHelper.enableDebugLog (true);
// From turning off the screen without the use of additional
// Permits (less than permissions - more confidence in the application)
getWindow (). addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Input parameter this is ActionResolver. Allows you to call from
// Game loop platform-specific methods GPGS
game = new TestGame (this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration ();
initialize (game, config);
gameHelper.setup (this);
}
// Methods gameHelper'a: onStart (), onStop () are called to work correctly
// GPGS in the lifecycle of android-app
Override
protected void onStart () {
super.onStart ();
gameHelper.onStart (this);
}
Override
protected void onStop () {
super.onStop ();
gameHelper.onStop ();
}
Override
protected void onDestroy () {
super.onDestroy ();
}
Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult (requestCode, resultCode, data);
// Here gameHelper decides to connect, or reconnect
// Disconnected from the game services, depending on the result code
// Activity
gameHelper.onActivityResult (requestCode, resultCode, data);
}
Override
public boolean getSignedInGPGS () {
// Connection status
return gameHelper.isSignedIn ();
}
Override
public void loginGPGS () {
try {
runOnUiThread (new Runnable () {
Override
public void run () {
// Initiate user entry. Can be called a dialogue
// Login. Performed in UI-stream
gameHelper.beginUserInitiatedSignIn ();
}
});
} Catch (Exception e) {
e.printStackTrace ();
}
}
Override
public void submitScoreGPGS (int score) {
// Send game points to a specific table records with ID
// "HgkIr62KmoQJEAIQAQ"
Games.Leaderboards.submitScore (gameHelper.getApiClient (),
"HgkIr62KmoQJEAIQAQ", score);
}
Override
public void unlockAchievementGPGS (String achievementId) {
// Open achievement with ID achievementId
Games.Achievements.unlock (gameHelper.getApiClient (), achievementId);
}
Override
public void getLeaderboardGPGS () {
Activity // call for all registered tables records. as
Activity // can call for a specific table
startActivityForResult (
Games.Leaderboards.getAllLeaderboardsIntent (gameHelper
.getApiClient ()), 100);
}
Override
public void getAchievementsGPGS () {
// Call Activity achievements
startActivityForResult (
Games.Achievements.getAchievementsIntent (gameHelper
.getApiClient ()), 101);
}
Override
public void onSignInSucceeded () {
}
Override
public void onSignInFailed () {
}
}
Suppose we have in the game provided the achievement - to collect 1 million. Player points, the code implementing it would look like this:
Code:
public static void checkTotalPoints (int points) {
ActionResolver res = getActionResolver ();
if (! res.getSignedInGPGS ()) {
return;
}
if (points> = 1000000) {
res.unlockAchievementGPGS ("HgkIr62KmoQJEAIQGA");
}
}
Same thing with a table of records, only even easier: you just need to call the submitScoreGPGS (int score) interface ActionResolver.
PS To test gaming services need to export apk-file with the same certificate as in the developer console. Just need to add accounts testers in the console. Changes in gaming services come into effect after a while.
Google Play Clear Sky 2
Long second part released!
sources used
developers.google.com/games/services/android/quickstart
developer.android.com/intl/ru/google/play-services/setup.html
github.com/libgdx/libgdx/wiki
Please don't add the &hl=ru parameter to your Play Store links - then it is in Russian for all users. Without it, native language is used.