I am confused that after adding more EditText field, how am i suppose to know the string code so i could do an addition math to add them all up.Thank You.
Update :
So I managed to use ArrayAdapter to add the data into an array but I am facing problem to call it back in. Help!!!
txt = (EditText) findViewById(R.id.iteminput);
show = (ListView) findViewById(R.id.listView);
save = (Button) findViewById(R.id.Add);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getInput = txt.getText().toString();
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Splitter.this, android.R.layout.simple_list_item_1, addArray);
show.setAdapter(adapter);
((EditText) findViewById(R.id.iteminput)).setText("");
}
});
public void Calculate(View v){
for(int i = 0; i<adapter.getCount() ; i++){
Integer Total= adapter.getItem(i);
}
TextView Total=(TextView)findViewById(R.id.Total);
Total.setText("Splitted Cost: "+Total.toString());
}
The getCount couldnt get the adaptor :(
Just declare your adapter as a field and you will be able to access it in a method.
public class MainActivity extends Activity {
private ArrayAdapter<String> adapter; // declared as a field now you can access it anywhere.
public void onCreate(){
txt = (EditText) findViewById(R.id.iteminput);
show = (ListView) findViewById(R.id.listView);
save = (Button) findViewById(R.id.Add);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getInput = txt.getText().toString();
addArray.add(getInput);
adapter = new ArrayAdapter<String>(Splitter.this, android.R.layout.simple_list_item_1, addArray);
show.setAdapter(adapter);
((EditText) findViewById(R.id.iteminput)).setText("");
}
});
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to populate a ListView using an ArrayAdapter that I am filling with input from an EditText. My program seems to compile fine but during app start up it immediately crashes. I suspect that it has something to do with me trying to set-up my list view. I am not sure what I am initializing wrong such that my app instantly crashes. Any and all tips would be greatly appreciated. Thanks in advance!
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
ListView listView = (ListView) findViewById(R.id.dispScores);
listView.setAdapter(adapter);
My Adapter Class:
private class ScoreAdapter extends ArrayAdapter<scoreScreen> {
private ScoreAdapter(Context context, ArrayList<scoreScreen> scores) {
super(context, 0, scores);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
scoreScreen score1 = getItem(position);
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_scores, parent, false);
}
TextView holeNum = (TextView) convertView.findViewById(R.id.holeNum);
holeNum.setText(score1.hole);
return convertView;
}
}
My ListView inside of my onCreate method.
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
I am assuming my problem is not inside my EditText inputs since they are inside of an OnClickListener method, but just incase I have attached it below.
public View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
//savedScores.add(input1.getText().toString());
scoreScreen addScore = new scoreScreen("Score is" + num1);
adapter.add(addScore);
j++;
input1.setText(""); //Clear input text box
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
//CURRENTLY ONLY DISPLAYS THE LAST NUNMBER IN THE TEXTEDIT, NEED TO SET UP LISTVIEW!!!!!!
for (int i=0; i < j; i++){
// output1.setText(savedScores.get(i));
} break;
}
}
};
onCreate method added as requested:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Button scoresAct = (Button) findViewById(R.id.allScores); //THIS IS TO GO TO ALL SCORES ACTIVITY
scoresAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent scoreScreen = new Intent(MainActivity.this, AllScoresAct.class);
startActivity(scoreScreen);
}
});*/
Button sumScores = (Button) findViewById(R.id.buttTotal);
Button saveScores = (Button) findViewById(R.id.allScores);
Button changeScores = (Button) findViewById(R.id.editScore);
sumScores.setOnClickListener(onClickListener);
saveScores.setOnClickListener(onClickListener);
changeScores.setOnClickListener(onClickListener);
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
}
After moving my adapter and ArrayList into my onCreate, I get a new error. I did some research on null pointers, but I have already initialized both of these. Below is my logcat, any ideas? Thanks
Make sure super.onCreate(savedInstanceState) is the first thing you are calling in your onCreate() and also not trying to access any view from the layout xml before setContentView().
EDIT:
Initialize the adapter in onCreate() method instead of doing it globally.
onCreate() {
.......
this.adapter = new ScoreAdapter(this, savedScores);
}
This is my global declarations for my ArrayList and Adapter.
ArrayList<scoreScreen> savedScores = new ArrayList<>();
ScoreAdapter adapter = new ScoreAdapter(this, savedScores);
You can declare those globally, but for the Adapter, the this parameter must be used within/after onCreate, as the error says
System services not available to Activities before onCreate()
For example
private ArrayList<ScoreScreen> savedScores = new ArrayList<>();
private ScoreAdapter adapter;
#Override
protected void onCreate(Bundle b) {
...
adapter = new ScoreAdapter(this, savedScores);
}
I have a delete all button and everytime it delete all item in a listview, the listview won't road but stay the same, they will reload only when I create a new item or restart this activity. I have print a log on my code and it seems that the list view reload before the delete method called. my code is this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper db = new DBHelper(this);
final ListView listView = (ListView) findViewById(R.id.listView);
TextView empty = (TextView) findViewById(R.id.empty);
ArrayList<Inventory> listArray = new ArrayList<>();
listArray.clear();
listArray = db.read();
if (listArray.size() == 0) {
empty.setText("No Items");
} else {
empty.setText("");
}
ListViewAdapter customAdapter = new ListViewAdapter(listArray);
customAdapter.notifyDataSetChanged();
listView.setAdapter(customAdapter);
Button add_button = (Button) findViewById(R.id.button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewItem(view);
}
});
Button button_deleteAll = (Button) findViewById(R.id.button_deleteAll);
button_deleteAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deteleAll();
DBHelper db = new DBHelper(MainActivity.this);
final ListView listView = (ListView) findViewById(R.id.listView);
TextView empty = (TextView) findViewById(R.id.empty);
ArrayList<Inventory> listArray = new ArrayList<>();
listArray.clear();
listArray = db.read();
Log.v("arraysize:", String.valueOf(listArray.size()));
if (listArray.size() == 0) {
empty.setText("No Items");
} else {
empty.setText("");
}
ListViewAdapter customAdapter = new ListViewAdapter(listArray);
customAdapter.notifyDataSetChanged();
listView.setAdapter(customAdapter);
}
});
}
The method deleteAll() deletes all the data in SQLite.
I wish to know how to reload listview after this method called, rather than reload before this method.
add the delete all method in your adapter. call the deleteAll method of your adapter whenever button was clicked. the deleteAll method would be like below:
public void setListArray(ArrayList arrayList)
{
//assuming your adapter list is named "listArray"
this.listArray = arrayList;
notifyDataSetChanged();
}
and in your button click simply write this code:
button_deleteAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//assuming your list of itames here is named "mListArray"
mListArray.clear();
adapter.setListArray(mListArray);
}
}
I guess there is no need to initialize the customAdapter again in the button OnClick method. Also no need to setAdapter again.
Try to remove these lines in the onClick method.
Hope this fixes you issue.
Just add notifyDataSetChanged(); to your Adapter, inside a Listener. For example:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
myArrayList.remove(position);
myArrayAdapter.notifyDataSetChanged();
}
});
i want to use condition " if " for my array list
here is my code in (activity 1) to send string in textview with button to static variable that is in (exchange activity) :
Button btn1 = (Button) findViewById(R.id.btn1);
final TextView text = (TextView) findViewById(R.id.txt1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exchange.in =text.getText().toString();
}
});
here is my static variable in (exchange activity)
public static String in;
and here is my (activity 2) code that i use array list in it to receive & store string from (activity 1) that is in static variable (exchange.in)
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> web = new ArrayList<String>(10);
for (int i = 0; i < 10; i++) {
web.add("");
}
CustomList adapter = new
CustomList(activity_main.this, web);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
}
now i don't know how to store data from (exchange.in) to arraylist and then use if condition to recognize that, if arraylist(0) was full, put data that is in (exchange.in) to arraylist(1) and it will continue like this...
is anyone know about this?
I created an editable custom listview with a button outside the listview. I want to save the editText value entered by the user on the button click. My edit text is in base Adapter class and my list and button is in activity class, i'm having problem accessing the edit text from the list and my code crashes because of null pointer exception
public class ProductsList extends Activity{
ProductListAdapter dataAdapter;
ProgressDialog progressDialog=null;
ListView listView;
UserSQLiteDB usersqlite_obj;
ArrayList<Products> prodlist;
EditText edChemistName, edChemistAddr;
Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
edChemistName = (EditText) findViewById(R.id.editText1);
edChemistAddr = (EditText) findViewById(R.id.editText2);
btnSave =(Button)findViewById(R.id.button1);
listView = (ListView)findViewById(R.id.listView1);
usersqlite_obj = new UserSQLiteDB(this);
progressDialog = ProgressDialog.show(this, "Saved","Please wait...", true);
// new Thread() {
runOnUiThread(new Runnable() {
public void run() {
try{
usersqlite_obj.open();
prodlist = new ArrayList<Products>();
prodlist = usersqlite_obj.getProductsList();
Log.e("prodlist", "1");
dataAdapter = new ProductListAdapter(ProductsList.this,prodlist);
listView.setAdapter(dataAdapter);
usersqlite_obj.close();
} catch (Exception e) {
Log.d("error",e.getMessage());
}
dismissLoadingDialog();
}
});
}
public void buttonClick(View V) {
for(int i=0;i<listView.getCount();i++){
View row = listView.getChildAt(i);
Log.e("editText clicked", "yes");
EditText editText= (EditText) row.findViewById(R.id.ed);
if (editText.length()>0){
String text = editText.getText().toString();
Log.e("extracted text", "text");
}
}
If u want to use edittext data of listview in ur adapter class then u should pass this liatview in adapter class or you can set this adapter in activty file.
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
:
:
}