Calling method in second activity - android

I'm writing a tip app where the user selects a check, and then on the second activity the subtotal is displayed. However, I'm completely lost on how I display my subtotal. I have a getSubtotal() method but I don't know how to call it.
First Activity
public class TableListActivity extends Activity {
private ListView mListView;
private TableListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_list);
// Find the ListView, create an adapter that reads our list of checks,
// and connect the two
mListView = (ListView)findViewById(R.id.listView);
mAdapter = new TableListAdapter(this, DataStore.CHECKS);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent (TableListActivity.this, PayCheckActivity.class);
intent.putExtra(PayCheckActivity.Extra_check, arg2);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.table_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
// TODO do stuff here
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}}
Second Activity
public class PayCheckActivity extends Activity{
String Thank;
Button Sign;
Button fifteen;
Button eighteen;
Button twenty;
String sample;
public static final String Extra_check= "abc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paycheck);
Sign = (Button)findViewById(R.id.Sign);
fifteen= (Button)findViewById(R.id.fifteen);
eighteen= (Button)findViewById(R.id.eighteen);
twenty= (Button)findViewById(R.id.twenty);
Sign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank You", Toast.LENGTH_LONG);
msg.show();
}});
fifteen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank Yolllllu", Toast.LENGTH_LONG);
msg.show();
}});}}
Check.java
public class Check {
private long id;
private String tableName;
private ArrayList<MenuItem> mItems = new ArrayList<MenuItem>();
private boolean hasBeenSigned = false;
public static class MenuItem {
public String name;
public Amount cost;
public MenuItem(String itemDescription, double cost) {
this.name = itemDescription;
this.cost = new Amount(cost);
}
}
public Check(long id, String tableName) {
this.id = id;
this.tableName = tableName;
}
public long getId() {
return id;
}
#Override
public String toString() {
// The ArrayAdapter uses toString to get the text to display in the list item
// We override toString here to display the table name
return tableName;
}
public void addItem(String itemDescription, double cost) {
mItems.add(new MenuItem(itemDescription, cost));
}
public String getTableName() {
return tableName;
}
public Amount getSubtotal() {
double total = 0;
for (MenuItem item : mItems) {
total += item.cost.getRawValue();
}
return new Amount(total);
}
public void markAsSigned() {
hasBeenSigned = true;
}
public int getItemCount() {
return mItems.size();
}
public MenuItem getMenuItemAt(int index) {
return mItems.get(index);
}}

Just a quick hint: You are sending some data to the second activity via Intent (onItemClick). In the second activity in onCreate, you can pick this data and call your getSubtotal method. Since it's not quite clear, what "Check" does, it's up to you how to instantiate it:
public class PayCheckActivity extends Activity{
// ...
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent != null) {
String value = intent.getStringExtra(PayCheckActivity.Extra_check);
Check check = .....
check.getSubtotal()
}
}
// ...
}

Related

How to save user drawings to SQLite database in another activity?

