passing data from custom adapter to another activity - android

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 :)

Related

Using Text Only Once Through Random Method

I am new to Android. I am showing Text in the TextView on Button click Randomly. On 1st Textview the Heading and on 2nd the explaination of that heading. I am able to show the Heading and Explaination Randomly and now I want if the Text is shown once should not be shown again means it will be removed. This is the point where I stuck. I am not able to remove the texts. Any help will be appreciated. I am posting my code here.
MainActivity.java
TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_heading.get(int_text)); //getting error
text_explain(array_explain.get(int_text)); //getting error
array_heading.remove(int_text); //getting error
array_explain.remove(int_text); //getting error
}
});
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer>array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
}
}
I am not able to remove the texts. Any help will be appreciated. I am
posting my code here.
To clean the content of the TextView you could pass null to setText. E.g
text_heading.setText(null);
If you want to change the content every time you click on the button, you have to move
int_text = random.nextInt(array_heading.length);
your onClick callback,
You should be aware of the fact that next int returns an int between [0, n). array_heading.length -1 is necessary only if you want to exclude R.string.source_text9_explain from the possible texts you want to show. Keep also in mind that if array_heading contains more items than array_explain you could get ArrayIndexOutBoundException
I would keep the strings together in an object:
public class Item {
private final int textId;
private final int textExplanationId;
public class Item(int textId, int textExplanationId){
this.textId = textId;
this.textExplanationId = textExplanationId;
}
public int getTextId(){return textId;}
public int getTextExplanationId(){return textExplanationId;}
}
Then I would store those in an ArrayList:
List<Item> items = new ArrayList<Item>(new Item[]{
new Item(R.string.source_text1, R.string.source_text1_explain),
new Item(R.string.source_text2, R.string.source_text2_explain),
//etc
});
Then I would shuffle that array once:
Collections.shuffle(items);
And read from it in order:
Item current = items.get(currentIndex++);
text_heading.setText(current.getTextId());
text_explain.setText(current.getTextExplanationId());
TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text)); //getting error
text_explain.setText(array_explainList.get(int_text)); //getting error
array_headingList.remove(int_text); //getting error
array_explainList.remove(int_text); //getting error
}
});
}
}
You must use ArrayList for it.
ArrayList<Integer> heading = Arrays.asList(array_heading);
ArrayList<Integer> explain = Arrays.asList(array_explain);
Now set text from this arraylists. And when its set once remove it from the arraylist so it cannot be shown again.
Use like this
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size());
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text));
text_explain.setText(array_explainList.get(int_text));
array_headingList.remove(int_text);
array_explainList.remove(int_text);
if(array_headingList.size() == 0){
click.setEnabled(false);
Toast.makeText(getApplicationContext(),"All text finished",Toast.LENGTH_SHORT).show();
} else if(array_headingList.size() == 1){
int_text = 0;
} else {
int_text = random.nextInt(array_headingList.size());
}
}
});

how do I set up a next and previous button

Hello as the title state I'm trying to setup a next and previous buttons but I'm still new at coding so this has me a little confused.
I tried to use if statements with an enum within a single button but it defaults to last if statement when the event is handled here's the code-
private enum EVENT{
pe1, pe2, pe3, pe4;
}
EVENT currentEvent = EVENT.pe1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentEvent==EVENT.pe1) {
olText.setText("PE1");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe2;
}
if (currentEvent==EVENT.pe2){
olText.setText("PE2");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe3;
}
}
});
}
I tried to use the enumerator to assign a number to each if statement so when the user hit previous it would subtract and when they hit next it would add, each number would have some text or image within its if statement but as I said it defaults to the last if statement- Any help is much appreciated.
How about this?
int eventNum = 0;
int maxEvents = XXX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
prevBtn = (Button) findViewById(R.id.prevBtn);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
setEventData(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(prevBtn) && eventNum > 0) {
eventNum--;
setEventData(false);
return;
}
if(v.equals(nextBtn) && eventNum < maxEvents - 1) {
eventNum++;
setEventData(true);
return;
}
}
}
nextBtn.setOnClickListener(listener);
prevBtn.setOnClickListener(listener);
}
private void setEventData(boolean animLeft) {
olText.setText("PE" + (eventNum + 1));
if(animLeft) {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
} else {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_right));
}
}
You'll want to create a class variable that keeps track of which text your TextView is showing. So in the following example, I create a list of Strings that I just store in a String array. Then I create an iterator variable which stores which String from the list I'm currently viewing in the TextView. Every time you click the previous or next button, you simply store your current state in the iterator variable so you can recall it the next time a click event comes in.
String[] labels = {"one", "two", "three", "four"};
int currentView = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPreviousButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView--; //decrement our iterator
if(currentView < 0) currentView = 0; //check to make sure we didn't go below zero
textView.setText(labels[currentView]);
}
public void onNextButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView++; //increment our iterator
if(currentView > labels.length-1) currentView = labels.length-1; //check to make sure we didn't go outside the array
textView.setText(labels[currentView]);
}

