The Exception:
Unable to start activity ComponentInfo{com.scytec.datamobile.vd.gui.android/com.scytec.datamobile.vd.gui.android.SelectedList}: java.lang.NullPointerException..
I just want to show checkbox list view and on every check it display "checked", simply but i don't know why this gives me an exception.
public class SelectedList extends Activity implements IObserver{
private ListView machine_listview;
ArrayAdapter<String> adapter;
ArrayList<String> arrayListofMachines;
ArrayList<String> arrayListofMachineNumbers;
Vector<MDCMachineStatus> machineStatus_vector;
Handler handler;
private static int oldPosition = 0;
private Boolean firstClick = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.machinelistview);
machine_listview = (ListView) findViewById(R.id.machine_listview);
machine_listview.setFastScrollEnabled(true);
MachineStatusSingleton.Register(this);
getData();
adapter = new ArrayAdapter<String>(SelectedList.this, R.layout.selectedlist,R.id.text1, arrayListofMachines);
machine_listview.setAdapter(adapter);
machine_listview.setSelection(oldPosition);
CheckBox chk=(CheckBox)findViewById(R.id.check);
chk.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
TextView txt=(TextView)findViewById(R.id.xtra);
if (arg1)
Log.d("", "abul, checked") ;
else
Log.d("", "abul, not checked") ;
}
}
);
machine_listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
oldPosition = position;
MachineStatusSingleton.setMachineNumber(arrayListofMachineNumbers.get(position));
SelectedList.this.finish();
}
});
handler = new Handler(){
public void handleMessage(android.os.Message msg) {
machine_listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
};
};
}
public void Update(ISubject arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDestroy()
{
super.onDestroy();
MachineStatusSingleton.Unregister(this);
}
private void getData(){
machineStatus_vector = MachineStatusSingleton.GetData();
arrayListofMachines = new ArrayList<String>();
arrayListofMachineNumbers = new ArrayList<String>();
for(MDCMachineStatus temp: machineStatus_vector){
arrayListofMachines.add(temp.toString());
arrayListofMachineNumbers.add(temp.getNumber());
}
Collections.sort(arrayListofMachines);
Collections.sort(arrayListofMachineNumbers);
}
private void updateData(){
getData();
handler.sendEmptyMessage(0);
adapter.notifyDataSetChanged();
int index = machine_listview.getFirstVisiblePosition();
View v = machine_listview.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// ...
// restore
machine_listview.setSelectionFromTop(index, top);
}
}
We run our app very well and suddenly we encounter NullPointerException or Unable to start activity etc errors.
Basically NullPointerException or Unable to start activity occurs when there is issue in onCreate() method of our Activity.
This occurs when :
We change any xml values of layout related to this Activity
If we do not map xml UI's properly in our Acivity
Try to access UI which is in another layout file.
Solution :
First Cross check all the mapped elements
Give unique naming
Directly after:
TextView txt=(TextView)findViewById(R.id.xtra);
... add this:
if (txt == null) { Log.w("", "TextView is null"); }
Assuming your null pointer exception doesn't occur until you select the checkbox, that sounds like the most likely issue. I've encountered the same when I forget that I removed the corresponding element from the XML layout, or if I got the ID wrong. Usually I wrap any actions upon an element returned by "findViewById" within a null check, to ensure that even if the retrieval fails, the app at least won't crash.
Looks like you're assigning to chk, and subsequently, txt by calling findViewById as you declare them. I had to declare them first, and then assign to them using findViewById.
Related
it seems to be a typical question but its not i am facing problem in accessing a variable of main activity's onitemselected class(spinner class)from mapavtivity
in main avtivity map is shown on button click
now i want to use a variable of main activity's class from mapctivity
mapactivity code
String dest ;
OnItemSelectedListener place = new OnItemSelectedListener();
dest = place.onItemSelected();
now onitemselected class
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
name = "Destination:" + parent.getSelectedItem().toString()+ "\n";
etTextOut.setText(name);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public String onItemSelected() {
// TODO Auto-generated method stub
//dest = name;
return name;
}
}
problem is in mapactivity the variable is null it cannot get value
tell me what i am doing wrong
I'm not sure if I understand the way your program is set up but from what I understand you have a main Activity which has a spinner in it.
First make sure you're actually setting the onItemSelectedlistener to the spinner after you create it.
OnItemSelectedListener place = new OnItemSelectedListener();
//Replace "spinnerId" with the id you have set for your spinner in your layout
Spinner spinner = (Spinner) findViewById(R.id.spinnerId);
spinner.setOnItemSelectedListener(place);
Then if you want to start the MapActivity and have it have access to the "name" value, you'll have to pass the value in the intent you use to start the activity.
String dest = place.onItemSelected();
//You might want to rename this method to something clearer like "getName" but that's just me.
Intent intent = new Intent(this, MapActivity.class);
intent.putExtra("DestValue", dest);
startActivity(intent);
Now, in your MapActivity, you will have access to this value by using:
Intent intent = getIntent();
String dest = intent.getStringExtra("DestValue");
If your main activity is not starting the MapActivity, you can also try looking into SharedPreferences to pass values between activities.
Hope this was helpful.
Corrected Answer:
Try this in your activity. It should work:
private EditTextBox etTextOut;
#Override
protected void onCreate(Bundle savedInstanceBundle){
EditTextBox etTextOut = (EditTextBox) findViewById(R.id.etTextOutId);
Spinner spinner = (Spinner) findViewById(R.id.spinnerId);
OnItemSelectedListener spinnerListener = new OnItemSelectedListener{
private String name;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
name = name = "Destination:" + parent.getSelectedItem().toString()+ "\n";
etTextOut.setText(name);
}
public void onNothingSelected(AdapterView<?> parent){}
public String getName(){
return name;
}
}
spinner.setOnItemClickListener(spinnerListener);
}
I have code like this
#Override
public void onCreate(Bundle savedInstanceState) {
addItemsOnSpinnerOrgaLevel();
btn_getReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//How can i access map and list defined in orgaLevelTask(AsyncTask)???
Like
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
// Both are defined in AsyncTask ??
}); //end of anonymous class
} //end of onCreate()
public void addItemsOnSpinnerOrgaLevel() {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of addItemsOnSpinnerOrgaLevel()
In AsyncTask onPostExecute() Method i have
#Override
protected void onPostExecute(ArrayList<OrgaLevel> result) {
super.onPostExecute(result);
if (result != null) {
addItemsOnSpinnerOrgaLevel(result);
}
dialog.dismiss();
} //end of onPostExecute()
public void addItemsOnSpinnerOrgaLevel(ArrayList<OrgaLevel> result) {
orgaLevelElementslist = new ArrayList<String>();
orgaLevelElementslist.add("All");
orgaLevelMap = new HashMap<String, Integer>();
orgaLevelMap.put("All", 0);
for (int i=0; i<result.size(); i++) {
OrgaLevel orgaLevelRecord = (OrgaLevel) result.get(i);
String key = orgaLevelRecord.getOrgaName();
String value = orgaLevelRecord.getOrgaCode();
orgaLevelMap.put(key, Integer.parseInt(value));
orgaLevelElementslist.add(key);
} //end of for()
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(accountReportActivity, android.R.layout.simple_spinner_item, orgaLevelElementslist);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_orgaLevel.setAdapter(dataAdapter);
setSpinnerOrgaLevelListener();
} //end of addItemsOnSpinnerOrgaLevel()
private void setSpinnerOrgaLevelListener() {
spinner_orgaLevel.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
subOrgaLevelTask = new SubOrgaLevelTask(accountReportActivity, spinner_branch, orgaCode);
subOrgaLevelTask.execute();
} //end of onItemSelected()
}); //end of anonymous class
} //end of setSpinnerOrgaLevelListener()
In the subOrgaLevelTask i also have the same hash map as in this class. You can see that what i am trying to do is, put a key value in spinner. So when my btn_getReport button get click then i get the value of the selected item. Like if All is slected then i get 0 and so on. This key value thing is working. The problem is when btn_getReport get click then how can i get the value of the selected item. Because i am filling items in a background thread(In OrgaLevelTask and SubOrgaLevelTask) and my button is in Activity. So how can i do that when button get click, then i get the values from the map defined in OrgaLevelTask and SubOrgaLevelTask ?
Thanks
well, make them public in orgaLevelTask, and simply access them. orgaLevelTask should be a variable in you activity class. Have you tried it? any errors?
You must make sure orgaLevelTask members will be accessed in thread safe manner
I have two activitys...
Activity 1: have a edittext and two button:button1 & button2
Activity 2: have a autocompletetextview and a listview
I want to that when i enter string to edittext and click button1 ,i create a HashMap(static) to save value(set defaul="hello word") and key as string in edittext...
Event when click button1:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
hashMap.put(edittext.getText().toString(),"hello word");//I declared hashMap
}
});
In activity2 :
public class Notification_App extends Activity {
AutoCompleteTextView actv_notification;
ListView lv_notification;
Dictionary1 dictionary1;
ArrayList<String> str_value;
ArrayList<String> array_key;
#Override
public void onCreate(Bundle circle)
{
super.onCreate(circle);
setContentView(R.layout.notification);
actv_notification=(AutoCompleteTextView)findViewById(R.id.actv_notification);
lv_notification=(ListView)findViewById(R.id.listview_notification);
array_key=new ArrayList<String>(dictionary1.hashMap.keySet());
Iterator myVeryOwnIterator = dictionary1.hashMap.keySet().iterator();
while(myVeryOwnIterator.hasNext())
{
String key=(String)myVeryOwnIterator.next();
String value=(String)dictionary1.hashMap.get(key);
str_value.add(value);
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(Notification_App.this, android.R.layout.simple_dropdown_item_1line,array_key);
ArrayAdapter<String> adapter1=new ArrayAdapter<String>(Notification_App.this, android.R.layout.simple_list_item_1,array_key);
actv_notification.setAdapter(adapter);
lv_notification.setAdapter(adapter1);
lv_notification.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), str_value.get(position), Toast.LENGTH_LONG).show();
}
});
}
but error display: null poiter at line: str_value.add(value);...Can you help me..
I think you just forgot to initialise str_value variable. Put before your while loop:
str_value = new ArrayList<String>();
and it should do the trick.
P.S. I'm not checking the logic of your code, simply pointing out why you get NullPointerException.
Try to add
str_value = new ArrayList<String>();
Before the first
str_value.add(value);
You're getting an exception because str_value is null.
You need to create the actual object:
str_value = new ArrayList<String>();
public class CompanySearchActivity extends RathbonesActivity {
private CompanySearchAdapter mStockListAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.companysearch_layout);
final EditText keywordET = (EditText)findViewById(R.id.codeET);
final Button search = (Button)findViewById(R.id.button_stock_add);
final Activity a= CompanySearchActivity.this;
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String keyword = keywordET.getText().toString();
Log.i("keyword: ",keyword);
ArrayList codearr = getResults(keyword);
mStockListAdapter = new CompanySearchAdapter(a,codearr);
ListView listview = (ListView) findViewById(R.id.stocklist);
listview.setAdapter(mStockListAdapter);
listview.setOnItemClickListener(this);
listview.setOnItemLongClickListener(this);
}
});
}
The lines listview.setOnItemClickListener(this);
listview.setOnItemLongClickListener(this); are giving errors because of this keyword, i replaced it with 'a' too but it doesnt work. What can be the possible way to achieve this?
If you wish to use the parent activities onClick method your activity must implement OnItemClickListener and OnItemLongClickListener
public class CompanySearchActivity extends RathbonesActivity implements OnItemClickListener, OnItemLongClickListener
{
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
}
}
Note the code "implements OnItemClickListener, OnItemLongClickListener"
This is vital for implementing it this way.
Then you can call:
listview.setOnItemClickListener(CompanySearchActivity.this);
listview.setOnItemLongClickListener(CompanySearchActivity.this);
The this keyword is a reference to the object that owns the currently executing method. In this case this refers to the anonymous View.OnClickListener object that you are defining. Try replacing this with CompanySearchActivity.this
your listview onClick definition should look like your search listener.
search.setOnClickListener(new View.OnClickListener() {
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String keyword = keywordET.getText().toString();
Log.i("keyword: ",keyword);
ArrayList codearr = getResults(keyword);
mStockListAdapter = new CompanySearchAdapter(a,codearr);
}
});
ListView listview = (ListView) findViewById(R.id.stocklist);
listview.setAdapter(mStockListAdapter);
listview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
<do somthing when its clicked>
}
});
also ensure if you have multiple layouts that these view items (listview and search)
are in companysearch_layout.xml
I have an ArrayAdapter (myAdapter) attached to an AutoCompleteTextView (textView) component.
Once the user presses a character I would like to populate AutoCompleteTextView's drop down list with items containing this character.
I retrieve the items using AsyncTask (which uses a web service).
I call myAdapter.add(item) but the drop down list is empty.
I added a call myAdapter.getCount() after each addition and it shows zero every time.
Calling notifyDataSetChanged() didn't help.
I even tried to add simple String objects instead of my custom objects, to no avail.
What am I doing wrong?
Edit: I changed the code as miette suggested below but still to no avail.
Generally, what I do is after text is changed in my auto complete text view, I call a new AsyncTask and pass it the entered text and a Handler (see afterTextChanged()). The task retrieves objects relevant to the text and once done the Handler's handleMessage() is called. In handleMessage() I attempt to populate the adapter's objects. But still the adapter's drop down list ends up empty.
Here is my code:
public class AddStockView extends Activity
implements OnClickListener, OnItemClickListener, TextWatcher {
ArrayAdapter<Stock> adapter;
AutoCompleteTextView textView;
Vector<Stock> stocks;
public AddStockView() {
// TODO Auto-generated constructor stub
stocks = new Vector<Stock>();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.add_stock_view);
findViewById(R.id.abort_button).setOnClickListener(this);
adapter = new ArrayAdapter<Stock>(this,
android.R.layout.simple_dropdown_item_1line, stocks);
//adapter.setNotifyOnChange(true);
textView = (AutoCompleteTextView)
findViewById(R.id.search_edit_text);
textView.setAdapter(adapter);
textView.setOnItemClickListener(this);
textView.addTextChangedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.abort_button:
finish();
break;
case R.id.search_edit_text:
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
Stock stockToAdd = (Stock)parent.getAdapter().getItem(position);
//TODO: Add the above stock to user's stocks and close this screen
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.layout.menu, menu);
CategoryMenu.getInstance().populateMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
CategoryMenu.getInstance().menuItemSelected(item, this);
return false;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
#Override
public void afterTextChanged(Editable text) {
// TODO Auto-generated method stub
if (text.toString().equals(""))
return;
new AppTask().execute(new AppTask.Payload(Consts.taskType.SEARCH_STOCK,
new Object[] {text, handler}, this));
}
#Override
public void beforeTextChanged(CharSequence a0, int a1, int a2, int a3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence a0, int a1, int a2, int a3) {
// TODO Auto-generated method stub
}
private void addStockItemsToAdapter(Vector<Object> dataItems)
{
for (int i = 0; i <dataItems.size(); i++)
{
Stock stk = (Stock)dataItems.elementAt(i);
stocks.add(stk);
}
}
public void populateAdapter()
{
addStockItemsToAdapter(ContentReader.getInstance.getDataItems());
adapter.notifyDataSetChanged();
int size = adapter.getCount(); // size == 0 STILL!!!!
textView.showDropDown();
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
populateAdapter();
}
};
}
Thanks a lot, Rob
I had the exact same problem. After examining the ArrayAdapter and AutoCompleteTextView source code, I found out that the problem was, in short, that:
the original object list is stored in ArrayAdapter.mObjects.
However, AutoCompleteTextView enables ArrayAdapter's filtering, meaning that new objects are added to ArrayAdapter.mOriginalValues, while mObjects contains the filtered objects.
ArrayAdapter.getCount() always returns the size of mObjects.
My solution was to override ArrayAdapter.getFilter() to return a non-filtering filter. This way mOriginalValues is null and mObjects is used instead in all cases.
Sample code:
public class MyAdapter extends ArrayAdapter<String> {
NoFilter noFilter;
/*
...
*/
/**
* Override ArrayAdapter.getFilter() to return our own filtering.
*/
public Filter getFilter() {
if (noFilter == null) {
noFilter = new NoFilter();
}
return noFilter;
}
/**
* Class which does not perform any filtering.
* Filtering is already done by the web service when asking for the list,
* so there is no need to do any more as well.
* This way, ArrayAdapter.mOriginalValues is not used when calling e.g.
* ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly
* and methods like getCount() return the expected result.
*/
private class NoFilter extends Filter {
protected FilterResults performFiltering(CharSequence prefix) {
return new FilterResults();
}
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Do nothing
}
}
}
Create an array adapter with a vector or array like:
ArrayAdapter(Context context, int textViewResourceId, T[] objects)
By initializing your arrayadapter, you will make it listen to objects array. Do not add item to the adapter or clear the adapter, do your additions in "objects" array and also clear it. After changes on this array call
adapter.notifyDataSetChanged();
More specifically
ArrayAdapter<YourContentType> yourAdapter = new ArrayAdapter<YourContentType> (this,R.id.OneOfYourTextViews,YourDataList);
yourAdapter.notifyDataSetChanged();
aTextView.setText(yourAdapter.isEmpty() ? "List is empty" : "I have too many objects:)");
This should be done after loading YourDataList, I checked your code, are you sure handler calls addStockItemsToAdapter() before you look your adapter is empty or not?
You should also check if stocks vector has any elements in it.
Where do you call addItemsToAdapter()?
Can you show us, how you have tried to add simple Strings to your Adapter?
Edit: out of the comments the helpful code sample:
adapter = new ArrayAdapter<Stock>(this, android.R.layout.simple_dropdown_item_1line, stocks);
adapter.notifyDataSetChanged();
textView.setAdapter(adapter);