I have a class extends View and I do my drawings there.I open another activity from menu after I finished my drawing. In second activity, there is editText field for username and there is also a save button. I want to make them saved to my SQLite database, first drawing and then the image related to user. How can I do that ? Now this is my code currently and I'm getting an error.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.example.mydrawingapp.View.AppView.getContext()' on a null object reference
at com.example.mydrawingapp.SecondActivity$1.onClick(SecondActivity.java:31)
My Database Helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "drawingApp.db";
public static final String TABLE_NAME="saveUser";
public static final String COL_1 = "ID";
public static final String COL_2="username";
public static final String COL_3="image";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE saveUser (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,image BLOB)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addImage(String user, byte[] image){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",user);
contentValues.put("image",image);
long res = database.insert("saveUser",null,contentValues);
database.close();
return res;
}
}
This is the code that I have in my Second Activity class:
public class SecondActivity extends AppCompatActivity {
private EditText textUsername;
private Button buttonRegister;
private String username;
private AppView appView;
private DatabaseHelper dbHelper;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textUsername = (EditText) findViewById(R.id.editText);
username = textUsername.getText().toString();
buttonRegister=(Button) findViewById(R.id.saveButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(appView.getContext(),null );
image = appView.saveImage();
dbHelper.addImage(username,image);
}
});
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
private AppView appView;
private AlertDialog.Builder currentAlertDialog;
private ImageView widthImageView;
private AlertDialog dialogLineWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appView = findViewById(R.id.view);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clearId:
appView.clear();
break;
case R.id.saveId:
openLoginDialog();
break;
case R.id.lineWidth:
showLineWidthDialog();
break;
}
return super.onOptionsItemSelected(item);
}
private void openLoginDialog() {
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
}
void showLineWidthDialog() {
currentAlertDialog = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.width_dialog, null);
final SeekBar widthSeekBar = view.findViewById(R.id.widthSeekBar);
Button setLineWidthButton = view.findViewById(R.id.widthDialogButton);
widthImageView = view.findViewById(R.id.imageViewId);
setLineWidthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView.setLineWidth(widthSeekBar.getProgress());
dialogLineWidth.dismiss();
currentAlertDialog = null;
}
});
widthSeekBar.setOnSeekBarChangeListener(widthSeekBarChange);
currentAlertDialog.setView(view);
dialogLineWidth = currentAlertDialog.create();
dialogLineWidth.setTitle("Set Line Width");
dialogLineWidth.show();
}
SeekBar.OnSeekBarChangeListener widthSeekBarChange = new SeekBar.OnSeekBarChangeListener() {
Bitmap bitmap = Bitmap.createBitmap(400, 100, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Paint p = new Paint();
p.setColor(appView.getDrawingColor());
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeWidth(progress);
bitmap.eraseColor(Color.WHITE);
canvas.drawLine(30, 50, 370, 50, p);
widthImageView.setImageBitmap(bitmap);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
}
your context is null so you need initialize that in this way:
public class SecondActivity extends AppCompatActivity {
private EditText textUsername;
private Button buttonRegister;
private String username;
private AppView appView;
private DatabaseHelper dbHelper;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textUsername = (EditText) findViewById(R.id.editText);
username = textUsername.getText().toString();
buttonRegister=(Button) findViewById(R.id.saveButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(SecondActivity.this ,null ); // change this line
image = appView.saveImage();
dbHelper.addImage(username,image);
}
});
}
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(**appView**.getContext(),null );
image = appView.saveImage();
dbHelper.addImage(username,image);
}
appView<-- this is null at the point of click initialize this first

Android RecyclerView does not refresh after insert