Passing the same object from one activity to another activity

I have a Mainactivity that contains the list of Trainings. And on each list is clicked it starts the session of the same training in whole application.
I managed to use Singleton and access that into my main activity. But onItemClick it takes to dialog box and on button click inside dialog it should take to another activity. Now I a getting error like java NullPointerException. Here is the code below;
Remember: I want same training session in second activity also.
MainActivity class;
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentTraining = (Training)arg0.getAdapter().getItem(arg2);
Log.i("DEBUG", currentTraining.getTitle());
CurrentTraining.getInstance().setTraining(currentTraining);
Toast.makeText(
getApplicationContext(),
"You clicked on position : " + arg2 + " and ID : "
+ currentTraining.getId(), Toast.LENGTH_LONG).show();
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(currentTraining.getTitle());
TextView description = (TextView) dialog.findViewById(R.id.textView1);
description.setText("Description: " + currentTraining.getDescription());
TextView location = (TextView) dialog.findViewById(R.id.textView2);
location.setText("Location: " + currentTraining.getLocation());
TextView date = (TextView) dialog.findViewById(R.id.textView3);
date.setText("Date: " + currentTraining.getDate());
Button back_btn = (Button) dialog.findViewById(R.id.button1);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
Button start_btn = (Button) dialog.findViewById(R.id.button2);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
TraineeActivity.class);
//intent.putExtra("trainingId", currentTraining.getId());
//intent.putExtra("title", currentTraining.getTitle().toString());
MainActivity.this.startActivity(intent);
}
});
dialog.show();
}
And in second Activity Class;
Training currentTraining;
private ListView personNamesListView;
// Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter traineeListAdapter;
private TextView TitleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trainees);
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Log.i("DEBUG", ""+currentTraining.getTitle());
TitleView = (TextView)findViewById(R.id.training_title);
TitleView.setText(currentTraining.getTitle());
Button addnew = (Button) findViewById(R.id.add_btn);
addnew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(TraineeActivity.this,
FormActivity.class);
TraineeActivity.this.startActivity(intent);
}
});
personNamesListView = (ListView) findViewById(R.id.traineeslist);
// Create a list that contains only full name of the trainee
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
protected void onResume(){
super.onResume();
traineeListAdapter = new ArrayAdapter<Trainee>(this, android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
My Singleton Class:
public class CurrentTraining {
private Training training ; //Training is my model class
private static CurrentTraining instance;
private CurrentTraining() {
}
public static CurrentTraining getInstance() {
if (instance == null)
instance = new CurrentTraining();
return instance;
}
public Training getTraining() {
return training;
}
public Training setTraining(Training training) {
return this.training = training;
}
}
In onCreate() of your second activity, you do this:
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Since currentTraining is null, this will just set the singleton variable training to null and return null.
Where are you actually setting the value of the one that the user picked?

Textview onclick() in widget android

we have stored some text in an arraylist. we want to display it in a single textview,when I click the textview the next value(text) in the arraylist should be updated in the widget.
If I understand what you're trying to do correctly, try this out:
public class MyActivity extends Activity {
ArrayList<String> values = new ArrayList<String>();
TextView myText;
private int index;
protected void onCreate(Bundle saved) {
super.onCreate(saved);
setContentView(R.layout.content_layout_id);
index = 0;
//example values:
values.add("foo");
values.add("bar");
values.add("another value");
myText = (TextView) findViewById(R.id.myTextId);
//show the first value on myText
myText.setText(values.get(index));
myText.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Show next value in our text view:
myText.setText(values.get(++index));
//be sure to consider the ArrayList.size() so you won't try to present the 6th value in a 5 values ArrayList.
//but this depends on your implementation.
}
});
}
}

Button to transfer me to next page and start a game

It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(input.getText().toString());
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.

Categories

Resources