So i used a editText called "add", when i click on the button he have to insert into a table a title (string) and amount(int) and comments (string) .
the title is like this : String title = add.getText().toString();
But it does not appear in the table .
Plus when i had forgotten the "getText()" it displayed : android.widget.EditText#43e41168 .
I dont know why ...
(Sorry for my bad english, i'm french ^^).
private Table income;
private Table expense;
String title,comment;
int amount;
EditText add;
Button add_btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper helper = new DatabaseHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
expense = new Table(db,helper.TABLE_1);
income = new Table(db,helper.TABLE_2);
add_btn = (Button)findViewById(R.id.add_btn);
add = (EditText)findViewById(R.id.add);
add_btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
title = add.getText().toString();
income.insertTable(title, 100, " test");
expense.insertTable("another title", 50, "blah blah");
}
}
this is the right answer, i had to move the String title from the onCreate to the onClick.
Related
I have a listview which consist of items with prices. My listview also has a Delete button. I also have a textview at the bottom part of the layout which is not part of the listview and it shows the total amount. I can successfully remove the item from my listview. What I want is that when the item is removed, the total amount will also change.
Here is a part of my adapter where i must do some actions
holder.del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(getItem(position));
}
});
and here is my Activity where my textview of amount is found.
public class Cart extends MainActivity {
TextView amount_total;
ListView cartList;
CartCustomAdapter cartCustomAdapter;
String name, price;
static ArrayList<Order> cartArray = new ArrayList<Order>();
static Double total_amount = 0.00d;
static Double temp = 0.00d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
amount_total = (TextView) findViewById(R.id.total_tv);
Bundle bundle = getIntent().getExtras();
Button checkout = (Button) findViewById(R.id.check_out);
Button add_item = (Button) findViewById(R.id.add_item);
name = bundle.getString("i_name");
price = bundle.getString("i_price");
temp = Double.parseDouble(price);
total_amount = (total_amount + temp);
amount_total.setText("Php" + total_amount.toString());
add_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cart.this,MainActivity.class);
startActivity(intent);
}
});
cartList = (ListView) findViewById(R.id.cart_list);
cartCustomAdapter = new CartCustomAdapter(Cart.this,R.layout.list_cart,cartArray);
cartList.setItemsCanFocus(false);
cartList.setAdapter(cartCustomAdapter);
cartArray.add(new Order(name,price,"1"));
cartCustomAdapter.notifyDataSetChanged();
}
}
Define an interface with method like below to update text view in your activity :
updateDeletedItemCount();
and in this method take integer and increase its count like
deletedCount++;
and then update it on text view like this
tvDeletedCount.setText("Deleted Item Count : "+ deletedCount);
This is the easiest way to do that:
//Add a method to your Cart
public void changeTotal(int totalPrice){
if(textView != null) // set total price
}
// Call after remove an item in your listener:
if(getContext() instanceOf Cart){
((Cart)getContext()).changeTotal(newTotalPrice);
}
This is not the best way, but I think it's ok for now :)
I have a problem. I do not know how to call a different class. the code is for a button (when you click the button a message appears in random) so i thought it would be better if i placed it in a different class as i have also used arrays.Now i do not know how to call the class.
This is my code.I want to call "Firstin" inside SecondActivity.
public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//finds textview
final Text Ftext = (Text) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final Text Stext = (Text) findViewById(R.id.textView3);
//finds button view
Button btnView = (Button) findViewById(R.id.button1);
#SuppressWarnings("unused")
Button btnView2 = (Button) findViewById(R.id.button2);
btnView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Answer = mFirst.firstAnswer();
Ftext.setTextContent(Answer);
}
});
this is the class I'm trying to call:
package com.example.insultgenerator;
import java.util.Random;
public class Firstin {
public String firstAnswer(){
String [] mResults={
"its cool",
"we cool",
"im cool",
"he cool",
"she cool"
};
// the button was clicked so replace the answer label with answer
String Answer = "" ;
// the two double is a 'empty string
Random RandomGen = new Random();// telling the program to construct a random generator
int RandomNum= RandomGen.nextInt(mResults.length);
Answer = mResults[RandomNum];
return(Answer);
}
}
You should cast to TextView
final TextViewFtext = (TextView) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final TextViewStext = (TextView) findViewById(R.id.textView3);
then use TextView.setText(...) method:
String Answer = mFirst.firstAnswer();
Ftext.setText(new Firstin().firstAnswer());
}
});
then last call the method from the other class with new Firstin().firstAnswer() which creates a instance of the class and executes the method.
i have two activity files in my code, and the first activity file loads the layout search, and the second file loads layout list. I have a textbox in layout search and enter some text. I want to use this text in my second activity file but i can not reach it since it is in the layout search. How can i do this? Here the first activity file, here there is an EditText item called searchedText, and i want to use it in the second activity file.
public class SearchActivity extends Activity{
public EditText searchedText;
public RadioGroup radioGroup;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
}
public void onStart(){
super.onStart();
searchedText = (EditText) findViewById(R.id.searchText);
Button searchinSearchButton = (Button)findViewById(R.id.searchInSearch);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
searchinSearchButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String searched=searchedText.getText().toString();
Intent myIntent = new Intent(v.getContext(),
SearchListActivity.class);
startActivityForResult(myIntent, 1);
}
});
}
}
And here is the second activity file:
public class SearchListActivity extends Activity{
public DatabaseAdapter db;
public ArrayList<String> myList;
public ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
db = new DatabaseAdapter(this);
myList = new ArrayList<String>();
getContacts();
// Example of retrieving tweets of the user "mashable" and adding them to
myList
/*
ArrayList<Tweet> tweets= new ArrayList<Tweet>();
tweets.addAll(Twitter.getTimeline("mashable", 10));
for(Tweet t: tweets){
myList.add(t.username + ": " + t.message + " Tweet id: "+ t.id);
}
*/
printList();
}
public void printList(){
listview = (ListView)findViewById(R.id.contactcListView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listview.setAdapter(adapter);
}
public void getContacts() {
db.open();
Cursor c = db.getContactbyName("y");
if (c.moveToFirst()) {
do {
DisplayContact(c);
} while (c.moveToNext());
}
db.close();
}
public void DisplayContact(Cursor c) {
String entry = "";
// if you add another attribute to your table, you need to change 3 into x
for (int i=1; i<5;i++){
entry += c.getString(i) + "\n";
}
myList.add(entry);
}
}
In this second activity file, you can see the getContacts() method. There, i search by Cursor c = db.getContactbyName("y"); but instead of "y", i want to search whatever user enters the texbox, whic is in the 1st activity file called searchedText. How can i do this?
Thanks
Send the text as an extra in your Intent when you start your second activity.
searchinSearchButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String searched=searchedText.getText().toString();
Intent myIntent = new Intent(v.getContext(),
SearchListActivity.class);
myIntent.putExtra("SEARCH_STRING",searched);
startActivityForResult(myIntent, 1);
}
});
And in your onCreate get the extra. You could use Intent.getStringExtra(String name)
In other words:
mySearched = getIntent().getStringExtra("SEARCH_STRING");
Just make sure to see if anything is null before using it.
i'm making an Android App and in my activity that follows i execute a query to the database and i take the results. I take the results and make TextViews to the Activity. I want when i click the TextView, to pass to the next Activity the name of the Restaurant i click. The problem with my code is that for all the TextViews it save the name of the last Restaurant. Any ideas? Thank you!
public class ViewRestaurants extends Activity{
String name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_restaurant);
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getSpRestaurants(getIntent().getStringExtra("city"), getIntent().getStringExtra("area"), getIntent().getStringExtra("cuisine"));
View layout = findViewById(R.id.items);
if(c.moveToFirst())
{
do{
name = c.getString(0);
TextView resname = new TextView(this);
TextView res = new TextView(this);
View line = new View(this);
resname.setText(c.getString(0));
resname.setTextColor(Color.RED);
resname.setTextSize(30);
resname.setTypeface(null,Typeface.BOLD);
res.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
res.setText(c.getString(1)+","+c.getString(2)+","+c.getString(3)+"\n"+c.getString(4));
res.setTextSize(20);
res.setTextColor(Color.WHITE);
res.setClickable(true);
res.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("com.mdl.cyrestaurants.guide", "com.mdl.cyrestaurants.guide.RestaurantDetails");
i.putExtra("name",name);
startActivity(i);
}
});
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,2));
line.setBackgroundColor(Color.RED);
((LinearLayout) layout).addView(resname);
((LinearLayout) layout).addView(res);
((LinearLayout) layout).addView(line);
}while (c.moveToNext());
}
db.close();
}
}
You'll need to make your name final within your loop and remove it as a class field in order to use it in the OnClickListener the way you are.
if(c.moveToFirst())
{
do{
final String name = c.getString(0);
//other code ...
res.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("com.mdl.cyrestaurants.guide", "com.mdl.cyrestaurants.guide.RestaurantDetails");
i.putExtra("name",name);
startActivity(i);
}
});
//more code...
}while (c.moveToNext());
}
Try making these changes
String name = c.getString(0);
resname.setText(name);
The reason why it is setting to the last restaurant name is because string is being passed by reference rather than by value as it is an object. Creating a unique string within the scope of the do while loop should solve this.
So basically my app starts out with a TabView, then through the options menu the user selects to add a game to the database. This opens the InputGame class, which accepts a few values, and then it should put them into a database when the user clicks "Submit". It will also go back to the original home view. The app goes back the the home tabs view just fine, bu nothing ever gets added to the database. Am I doing something wrong?
InputGame:
public class InputGame extends Activity {
private EditText gameTitle;
private Spinner consoleSelect;
private Spinner genreSelect;
private Spinner ratingSelect;
private Spinner styleSelect;
private EditText gamePub;
private EditText gameDev;
private EditText gameRegion;
private EditText gamePrice;
private EditText gameRelease;
private DatabaseHelper db = null;
private Cursor constantsCursor=null;
private Button addGame;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inputgame);
db = new DatabaseHelper(this);
constantsCursor = db.getReadableDatabase().rawQuery(
"SELECT _ID, title, console " + "FROM constants ORDER BY title",
null);
/*Hide the scroll bar*/
ScrollView sView = (ScrollView)findViewById(R.id.ScrollInput);
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);
/* Accepts game title */
gameTitle = (EditText) findViewById(R.id.gametitle);
/* Console select*/
consoleSelect = (Spinner) findViewById(R.id.console_select);
ArrayAdapter<CharSequence> consoleAdapter = ArrayAdapter.createFromResource(
this, R.array.consoles_array, android.R.layout.simple_spinner_item);
consoleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
consoleSelect.setAdapter(consoleAdapter);
/* Genre select*/
genreSelect = (Spinner) findViewById(R.id.genre_select);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
this, R.array.genres_array, android.R.layout.simple_spinner_item);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
genreSelect.setAdapter(genreAdapter);
/* Style select*/
styleSelect = (Spinner) findViewById(R.id.style_select);
ArrayAdapter<CharSequence> styleAdapter = ArrayAdapter.createFromResource(
this, R.array.style_array, android.R.layout.simple_spinner_item);
styleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
styleSelect.setAdapter(styleAdapter);
/* Rating select*/
ratingSelect = (Spinner) findViewById(R.id.rating_select);
ArrayAdapter<CharSequence> ratingAdapter = ArrayAdapter.createFromResource(
this, R.array.ratings_array, android.R.layout.simple_spinner_item);
ratingAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ratingSelect.setAdapter(ratingAdapter);
/* Accepts game publisher */
gamePub = (EditText) findViewById(R.id.gamepublisher);
/* Accepts game developer */
gameDev = (EditText) findViewById(R.id.gamedev);
/* Release date selector */
gameRelease = (EditText) findViewById(R.id.gamerelease);
/* Add the game button */
this.addGame = (Button)this.findViewById(R.id.addgame);
this.addGame.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
processAdd();
}
});
}
private void processAdd(){
ContentValues values=new ContentValues(8);
values.put("title", getGameTitle());
values.put("console", getGameConsole());
values.put("genre", getGameGenre());
values.put("style", getGameStyle());
values.put("rating", getGameRating());
values.put("publisher", getGamePublisher());
values.put("developer", getGameDeveloper());
values.put("release", getGameRelease());
db.getWritableDatabase().insert("constants", "title", values);
constantsCursor.requery();
Intent launchgamesActivity = new Intent(this, GCM.class);
startActivity(launchgamesActivity);
}
public String getGameTitle(){
return(gameTitle.getText().toString());
}
public String getGameConsole(){
return (consoleSelect.getContext().toString());
}
public String getGameGenre(){
return(genreSelect.getContext().toString());
}
public String getGameStyle(){
return(styleSelect.getContext().toString());
}
public String getGameRating(){
return(ratingSelect.getContext().toString());
}
public String getGamePublisher(){
return(gamePub.getText().toString());
}
public String getGameDeveloper(){
return(gameDev.getText().toString());
}
public String getGameRelease(){
return(gameRelease.getText().toString());
}}
and here is my database helper. The records I have pre-programmed in show up just fine:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "gameDb";
public static final String TITLE="title";
public static final String CONSOLE="console";
public static final String GENRE="genre";
public static final String RATING="rating";
public static final String PUBLISHER="publisher";
public static final String DEVELOPER="developer";
// public STATIC FINAL STRING REGION="REGION";
public static final String PRICE="price";
public static final String RELEASE="release";
public static final String COMPLETION="completion";
public static final String DESCRIPION="description";
public static final String IMAGE="image";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db
.execSQL("CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, console TEXT, genre TEXT, " +
"rating TEXT, publisher TEXT, developer TEXT, region TEXT, price REAL, release BLOB, completion BLOB, description BLOB, image BLOB);");
ContentValues cv = new ContentValues();
cv.put(TITLE, "Super Mario Galaxy");
cv.put(CONSOLE, "Wii");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "Transformers: War for Cybertron");
cv.put(CONSOLE, "Xbox 360");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "Final Fantasy XIII");
cv.put(CONSOLE, "Playstation 3");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "Final Fantasy VII");
cv.put(CONSOLE, "Playstation");
db.insert("constants", TITLE, cv);
cv.put(TITLE, "New Super Mario Bros");
cv.put(CONSOLE, "Nintendo DS");
db.insert("constants", TITLE, cv);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.w("Constants",
"Upgrading database, which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS constants");
onCreate(db);
}
}
EDIT: When submitting from InputGames, should I be closing that activity all together? I think the way I have it set now just goes back to the other activity, but nothing really gets done. Or is that not it at all?
EDIT #2 Well I got it to add. For some reason I have to use .execSQL. Thats fine I guess, but bow when I try to add from a spinner item in InputGames, I get this populating the respective element:
com.jvavrik.gcm.InputGame#43bb0510
were the number after the "#" is always different. Any ideas for this?
What if you change this:
db.getWritableDatabase().insert("constants", "title", values);
to this:
db.getWritableDatabase().insert("constants", null, values);