I have a problem with my RecyclerView.
I have a ProductDetailActivity which shows the detail of a product and i have a RecyclerView with its adapter in it.
The user can click on the give rating button which navigates to the RatingActivity where you can give a rating to the product.
The problem is that when i submit my rating and automatically go back to my RatingActivity, the RecyclerView does not get the recently added rating. i have to go back to my productlist and reclick on the product to see the recently added rating.
Here is my code:
ProductDetailActivity:
public class ProductDetailActivity extends AppCompatActivity {
public AppDatabase appDatabase;
private static final String DATABASE_NAME = "Database_Shop";
private RecyclerView mRecycleviewRating;
private RatingAdapter mAdapterRating;
private Button btnGoToRatingActivity;
List<Rating> ratings;
Product p;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
btnGoToRatingActivity = findViewById(R.id.btn_goToRatingActivity);
Intent intent = getIntent();
id = intent.getIntExtra("productid", -1);
// pour montrer tous les ratings d'un produit, tu fais un getall
p = appDatabase.productDAO().getProductById(id);
ImageView imageView = findViewById(R.id.imageDetail);
TextView textViewName = findViewById(R.id.txt_nameDetail);
TextView textViewAuthor = findViewById(R.id.txt_authorDetail);
TextView textViewCategory = findViewById(R.id.txt_categoryDetail);
TextView textViewDetail = findViewById(R.id.txt_descriptionDetail);
Picasso.get().load(p.getProductImage()).fit().centerInside().into(imageView);
textViewName.setText(p.getProductName());
textViewAuthor.setText(p.getProductAuthor());
textViewCategory.setText(p.getProductCategory());
textViewDetail.setText(p.getProductDescription());
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
mRecycleviewRating = findViewById(R.id.recyclerRating_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecycleviewRating.setLayoutManager(linearLayoutManager);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapterRating = new RatingAdapter(ratings);
mRecycleviewRating.setAdapter(mAdapterRating);
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
startActivity(i);
}
});
mAdapterRating.notifyDataSetChanged();
}
#Override
public void onResume() {
super.onResume();
ratings = appDatabase.ratingDAO().getRatingByProductId(id); // reload the items from database
mAdapterRating.notifyDataSetChanged();
System.out.println(mAdapterRating.ratings.size());
}
}
RatingActivity:
public class RatingActivity extends AppCompatActivity implements RatingGiveFragment.RatingListener {
RelativeLayout mRelativeLayout;
private Button btnConfirmRating;
private EditText mComment;
private RatingBar mRatingBar;
public AppDatabase appDatabase;
private RatingAdapter mAdapter;
List<Rating> ratings;
private static final String DATABASE_NAME = "Database_Shop";
Product p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
appDatabase = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
int idProduct = RatingActivity.this.getIntent().getIntExtra("productid",-1);
p = appDatabase.productDAO().getProductById(idProduct);
mRatingBar = findViewById(R.id.rating_bar);
mComment = findViewById(R.id.txt_insertOpinionText);
mRelativeLayout = findViewById(R.id.activity_rating);
btnConfirmRating = findViewById(R.id.buttonConfirmRating);
mAdapter = new RatingAdapter(ratings);
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
mAdapter.notifyDataSetChanged();
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
}
/*private class insertRating extends AsyncTask<String,Integer, Integer>
{
#Override
protected Integer doInBackground(String... strings) {
Rating rating = new Rating(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]), Integer.parseInt(strings[2]), strings[3], strings[4]);
appDatabase.ratingDAO().insertRating(rating);
return 1;
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (integer == 1)
{
Toast.makeText(getApplicationContext(), getString(R.string.createRating), Toast.LENGTH_SHORT).show();
}
}
}*/
#Override
public void ratingChanged(int newRating) {
RatingTextFragment textFragment = (RatingTextFragment) getSupportFragmentManager().findFragmentById(R.id.fmt_text);
textFragment.setRating(newRating);
}
private boolean checkEmptyFields(){
if(TextUtils.isEmpty(mComment.getText().toString())){
return true;
}else{
return false;
}
}
}
RatingAdapter:
public class RatingAdapter extends RecyclerView.Adapter<RatingAdapter.RatingViewHolder> {
List<Rating> ratings;
public RatingAdapter(List<Rating> ratings){
this.ratings = ratings;
}
#NonNull
#Override
public RatingViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rating_row,viewGroup, false);
return new RatingViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RatingViewHolder ratingViewHolder, int position) {
ratingViewHolder.ratingUsername.setText(ratings.get(position).getRatingUsername());
ratingViewHolder.ratingNumber.setText(String.valueOf(ratings.get(position).getRatingNumber()) + "/5");
ratingViewHolder.ratingComment.setText(ratings.get(position).getRatingText());
}
#Override
public int getItemCount() {
return ratings.size();
}
public static class RatingViewHolder extends RecyclerView.ViewHolder{
public TextView ratingUsername;
public TextView ratingNumber;
public TextView ratingComment;
public RatingViewHolder(#NonNull View itemView) {
super(itemView);
ratingUsername = itemView.findViewById(R.id.txt_usernamerating);
ratingNumber = itemView.findViewById(R.id.num_rating);
ratingComment = itemView.findViewById(R.id.txt_ratingComment);
}
}
}
Pictures:
You get no update in the ProductDetailActivity because you are not updating the data object ratings in the ProductDetailActivity that is the basis for the RatingAdapter.
It would be better to use startActivityForResult in the onClick()method of the ProductDetailActivity. Then you need to override the onActivityResult() method in the ProductDetailActivity. Evaluate the return values and update your data source if necessary, then call notifyDataSetChanged.
This is just pseudo code!
Changes to ProductDetailActivity:
btnGoToRatingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ProductDetailActivity.this, RatingActivity.class);
i.putExtra("productid", p.getProduct_id());
// with this you are telling the activity to expect results and..
//..to deal with them in onActivityResult
startActivityForResult(i, 1);
}
});
// You do not need this next line because setting the adaper triggers the first
//mAdapterRating.notifyDataSetChanged();
}
Add the onActivityResult() method to the ProductDetailActivity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
// trigger a method to update the data object that is linked to the adapter
ratings = appDatabase.ratingDAO().getRatingByProductId(id);
// and now that the data has actually been updated you can call notifyDataSetChanged!!
mAdapterRating.notifyDataSetChanged();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Probably do nothing or make a Toast "Canceled"??
}
}
}
Changes to RatingActivity:
btnConfirmRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!checkEmptyFields()) {
// I will just assume this works!
Rating rating = new Rating(p.getProduct_id(),UserConnected.connectedUser.getUser_id(),mRatingBar.getRating(), UserConnected.connectedUser.getUsername(), mComment.getText().toString());
appDatabase.ratingDAO().insertRating(rating);
Intent intent = new Intent();
//If you need to return some value.. do it here other you do not need it
//intent.putExtra("result", result);
setResult(Activity.RESULT_OK, intent);
finish();
}else{
Toast.makeText(RatingActivity.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
});
Please be aware in RatingActivity that in btnConfirmRating.setOnClickListener notifying the adapter with mAdapter.notifyDataSetChanged(); does nothing: firstly, because the adapter in the RatingActivity has nothing to do with the adapter in the ProductDetailActivity; secondly: you call finish(); in the next line of code.

