Android checkbox checked one variable - java

I have a many checkbox and I saved in a String if it's checked like this:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " " + etiquetas;
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " " + etiquetas;
}
But when I need in another Activity put the checkbox checked, idk how to checked because I saved in one. I really need to be like this in one variable, because they're instructions for the exam. And thas's my code for the other Activity;
Intent intent = getIntent();
if(intent != null){
String juice_2 = (String) getIntent().getStringExtra("EXTRA_JUICE");
//apple.setChecked();
}

In the current activity, you can use a single String that has multiple juice words separated by a SPACE character.
And at the destination activity, split the string into an array of strings based on the SPACE character, and then set the checkBox value if this array contains your specific juice.
at Activity A:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " ";
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " ";
}
// Going to Activity B
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("JUICE", juice);
startActivity(intent);
at Activity B:
if (getIntent() != null) {
String juice = getIntent().getStringExtra("JUICE");
if (juice != null) {
String[] splittedJuice = juice.split(" ");
ArrayList list = new ArrayList();
// Convert array into a List
Collections.addAll(list, oldLines);
// Check if the list contains "orange"
if (list1.contains("orange")) {
orange.setChecked(true);
}
if (list1.contains("apple")) {
apple.setChecked(true);
}
}
}

To pass data from one activity to another you can use Intent.putExtra().
The line will look something like this:
intent.putExtra(LABEL, juice);
where: LABEL is a String which allows second activity to find your variable,
juice is your variable.
To resolve the problem you can use something like this:
public class First extends AppCompatActivity {
private final static String LABEL = "juices";
String juice;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
final CheckBox apple = (CheckBox) findViewById(R.id.apple);
Button nextIntent = (Button) findViewById(R.id.next);
nextIntent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (apple.isChecked()) {
juice = apple.getText().toString();
}
Intent intent = new Intent(getApplicationContext(), Second.class);
intent.putExtra(LABEL, juice);
startActivity(intent);
}
});
}
}
Second Activity:
public class Second extends AppCompatActivity {
private final static String LABEL = "juices";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Intent intent = getIntent();
String dataReceived = intent.getStringExtra(LABEL);
System.out.println("Your string: " + dataReceived);
}
}
Anyway, I would recommend that you pass Boolean values to the next activity without converting them to a String if it's only to check/uncheck Checkboxes in the second layout.
If you have a lot of variables in the first activity you can pass them to the array, send it to the another activity (by the similar way) and iterate to check/uncheck boxes.

Related

Passing Data from multiple activities to one activity

I have created three different activities with three different ListViews similar to this and created another activity with a Button.
The purpose is to select any item from any ListView and it will change the Button text to the selected item I choose.
Here is the code I use to create the ListViews:
public class C_Camera extends AppCompatActivity {
ListView listView_C_Camera;
String[] listview_c_camera = new String[]{
"a" , "b", "c", "d" , "e" , "f","g", "h","i","j"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c__camera);
listView_C_Camera = findViewById(R.id.listview_c_camera);
ArrayAdapter<String> CanonCamera = new ArrayAdapter<>(this , R.layout.listview_row,listview_c_camera);
listView_C_Camera.setAdapter(CanonCamera);
listView_C_Camera.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String C_Camera_Temp = listview_c_camera[position];
Intent intent = new Intent(C_Camera.this, BuildCamera.class);
intent.putExtra("C_Camera",C_Camera_Temp);
startActivity(intent);
}
});
}
}
I have another activity with a Button that will get the values of the three different ListViews.
public class BuildCamera extends AppCompatActivity {
Button camerabuild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_build_camera);
camerabuild = findViewById(R.id.camerabuild);
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
camerabuild.setText(S_Camera_Holder);
...
Here I'm facing a problem.
If I use String C_Camera_Holder = getIntent().getStringExtra("C_Camera") and comment the others it will work and change the text,
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
// String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
// String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
// camerabuild.setText(N_Camera_Holder);
// camerabuild.setText(S_Camera_Holder);
but if I uncomment the second one (String N_Camera_Holder = getIntent().getStringExtra("N_Camera")) the first one will stop changing the text and the second will do and so on.
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
// String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
// camerabuild.setText(S_Camera_Holder);
the button will always carry the last setText() function that you call.
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
camerabuild.setText(S_Camera_Holder); <<----------which is, this one.
to make it dynamic on your activity intents you can use if statement.
like this
if(C_Camera_Holder != null){
camerabuild.setText(C_Camera_Holder);
}else if(N_Camera_Holder != null){
camerabuild.setText(N_Camera_Holder);
}else if(S_Camera_Holder != null){
camerabuild.setText(S_Camera_Holder);
}

