`public class GPA extends Activity{
private Spinner GradeSpinner1;
private TextView Total1;
private EditText EditCH1;
double chEntered;
double totalPoints;
String grade;
String groupChoice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpa);
groupChoice = GradeSpinner1.getSelectedItem().toString();
GradeSpinner1 = (Spinner) findViewById(R.id.spGP1);
Total1 = (TextView) findViewById(R.id.editTotal1);
EditCH1 = (EditText) findViewById(R.id.editCH1);
List<String> list = new ArrayList<String>();
list.add("--SELECT--");
list.add("A+");
list.add("A");
list.add("A-");
list.add("B+");
list.add("B");
list.add("B-");
list.add("C+");
list.add("C");
list.add("C-");
list.add("D+");
list.add("D");
list.add("F");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
GradeSpinner1.setAdapter(dataAdapter);
setUpListeners();
}
private void setUpListeners() {
GradeSpinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String credit = (EditCH1.getText().toString());
Double chEntered = Double.parseDouble(credit);
if(grade.equals("A")){
Double editTotal1 = chEntered * 4.00;
Total1.setText(editTotal1.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
`I want to do if/else statement for spinner and edit text. This is what I have done. No errors bt cnt run. Here is my java code.Can anyone help me? Please. thank you in advance.
Don´t know where the problem is, You have to add the stacktrace. But Your code has to be reformed inside onItemSelected:
String grade = parent.getItemAtPosition(pos).getText().toString(); //first mistake
String editTextText = EditCH1.getText().toString();
//check if String is null or empty before parsing. otherwise You will get an error if it is null or empty
if(editTextText!=null && !editTextText.equals("")){
chEntered = Double.parseDouble(editTextText);
}
if(grade.equals("A")){
totalPoints = chEntered*4.0;
String points = Double.toString(totalPoints);
Total1.setText(points);
}
}
And Your EditText should have input Type in xml layout android:inputType="numberDecimal"
Another simple test if the String is a digit is to check with TextUtils:
boolean digitOnly = android.text.TextUtils.isDigitsOnly(editTextText);
But maybe this doesn´t work on decimal numbers. There is a very simple solution:
private boolean isNumber(String numStr)
{
try
{
double d = Double.parseDouble(numStr);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
And Your "App has stopped" description could be caused from EVERYTHING!. There are so many possibillities....It´s important to see Your stacktrace and You have to post a part of code instead of link to a picture please.
Related
Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method
I'm Very new to Java and android... I'm Try to create an ListView using BaseAdapter List being created successfully i have a EditText along with button for each list item but the real problem is when i put some data into editText Field and scroll down to change value of last list item then i go back to the top it refreshes the data to default value it doesn't contain the value which was entered by user before scrolling down
My BaseAdaper Code
class CoustomAdptr extends BaseAdapter{
String[] dates;
Integer[] inventory;
Integer totalrooms;
public CoustomAdptr(RoomFragment roomFragment, String[] dates, Integer[] inventory, Integer totalrooms) {
this.dates = dates;
this.inventory = inventory;
this.totalrooms = totalrooms;
}
#Override
public int getCount() {
return dates.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.inventory_listview,null);
TextView textView = (TextView) view.findViewById(R.id.roomListViewText);
final EditText editText = (EditText) view.findViewById(R.id.roomListInventory);
final Button updateButton = (Button) view.findViewById(R.id.roomListViewInventoryUpdateButton);
if(inventory[i] == 0){
editText.setBackgroundColor(getResources().getColor(R.color.SoldOut));
editText.setTextColor(getResources().getColor(R.color.SoldOutTextColor));
} else if(inventory[i] < totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.invetory));
editText.setTextColor(getResources().getColor(R.color.invetoryTextColor));
} else if(inventory[i] == totalrooms){
editText.setBackgroundColor(getResources().getColor(R.color.fullInventory));
editText.setTextColor(getResources().getColor(R.color.fullInventoryTextColor));
}
editText.setText(String.valueOf(inventory[i]));
textView.setText(dates[i]);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String name = editText.getText().toString();
//String name1 = dates[i];
//String name2 = getArguments().getString("room_id");
updateButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_done_black_24dp,0,0,0);
//updateButton.setBackgroundColor(getResources().getColor(R.color.SoldOut));
updateButton.setText("Updated");
updateButton.setEnabled(false);
Toast.makeText(getContext(), "Update Inventory Button Clicked", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
This is How Im Passing Data to My Adapter
JSONObject jObj = parentObject.getJSONObject("success");
JSONObject jObj2 = jObj.getJSONObject("data");
JSONArray arrajson = jObj2.getJSONArray("inventories");
String arrayCount = Integer.toString(arrajson.length());
String[] dates = new String[arrajson.length()];
Integer[] inventory = new Integer[arrajson.length()];
Integer totalrooms = new Integer(jObj2.getInt("total_room"));
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
dates[i] = jsonObject.getString("date");
inventory[i] = jsonObject.getInt("inventory");
}
CoustomAdptr coustomAdptr = new CoustomAdptr(RoomFragment.this,dates,inventory,totalrooms);
listView.setAdapter(coustomAdptr);
Help Needed :- I Want to retain same visible and Value of edittext as users enters on scroll up or down... i hope i was able to explain my problem clearly
After clicking a button, save it's state in a boolean array or somewhere else. And inside getView method, check if this button was previously clicked or not then setup your view accordingly.
It would be better if you create a model class for rows.
I have a spinner(dynamic) which contains a list of IDs' and each ID has a product value. When I click on a particular ID, the value needs to be changed associated with that ID.
I have a listView which contains a table. The table consists of product names, product price and product information. When I change the ID, the table information(listview) changes but not the product value (this is a textview and not part of listview).
I'm passing the product value using an intent from a different class. How do I make it such that when I change an item in the spinner, the product value gets changed?
/**
* Listener for flight leg selection of spinner
*/
private OnItemSelectedListener onFlightLegSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
new ShowSalesReportAsyncTask(flightLegMap.get(flightLegs.get(position)), position).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing
}
};
This is my onCreate where I am getting the product value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_report);
salesReportListView = (ListView) findViewById(R.id.sales_report_listview);
spinnerFlightLegs = (Spinner) findViewById(R.id.flight_legs);
noTransactionsWarning = (TextView) findViewById(R.id.no_transactions_warning);
totalValueNetAmount = (TextView) findViewById(R.id.total_currency_net_value);
String salesRevenue = TOTAL_VALUE;
Bundle extras = getIntent().getExtras();
if (extras != null) {
salesRevenue = extras.getString(TOTAL_VALUE);
}
totalValueNetAmount.setText(salesRevenue);
flightLegMap = getAllFlightLegs();
if (!flightLegMap.isEmpty()) {
setFlightLegSpinner();
btnShare.setEnabled(true);
} else {
btnShare.setEnabled(false);
}
spinnerFlightLegs.setOnItemSelectedListener(onFlightLegSelectedListener);
salesReportListAdapter = new SalesReportListAdapter(this);
salesReportListView.setAdapter(salesReportListAdapter);
This is the Async task that I use to populate the view with data.
private class ShowSalesReportAsyncTask extends AsyncTask> {
private String flightLeg;
private int position;
public ShowSalesReportAsyncTask(String flightLeg, int position) {
this.flightLeg = flightLeg;
this.position = position;
}
#Override
protected List<Purchase> doInBackground(Void... params) {
List<Purchase> rows = new ArrayList<Purchase>();
PurchaseDao purchaseDao = new PurchaseDao(flightLeg, MIUtils.getShardDatabaseIndexMap());
LOG.debug(TAG + "Getting report for : {}", flightLeg);
// double netTotal = SalesUtil.calculateFlightTransactionTotal(purchaseDao, refundDao,());
return purchaseDao.getSuccessfulTransactions();
}
#Override
protected void onPostExecute(List<Purchase> result) {
super.onPostExecute(result);
if (!result.isEmpty()) {
noTransactionsWarning.setVisibility(View.GONE);
} else {
noTransactionsWarning.setVisibility(View.VISIBLE);
}
salesReportListAdapter.setRowsAndFlightDetails(result, flightLegMap.get(flightLegs.get(position)),
spinnerFlightLegs.getSelectedItem().toString());
totalValueNetAmount.setText((int) netTotal);
}
}
The item that needs to be changed is "EUR". SPINNER TABLE IMAGE
Add the code to register the listener in the onStart() method of the activity. This should work.
This should better answer your question - How to keep onItemSelected from firing off on a newly instantiated Spinner?
I am trying to get data from server into spinner, my json object is
{"result":{"AndhrPradesh":["Jayamahal","ABC","JP nagar"],"Mumbai":["XYZ","PQR"],"Pune":["123","Hi"]}}
I am able to get the values AndhraPradesh,Mumbai and Pune in one spinner. now my problem is after selecting city i want to display corresponding data in that city.
for example, if select Mumbai from one spinner i want to display XYZ,PQR in another spinner, Please help me.
First of all parse the json data like
JSONObject jsonObject = response.getJSONObject("data");
JSONArray cityName= jsonObject.getJSONArray("AndhrPradesh")
for(i=0;i<cityName.length();i++){
//your inner string of the Array
}
Then
citynameSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//here set the values to another spinner
}
});
Please use this code snippet
public class SpinnerFilterActivity extends AppCompatActivity {
private ArrayAdapter<String> mArrayAdapter;
private Spinner mMainSPN;
private ArrayList<String> mSpinnerArray;
private Map<String,ArrayList<String>> innterDataMap;
private Spinner mInnerSPN;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinnerArray = new ArrayList<String>();
innterDataMap = new HashMap<String, ArrayList<String>>();
mMainSPN = (Spinner) findViewById(R.id.spn_main);
mInnerSPN = (Spinner) findViewById(R.id.spn_inner);
mMainSPN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String key = mSpinnerArray.get(position);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SpinnerFilterActivity.this,android.R.layout.simple_spinner_item,innterDataMap.get(key));
mInnerSPN.setAdapter(arrayAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
parseJson();
}
private void parseJson() {
String s= "{\"result\":{\"AndhrPradesh\":[\"Jayamahal\",\"ABC\",\"JP nagar\"],\"Mumbai\":[\"XYZ\",\"PQR\"],\"Pune\":[\"123\",\"Hi\"]}}\n";
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject obj= jsonObject.getJSONObject("result");
Iterator<String> stringIterator = obj.keys();
while (stringIterator.hasNext()){
String key = stringIterator.next();
mSpinnerArray.add(key);
JSONArray jsonArray = obj.getJSONArray(key);
ArrayList<String> innerList = new ArrayList<>();
for (int i=0;i<jsonArray.length();i++){
innerList.add(String.valueOf(jsonArray.get(i)));
}
innterDataMap.put(key,innerList);
}
populateDataInSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void populateDataInSpinner() {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mSpinnerArray);
mMainSPN.setAdapter(arrayAdapter);
}
}
In this code I have kept a data in 2 fields one i mSpinnerArray to display the aster list and other is map in which inner list is kept on behalf of the key as parent value. Whenever onOptionItemSelected method gets called I fetch the list of inner data from map on behalf of the seleted item from the master list as it is working as a key in innerMap data. I hope I am clear. Let me know if there is any problem.
In the registration process, when the user select the title from the spinner then its array index values should be automatically select and send to the asynctask. I want to send the array index value (position) as well in the below shown code.
new RegisterAsyncTask(getApplicationContext()).execute(TitleName,CountryName);
original value of the position is inside the onItemSelected(), I want to know how to pass it to the onclick()
this is my java code
public class RegisterActivity extends Activity {
private String[] states, states1;
private Spinner countrySP, titleSP;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_register);
Spinner spinner = (Spinner) findViewById(R.id.registerTitle);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
states = getResources().getStringArray(R.array.title_array);
states1 = getResources().getStringArray(R.array.country_array);
titleSP = (Spinner) findViewById(R.id.registerTitle);
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
titleSP.setAdapter(dataAdapter);
countrySP = (Spinner) findViewById(R.id.registerCountry);
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states1);
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
countrySP.setAdapter(dataAdapter1);
final Button button = (Button) findViewById(R.id.btnRegister);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String TitleName = titleSP.getSelectedItem().toString();
String CountryName = countrySP.getSelectedItem().toString();
String position = String.valueOf(titleSP.getSelectedItemPosition());
String position = String.valueOf(countrySP.getSelectedItemPosition()); //Duplicate local variable position
new RegisterAsyncTask(
getApplicationContext()).execute(
TitleName,
CountryName, position);
Toast.makeText(getApplicationContext(),
"Asynctask started",
Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
}
}
});
public class MyOnItemSelectedListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//check which spinner triggered the listener
switch (parent.getId()) {
//country spinner
case R.id.registerTitle:
//make sure the country was already selected during the onCreate
String[] titles = getResources().getStringArray(R.array.title_array);
String selectedTitle = titles[position];
System.out.println("title = " + position );
case R.id.registerCountry:
//make sure the country was already selected during the onCreate
String[] countries = getResources().getStringArray(R.array.country_array);
String selectedCountry = countries[position];
System.out.println("country = " + position );
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
}
My title.xml inside values folder
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title_prompt">Choose the title</string>
<string-array name="title_array">
<item>Mr</item>
<item>Mrs</item>
<item>Miss</item>
<item>Dr</item>
<item>Rev</item>
<item>Ms</item>
</string-array>
</resources>
Use getSelectedItemPosition to get selected item position from Spinner on Button click as:
public void onClick(View v) {
String TitleName = titleSP.getSelectedItem().toString();
String CountryName = countrySP.getSelectedItem().toString();
String position=String.valueOf(titleSP.getSelectedItemPosition());
// pass position to RegisterAsyncTask
new RegisterAsyncTask(
getApplicationContext()).execute(TitleName,CountryName,position);
}
yes now i get it,
you need to do something like this
public void onClick(View v) {
try {
String TitleName = titleSP.getSelectedItem().toString();
String CountryName = countrySP.getSelectedItem().toString();
String selectedPos=Integer.toString(titleSP.getSelectedItemPosition()); // or countrySP if u need it to
new RegisterAsyncTask(
getApplicationContext()).execute(
TitleName,
CountryName, selectedPos);
:
:
now you have to modify RegisterAsyncTask doInBackground():
... doInBackground(String... params){
//params[0] is TitleName
//params[1] is CountryName
//params[2] is selectedPos
:
:
}