Using options in ActionSheet to change Button text

I am trying to develop an UI actionsheet in android. Using dependency:
compile 'com.baoyz.actionsheet:library:1.1.6'
I have developed an actionsheet in android which look like this:
ActionSheet in Android
I am trying to change the button text whenever any option is selected from the actionSheet. The index in the javafile below contains the string position just like array but i am unable to get the string value from that index.
Here is my javafile:
public class billBookInfo extends AppCompatActivity implements ActionSheet.ActionSheetListener{
private Button change;
private String setValue;
private Button vtype;
private Button zone;
Button next;
Button previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bill_book_info);
getSupportActionBar().hide();
vtype = (Button) findViewById(R.id.info_billbook_bt_vtype);
zone = (Button)findViewById(R.id.info_billbook_bt_zone);
}
}
public void onClick(View v){
switch (v.getId()) {
case R.id.info_billbook_bt_vtype:
setTheme(R.style.ActionSheetStyleiOS7);
change = vtype;
showActionSheet1();
break;
case R.id.info_billbook_bt_zone:
setTheme(R.style.ActionSheetStyleiOS7);
showActionSheet2();
change = zone;
break;
}
}
private void showActionSheet1() {
ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles("Motorcycle","Scooter","Car","Van")
.setCancelableOnTouchOutside(true).setListener(this).show();
}
private void showActionSheet2() {
ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles("Me", "Ko", "Sa", "Ja")
.setCancelableOnTouchOutside(true).setListener(this).show();
}
#Override
public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
}
#Override
public void onOtherButtonClick(ActionSheet actionSheet, int index) {
int i = 0;
if ( i == index){
setValue = "".concat(getString(index));
change.setText(setValue);
}
}
}
Why don't you use a variable to store those values.
String vArr[] = new String[]{"Motorcycle","Scooter","Car","Van"};
String dArr[] = new String[]{"Me", "Ko", "Sa", "Ja"};
ActionSheet vSheet, dSheet;
private void showActionSheet1() {
vSheet = ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles(vArr[0],vArr[1],vArr[2],vArr[3])
.setCancelableOnTouchOutside(true).setListener(this).show();
}
private void showActionSheet2() {
dSheet = ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles(dArr[0],dArr[1],dArr[2],dArr[3])
.setCancelableOnTouchOutside(true).setListener(this).show();
}
#Override
public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
}
#Override
public void onOtherButtonClick(ActionSheet actionSheet, int index) {
if ( actionSheet == vSheet){
change.setText(vArr[index]);
}
else{
change.setText(dArr[index]);
}
}

how should use getApplication method in PagerAdapter