Add values to ArrayList from different activity

I'm trying to create an app like shopping cart
Using this to access my database http://www.tutecentral.com/restful-api-for-android-part-2/
And i'm stuck at adding products to cart, so far I understand that the selected products go to arraylist in a few tutorials. In the code below I have two Activities, the MaterialView (this shows the details of the materials and has the option to add to cart), and the MaterialCart (shows the list of selected products.)
this is the block of code in MaterialView to send the values to MaterialCart
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
Intent i=new Intent(MaterialView.this, MaterialCart.class);
i.putExtra("mID", mid);
i.putExtra("name", Name.getText().toString());
i.putExtra("qty", Qty.getText().toString());
i.putExtra("price", Price.getText().toString());
i.putExtra("stock", Stock.getText().toString());
i.putExtra("rqQty", RqQty.getText().toString());
startActivity(i);
Toast.makeText(MaterialView.this, "Added Succesfully.", Toast.LENGTH_LONG).show();
}
} );
I have used Intent to pass the values (I'm pretty sure this method is wrong, I also tried calling the MaterialCart class itself to access the arrayList so I can add values and it didn't work)
This is the block of codes in my MaterialCart to receive the values
public class MaterialCart extends Activity {
final ArrayList<PropertyCartTable> materialProperties = new ArrayList<>();
#SuppressLint("LongLogTag")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_material_cart);
Intent i = new Intent();
Bundle extras = getIntent().getExtras();
try{
String Name = extras.getString("name");
String Qty = extras.getString("qty");
String Price = extras.getString("price");
String Stock = extras.getString("stock");
String RqQty = extras.getString("rqQty");
String ID = extras.getString("mID");
Log.d("EXTRAS:", Name + " " + Qty + " " + ID);
materialProperties.add(new PropertyCartTable( ID,Name,Qty,Price,Stock,RqQty));
getIntent().removeExtra("Name");
getIntent().removeExtra("Qty");
getIntent().removeExtra("Price");
getIntent().removeExtra("Stock");
getIntent().removeExtra("RqQty");
getIntent().removeExtra("MID");
}
catch (Exception h){
Log.d("Exception!",h.toString());
}
// materialProperties.add(array);
Log.d("MaterialView.Cart isEmpty", String.valueOf(materialProperties.isEmpty()));
if(materialProperties.isEmpty()) {
Toast.makeText(this, "You have no materials to request.", Toast.LENGTH_LONG).show();
i = new Intent(MaterialCart.this, ProductDetails.class);
startActivity(i);
}else{
ArrayAdapter<PropertyCartTable> adapter = new propertyArrayAdapter(this, 0, materialProperties);
ListView listView = (ListView) findViewById(R.id.lv_materialcart);
listView.setAdapter(adapter);
}
}
The codes work for receiving the values, but when I go back to the materialView (or choose another product) the ArrayList doesn't append the values.
What I'm trying to achieve here is to add the values from the MaterialView (even if the user adds many prodducts) to MaterialCart's ArrayList.
You can let your Application contain the data:
public class MyApp extends Application {
private static List<String> data = new ArrayList<>();
public static void addItem(String item) {
data.add(item);
}
public static List<String> getData() {
return data;
}
}
And when button is clicked:
ButtonAdd.setOnClickListener(new View.OnClickListener(){
public void onClick (View view){
MyApp.addItem(your item);
Intent i=new Intent(MaterialView.this, MaterialCart.class);
startActivity(i);
}
} );
And in MaterialCart.class:
List<String> data = MyApp.getData();
But remember:data will be clear when app is closed.And if you want save it locally,you need to use SharedPreferences

Getting text of buttons from an Activity and setting it as text in Text View in other Activity

