I am developing my first program using Android. It adds or subtracts to a total depending on which button the user clicks. I have made its xml and now I was creating its java but I getting some errors(Its not fully developed yet). I would be helpful if anyone can guide me.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Your Total is 0"
android:gravity="center"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+1"
android:layout_gravity="center"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-1"
android:layout_gravity="center"
android:text="Button" />
</LinearLayout>
Java Source File
package com.fahad.project;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AndroidProject1Activity extends Activity {
/** Called when the activity is first created. */
int numberCount;
Button add, sub;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
numberCount =0;
add=(Button)findViewById(R.id.bAdd);<!--error-->
sub=(Button)findViewById(R.id.bSub);<!--error-->
display=(TextView)findViewById(R.id.tvDisplay);<!--error-->
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
Error
Id is not resolved or is not a field
Please help me out with this error. Thanks.
EDIT
Pasting its .R file,
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.fahad.project;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}
Use the ID values from your XML layout. Try...
add=(Button)findViewById(R.id.button1);
sub=(Button)findViewById(R.id.button2);
You may want to give them more descriptive IDs moving forward!
You haven't given the TextView an ID in your XML, I will leave that one for you to fix :]
Ok! which id do you put in xml layout is generated automatically in R.id class.
for example:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+1"
android:layout_gravity="center"
android:text="Button" />
in this xml Button tag you put android:id="#+id/button1" and id as button1 is automatically added to R.id
And you connect your Button in java code using this id not your own
like this
add=(Button)findViewById(R.id.button1);
You declared buttons ids as "button1" and "button2" but refer to them as "bAdd" and "bSub" which won't work.
If your code doesn't compile even when you corrected the references, do the Right Click on the project -> Refresh and Project->Clean in Eclipse.
If it still doesn't work then you have probably messed up the project setup. Since you are obviously doing some first steps only, just create a new project and copy your code there.
Related
Iam doing an android application. In that i want to create dynamic controls(edittext) like android core contacts application. After entering data in the ediitext i want to save the data to sqlite database by clicking a button named save. As Iam new to android i dont have any idea to create dynamic controls and storing its row values. Please help me if anybody knows.
My code:
package com.xiaochaoyang.dynamicviews;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_container);
mContainerView = (LinearLayout) findViewById(R.id.parentView);
mAddButton = (Button) findViewById(R.id.btnAddNewItem);
// Add some examples
inflateEditRow("Xiaochao");
inflateEditRow("Yang");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// TODO: Handle screen rotation:
// encapsulate information in a parcelable object, and save it
// into the state bundle.
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// TODO: Handle screen rotation:
// restore the saved items and inflate each one with inflateEditRow;
}
// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
// Inflate a new row and hide the button self.
inflateEditRow(null);
//v.setVisibility(View.GONE);
}
// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
// remove the row by calling the getParent on button
mContainerView.removeView((View) v.getParent());
}
// Helper for inflating a row
private void inflateEditRow(String name) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.row, null);
final ImageButton deleteButton = (ImageButton) rowView
.findViewById(R.id.buttonDelete);
final EditText editText = (EditText) rowView
.findViewById(R.id.editText);
if (name != null && !name.isEmpty()) {
editText.setText(name);
} else {
mExclusiveEmptyView = rowView;
//deleteButton.setVisibility(View.INVISIBLE);
}
// A TextWatcher to control the visibility of the "Add new" button and
// handle the exclusive empty view.
editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if (s.toString().isEmpty()) {
//mAddButton.setVisibility(View.GONE);
//deleteButton.setVisibility(View.INVISIBLE);
if (mExclusiveEmptyView != null
&& mExclusiveEmptyView != rowView) {
mContainerView.removeView(mExclusiveEmptyView);
}
mExclusiveEmptyView = rowView;
} else {
if (mExclusiveEmptyView == rowView) {
mExclusiveEmptyView = null;
}
mAddButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
// Inflate at the end of all rows but before the "Add new" button
mContainerView.addView(rowView, mContainerView.getChildCount() );
}
}
My layouts:
Row Cointainer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parentView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical" >
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnAddNewItem"
android:layout_width="21dp"
android:layout_height="wrap_content"
android:background="#drawable/transparent_background"
android:gravity="center_vertical"
android:onClick="onAddNewClicked"
android:layout_gravity="right"
android:paddingLeft="5dp"
android:text="+"
android:textColor="#android:color/black" />
</ScrollView>
</LinearLayout>
Row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/editText"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:singleLine="true"
android:ems="10"
android:hint="" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/spinnerCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.15"
android:entries="#array/categories"
android:gravity="right" />
<ImageButton
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/content_remove"
android:background="#drawable/transparent_background"
android:contentDescription="#string/button_delete_row_description"
android:onClick="onDeleteClicked"/>
</LinearLayout>
First of all, while posting your question in SO, please show what have you tried so far, post your logcat if your app is getting force closed.
To work with controls, please refer to http://developer.android.com/reference/packages.html
There you find the methods available to work with controls.
Check this link: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
It helps to learn and perform CRUD operations on SQLite Database.
At last, what you left with is, get data (or input) from controls, and insert into database.
Also, please go for googling.
I installed the Android SDK bundle today and I am following the "My First App" tutorial and I am stuck, it states:
Open the MainActivity class (located in the project's src/ directory) and add the corresponding method:
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
Where do I put this in the file? and is this the "MainActivity.java" file?
I have tried and I keep getting errors so I am obviously going wrong somewhere.
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
MainActivity.java:
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
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 boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Hope I have made my problem clear, I looked on the forum for an answer but I couldn't find anything.
If you have a button in your(say activity_main.xml) xml layout and you have the below attribute for button
android:onClick="sendMessage"
and you have the below in MainActiivty.java
setContentView(R.layout.activity_main);
You should have the below in MainActivity.java
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
Example:
MainActivity.java
// Your imports
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //setting the layout to activity
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
// other widgets
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="146dp"
android:onClick="sendMessage"
android:text="Button" />
</RelativeLayout>
If you are a new android developer and doing your first so start from basic like launch new activity it contain hello world or any text view, button then you will clear idea about application.
create your android application
in XML layout drag the button and text view
run your first app.
you will get your output.
Put it in MainActivity.java at the top right after
public class MainActivity extends ActionBarActivity {
After you do this, you may have to import. Do this by pressing control / shift / O (not zero)
I surdenly noticed that My project starts throwing error anytime I try to access a resources that is a button. It underlines R.id.button. I dont understand why. I even deleted the last xml that I created but problem persist.
This is an example of my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/layoutborder"
android:orientation="vertical" >
<TextView
android:id="#+id/chat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="#string/stepone"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/wine" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:src="#drawable/ai" />
<Button
android:id="#+id/drugdetails"
style="#style/smallButtonStyleBlackpearl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:text="#string/nextbut" />
</LinearLayout>
My Java code
package com.example.rhemahealthcare;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockActivity;
import com.example.rhemahealthcare.R;
public class SteponeActivity extends SherlockActivity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.steponeactivity);
final Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent intent = new Intent(SteponeActivity.this,SteptwoActivity.class);
startActivity(intent);
}
});
}
}
i think you change any button1 id buy clicking right click and choose edit id. this option changes all the ids with that name in all the layouts.
As #Aleks G gussed it right in the comment, you don't have any button with id as button1 in your xml file. You've mentioned it :
final Button button = (Button)findViewById(R.id.button1);
Use the appropriate ID or put one in your layout file.
I have figured out the problem. My button ids were automatically change to button1 so they did not reference their previous ids that I gave to them. Thanks alot
I've created this simple example to illustrate what i am trying to accomplish.
This is my first layout:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class LifeCycleActivity extends Activity implements OnCheckedChangeListener {
/** Called when the activity is first created. */
private RadioButton rbR, rbG, rbB;
private RadioGroup rg;
private Button next;
int color=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbR = (RadioButton) findViewById(R.id.radio0);
rbB = (RadioButton) findViewById(R.id.radio1);
rbG = (RadioButton) findViewById(R.id.radio2);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
next = (Button) findViewById(R.id.button1);
final Intent it = new Intent(this, next.class);
final Bundle b = new Bundle();
rg.setOnCheckedChangeListener(this);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b.putInt("color", color);
it.putExtras(b);
startActivity(it);
}
});
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (checkedId==rbR.getId()) color=1;
if (checkedId==rbB.getId()) color=2;
if (checkedId==rbG.getId()) color=3;
}
}
This is the second layout:
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.*;
public class next extends Activity {
private LinearLayout ll;
private ImageView im;
private TextView tv;
private Button save;
private Bundle extras;
private int color=0;
private String selColor="";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
ll = (LinearLayout) findViewById(R.id.mainll);
ll.setOrientation(LinearLayout.VERTICAL);
im = new ImageView(this);
tv = new TextView(this);
save = new Button(this);
save.setText("save");
extras = getIntent().getExtras();
color = extras.getInt("color");
im.setImageResource(R.drawable.ic_launcher);
ll.addView(im);
if (color == 1) selColor = "RED";
if (color == 2) selColor = "BLUE";
if (color == 3) selColor = "GREEN";
tv.setText(selColor);
tv.setGravity(Gravity.CENTER);
ll.addView(tv);
ll.addView(save);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// here i want to save and exit
// so i can call onPause(), then finish()
// do not know how exactly since i have to follow some goals
// that i need for this example
}
});
}
}
I also have main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="red" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blue" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="green" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next" />
</LinearLayout>
AND next.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
As you can see, based on color selection in first layout I dynamically build the second layout.
This is what I want to do, help me please (add code if possible):
on the second layout if I press save, I want to save app state (whatever I built on that page) and exit.
If I add one more button to create other dynamic objects on that layout (EditText with name, or another layout with different objects) than if user saves, he/she will also save new objects (This part can be done later)
if user saved that page once then i want him to be able to get the same app state that he/she was in before exiting (of course if he/she selects the same radio button).
If he/she selects another button, i do not need to show that previous state, since the selection is different.
The trick with sharedpreferences did for me. I was finally able to same and retrieve my data onPause and onStart. Even though this worked fine, I appreciate the answer of Kevin_Dingo which is defiantly more professional way to go.
I am taking my first steps in Android and am starting with a very simple app which keeps track of progress through a knitting pattern and shows the instructions for the relevant row.
I want to update a couple of TextView objects programmatically. However, using getViewById() does not seem to identify them properly and the app crashes.
Having searched on Google it seems there are sometimes problems with the XML namespace in the layout XML but mine looks OK. Is it something to do with scope, perhaps?
instructions.java (this is the only activity)
package uk.co.oketchup.blanketsquare;
import android.app.Activity;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.view.View;
public class instructions extends Activity
{
private int mRow;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/* retrieve row from shared preferences, or start from zero if nothing there */
SharedPreferences settings = getPreferences(MODE_PRIVATE);
mRow = settings.getInt("row",0);
setContentView(R.layout.main);
/* associate onClick listeners with the two buttons */
final Button btnIncrement = (Button) findViewById(R.id.increment);
btnIncrement.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Increment row
++mRow;
calcAndUpdate();
}
});
final Button btnDecrement = (Button) findViewById(R.id.decrement);
btnDecrement.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Decrement row
--mRow;
calcAndUpdate();
}
});
}
private void calcAndUpdate() {
String Instructions;
int knit1;
int knit2;
int remaining;
if (mRow%2 == 1 )
{
/* Odd row */
knit1 = 40 - mRow;
Instructions = "K" + knit1;
remaining = knit1;
}
else
{
/* Even row */
knit1 = 18 - mRow/2;
knit2 = knit1 + 1;
Instructions = "Sl 1, k" + knit1 + ", [sl 1 kwise] 2 times, k1, p2sso, k" + knit2;
remaining = knit1 + knit2 + 2;
}
/* Update the display */
TextView tRow = (TextView) findViewById(R.id.row);
TextView tInstr = (TextView) findViewById(R.id.instr);
TextView tStRem = (TextView) findViewById(R.id.stitchremain);
/* Set the text */
tRow.setText(mRow);
tInstr.setText(Instructions);
tStRem.setText(remaining);
}
}
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Row"
/>
<TextView
android:id="#+id/instr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Instructions"
android:layout_below="#id/row"
/>
<Button
android:id="#+id/increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_alignParentBottom="true" />
<Button
android:id="#+id/decrement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:layout_toRightOf="#id/increment"
android:layout_alignParentBottom="true" />
<TextView
android:id="#+id/stitchremain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="stitches remaining"
android:layout_above="#id/increment"
/>
</RelativeLayout>
The TextView objects seem to have been registered ok as they appear in R.java
public static final class id {
public static final int decrement=0x7f050003;
public static final int increment=0x7f050002;
public static final int instr=0x7f050001;
public static final int row=0x7f050000;
public static final int stitchremain=0x7f050004;
}
Here is the error message shown in ddms.
Uncaught handler: thread main exiting due to uncaught exception
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:200)
at android.widget.TextView.setText(TextView.java:2813)
at uk.co.oketchup.blanketsquare.instructions.calcAndUpdate(instructions.java:75)
at uk.co.oketchup.blanketsquare.instructions.access$100(instructions.java:11)
at uk.co.oketchup.blanketsquare.instructions$1.onClick(instructions.java:33)
[etc]
Many thanks for your help.
mRow is an integer. When you call setText(mRow) on line 75, it thinks that you are trying to set the text with a String resource with ID = the value of mRow.
Instead, do:
tRow.setText(Integer.toString(mRow));
You should always convert other values to string before setting it to textview, like
txtX.setText(Integer.toString(intVal));