I have a problem when I want to use getApplication() for this class, error is take plaaaaaaace...what should I use instead of getApplication() (Becaus I want to use the method of TestClass is named setNamePermit) or how I should setNamePermit() method of test class.
public class CustomSwipeAdapter01 extends PagerAdapter{
private int[] image_Resources = {R.drawable.sample_01,R.drawable.sample_02,R.drawable.sample_03,R.drawable.sample_04,R.drawable.sample_05,R.drawable.sample_06,R.drawable.sample_07};
private Context ctx;
private LayoutInflater layoutInflater;
public TestClass app;
public CustomSwipeAdapter01(Context ctx) {
this.ctx = ctx;
}
#Override
public int getCount() {
return image_Resources.length;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return (view == (RelativeLayout) o);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
layoutInflater=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View item_view=layoutInflater.inflate(R.layout.activity_story01,container,false);
ImageView imageView=(ImageView)item_view.findViewById(R.id.image_view);
TextView textView=(TextView)item_view.findViewById(R.id.image_count);
Button btn_back_story01 = (Button) item_view.findViewById(R.id.btn_back_story01);
imageView.setImageResource(image_Resources[position]);
int itemNo=position+1;
textView.setText(itemNo + "/" + getCount());
container.addView(item_view);
//what should use instead of getApplication() in below line:
app = (TestClass)getApplication();
btn_back_story01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) ctx).finish();
app.setNewPermit(false);
ctx.startActivity(new Intent(ctx, MainStory01.class));
}
});
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout)object);
}
}
Test Class is:
public class TestClass extends Application {
public Boolean getMedia_state() {
return media_state;
}
public void setMedia_state(Boolean media_state) {
this.media_state = media_state;
}
Boolean media_state;
Boolean checkPlaying;
public Boolean getNewPermit() {
return newPermit;
}
public void setNewPermit(Boolean newPermit) {
this.newPermit = newPermit;
}
Boolean newPermit;
MediaPlayer media;
#Override
public void onCreate() {
super.onCreate();
setMedia_state(true);
setNewPermit(true);
media = new MediaPlayer();
media = MediaPlayer.create(getApplicationContext(), R.raw.music);
}
public void musicRestart() {
media = MediaPlayer.create(getApplicationContext(), R.raw.music);
media.start();
media.setLooping(true);
}
public void musicPlay() {
media.start();
media.setLooping(true);
}
public boolean checkPlaying() {
if (media.isPlaying()) {
checkPlaying = true;
} else {
checkPlaying = false;
}
return checkPlaying;
}
public void musicStop() {
media.stop();
}
}
TestClass tc = new TestClass();
Accessing methods in TestClass:
tc.setNewPermit(false);
UPDATE: in your pager adapter, you can now pass any of those values around. For example, change your btn_back_story01 onClick() to:
btn_back_story01.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CustomSwipeAdapter01.this, MainStory01.class);
intent.putExtra("is_new_permit", tc.getNewPermit());
startActivity(intent);
}
});
In MainStory01 activity's onCreate() you can now get the extras passed in your Intent, via Bundle...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
boolean isNewPermit = bundle.getBoolean("is_new_permit");
}
}
There may be some errors in the code, I am not at my work computer at the moment, but this should give you an idea of how to proceed.

public function in class doesn't work properly

I have a "movie" class and a public function getName(), but the function doesn't return anything, and the logcat is just blank.
public class movie {
public String name45;
int dvd_no ;
public void addData( String name1 , int dvd_no1)
{
this.name45=name1 ;
this.dvd_no = dvd_no1 ;
Log.d("constructor name1", name1);
Log.d("constructor name45", name45);
}
public String getName()
{
return name45 ;
}
}
This is an activity which uses this method - the list always has blank entries.
public class MoviesList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.movieslist);
ListView lvAllMoviesList = (ListView)findViewById(R.id.allmovieslist);
ArrayList<String> moviesNames = new ArrayList<String>();
// go through list of members and compare name with given name
for(movie movie : MovieReg_activity.movies) {
String name = movie.getName();
Log.d("Movie Name list", movie.getName());
moviesNames.add(name);
}
ArrayAdapter<String> AllMovieList = new ArrayAdapter<String>(MoviesList.this,android.R.layout.simple_list_item_1, moviesNames);
lvAllMoviesList.setAdapter(AllMovieList);
}
}
the code which generate objects and add values to it
public class MovieReg_activity extends Activity {
public static List<movie> movies = new ArrayList<movie>();
String movName ;
int dvdNo ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mov_reg_layout);
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
EditText etdvd_no = (EditText)findViewById(R.id.etdvds);
Button btMovie_submit = (Button)findViewById(R.id.btmovsubmit);
movName= etmovie_name.getText().toString();
// dvdNo = Integer.parseInt(etdvd_no.getText().toString()); // to string then to int :)
btMovie_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int x=0 ;
movie movie = new movie() ;
movie.addData(movName, dvdNo);
movies.add(x,movie );
x++ ;
int size =movies.size() ;
Toast.makeText(MovieReg_activity.this, "no of movies added :"+size , Toast.LENGTH_SHORT).show();
}
});
}
}
You are setting the TAG parameter for the logs to the first string, try:
Log.d("DEBUG", "constructor name1 " + name1);
Log.d("DEBUG", "constructor name45 " + name45);
And then set your logcat filter to DEBUG
The problem was in taking the data from the user in the MovieReg_activity
and its solved by putting those two lines
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
movName= etmovie_name.getText().toString();
inside the button listener to be like this
public void onClick(View v) {
int x=0 ;
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
movName= etmovie_name.getText().toString();
movies.add(new movie(movName , dvdNo) );
String name3= movie.getName() ;
x++ ;
int size =movies.size() ;
Toast.makeText(MovieReg_activity.this, "no of movies added :"+size , Toast.LENGTH_SHORT).show();
}
});

Categories

Resources