I m working on a project i have two categories Cricketers and Animals on one activity as Button and a Text View on other activity i want to change the text of Text View when ever i presses the Button i.e If Cricketer then set text to cricketer same goes for animal.
OnClick Listner for both buttons: On Activity 1
public void onClickcricketer(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btncricket);
String crickettext = b.getText().toString();
i.putExtra("Cricket",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btnanimal);
String animaltext = b.getText().toString();
i.putExtra("Animal",animaltext);
startActivity(i);
}
Code on Activity 2:
Bundle cricketData = getIntent().getExtras();
if (cricketData == null){
return;
}
String Cricket = cricketData.getString("Cricket");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
Bundle AnimalData = getIntent().getExtras();
if (AnimalData == null){
return;
}
String Animal = AnimalData.getString("Animal");
final TextView a = (TextView)findViewById(R.id.txtCategryShow);
a.setText(Animal);
This method just show animal text in Text view.. when i click Crcketer button it shows nothing
First perform an onClick method:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String toExtra = "" + btn.getText();
Intent i = new Intent(this,NextActivity.class);
i.putExtra("key",toExtra);
}
});
then in the new Activity OnCreate method add:
Intent i = getIntent();
String fromExtra = intent.getStringExtra("key");
and finally setText to your TextView:
txt.setText(fromExtra)
It is doing correct, see your code again, On same TextView you are setting text Animal which is null in case of clicking cricket ..
Try this in second activity:
String Cricket = getIntent().getStringExtra("KEY");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
And make your methods like this:
public void onClickcricketer(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_cricket);
String crickettext = b.getText().toString();
i.putExtra("KEY",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_animal);
String animaltext = b.getText().toString();
i.putExtra("KEY", animaltext);
startActivity(i);
}

NumberFormatException in Android

I'm making an application in which the user can add Store departments and for those departments the ability to add the cities of where the departments are located.
I keep on getting a NumberFormatException when I'm trying to add a city for a departement:
Caused by: java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:124)
at java.lang.Long.parseLong(Long.java:345)
at java.lang.Long.parseLong(Long.java:321)
at org.hello.addgroups.vestiging_list.onCreate(vestiging_list.java:45)
after this the app crashes but when I restart the app the values are added into the list.
these are my classes:
Add_vestiging.java:
public class Add_vestiging extends Activity implements View.OnClickListener{
EditText et,hiddenet;
Button add_bt, cancel_btn;
SQLController dbcon;
Intent i;
Long groupd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_vestiging);
et = (EditText)findViewById(R.id.vestigingName);
add_bt = (Button) findViewById(R.id.addBtn);
cancel_btn = (Button) findViewById(R.id.cancelBtn);
dbcon = new SQLController(this);
try {
dbcon.open();
} catch(SQLException e) {
e.printStackTrace();
}
i = getIntent();
String id = i.getStringExtra("groupID");
groupd = Long.parseLong(id);
add_bt.setOnClickListener(this);
cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
startActivity(main);
break;
case R.id.cancelBtn:
super.finish();
break;
}
}
}
vestiging_list.java:
public class vestiging_list extends Activity {
ListView lv;
SQLController dbcon;
TextView title;
Button addves;
Long long_id;
String groupid;
Intent add_ves;
String groupname;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vestiging_list);
dbcon = new SQLController(this);
title = (TextView) findViewById(R.id.vestitel);
try {
dbcon.open();
} catch (SQLException e) {
e.printStackTrace();
}
add_ves = getIntent();
groupid = add_ves.getStringExtra("groupID");
groupname = add_ves.getStringExtra("groupName");
title.setText(groupname);
long_id = Long.parseLong(groupid);
addves = (Button)findViewById(R.id.addves_bt_id);
lv = (ListView)findViewById(R.id.vestigingList_id);
addves.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add_ves = new Intent(getApplicationContext(), Add_vestiging.class);
add_ves.putExtra("groupID", groupid);
startActivity(add_ves);
}
});
Cursor cursor = dbcon.readVestigingen(long_id);
String[] from = new String[] { GroupDatabaseHelper.V_ID, GroupDatabaseHelper.VESNAME};
int[] to = new int [] { R.id.vesID, R.id.vesName};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(vestiging_list.this, R.layout.vestiging_single_row_item, cursor, from, to,1);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
Any ideas on how to remove the NumberFormatException?
Any help is greatly appreciated.
Thanks in advance.
Any ideas on how to remove the NumberFormatException?
The exception is caused by Long.parseLong in vestiging_list at line 45. The reason is that groupid, in your case in null. Since you didn't fill up the Intent object you used to start vestiging_list.
E.g.
case R.id.addBtn:
String name = et.getText().toString();
try {
dbcon.insertVestiging(groupd, name);
}catch(SQLiteException e) {
e.printStackTrace();
}
Intent main = new Intent(Add_vestiging.this, vestiging_list.class);
main.putExtra("groupID", String.valueOf(groupd));
startActivity(main);
break;
assuming that groupd is a long.
I think problem is in the following line :
int[] to = new int [] { R.id.vesID, R.id.vesName};
What is the type of "R.id.vesName" ?. It should be integer.
From the stack trace that you have provided I can assume that groupId is null:
groupid = add_ves.getStringExtra("groupID");
...
long_id = Long.parseLong(groupid);
According to the Long's Javadoc Long#parseLong(String) throws an Exception if the argument is not a parsable Long, sth which is the case with null.
Check if groupid can be null else you have a bug. If it can be null then check if it equals null and then set long_id to an appropriate value e.g. 0 or -1.
It looks to me like you're creating an Intent, but you're not passing the info to the intent. The class reference to the current class is just a trace, and doesn't include info.
When you make the Intent in the Add_vestiging class, in onClick, do something like main.putExtra("groupID", id).
Looks like you're putting it in the SQLController, so you could try passing that as well.

String is null while obtaining from another class using getIntent

Right now I am have a activity screen with edittext lines that I am obtaining user input from. When I hit the create event button on the button, the event text should populate into a news feed that I have on another activity.
Here is the portion CreateEvent activity/screen code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_event);
CreateEvent_Button = (Button)findViewById(R.id.create_event_button);
WhatEvent_Text = (EditText)findViewById(R.id.what_event);
WhenEventTime_Text = (EditText)findViewById(R.id.time_event);
WhenEventDate_Text = (EditText)findViewById(R.id.date_event);
WhereEvent_Text = (EditText)findViewById(R.id.where_event);
CreateEvent_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WhatEvent_String = WhatEvent_Text.getText().toString();
WhenEventTime_String = WhenEventTime_Text.getText().toString();
WhenEventDate_String = WhenEventDate_Text.getText().toString();
WhereEvent_String = WhereEvent_Text.getText().toString();
Log.e("What: ", WhatEvent_String);
Log.e("When_Time: ", WhenEventTime_String);
Log.e("When_Date: ", WhenEventDate_String);
Log.e("Where_Event: ", WhereEvent_String);
Intent intent = new Intent(CreateEvent.this,MainActivity.class);
intent.putExtra("WhatEvent_String", WhatEvent_String);
intent.putExtra("WhenEventTime_String", WhenEventTime_String);
intent.putExtra("WhenEventDate_String", WhenEventDate_String);
intent.putExtra("WhereEvent_String", WhereEvent_String);
startActivity(intent);
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
}
});
}
When the create event button is pressed, it creates an event into the MainActivity screen/activity; however, the user input is null. I am not sure why this is happening because I believe I am using the intent methods correctly.
Here is my MainActivity screen.
Here is the getIntent method in my onCreate method in my MainActivity
Intent intent = getIntent();
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
However, when I call my addEvent method:
protected void addEvent() {
// Instantiate a new "row" view.
// final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.list_row, mContainerView, false);
// Set the text in the new row to a random country.
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
//mContainerView.addView(newView, 0);
HitupEvent hitupEvent = new HitupEvent();
hitupEvent.setTitle("Rohit "+ "wants to "+test );
hitupEvent.setThumbnailUrl(roro_photo);
//hitupEvent.setRating(30);
//hitupEvent.setYear(1995);
//hitupEvent.setThumbnailUrl(null);
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
hitupEvent.setGenre(singleAddress);
hitupEventList.add(hitupEvent);
adapter.notifyDataSetChanged();
}
The event input text is null. I am not sure why this is happening.
I tried to resolve it but no luck,
How to send string from one activity to another?
Pass a String from one Activity to another Activity in Android
Any idea as for how to resolve this?!
Thanks!
Don't use Intent to get the String you put through putExtra()
Intent intent = getIntent(); // don't use this
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
Instead Use Bundle, an example snippet
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
EDIT
I noticed just now that you're calling the method main.addEvent() from the wrong place ! Call it in the MainActivity in the onCreate() method.
Remove these lines
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
and in your MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
addEvent(); // call your addEvent() method here
}

Categories

Resources