Get value in HashMap Android - android

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>();

Related

How can I get value from an arrayadapter to pass it another activity

Here I'm trying to send my value that gets from a spinner (array adapter) to another activity. I populate my spinner using json and my spinner is something like below.
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, villageList);
spinner_village.setAdapter(adp);
spinner_village.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
JSONObject villageObject = arrayList.get(position);
String villageId = villageObject.getString("id");
String villageName = villageObject.getString("name");
String villageCode = villageObject.getString("village_code");
Toast.makeText(Region.this, villageCode, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Now I'm trying to get "villageCode" to my on create a method so that I can pass this value to my another activity. What I've done so far is
spinner_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Region.this, Participant_Details.class)
.putExtra("catment_code", **-----**);
Region.this.startActivity(intent);
Region.this.finish();
}
})
putextra is giving error. How can I resolve it or what is the problem.
You can set the string villageCode as global variable (You can make your variable global by declaring it in the class level It should not be inside any method in your class) and then you extract the value of the string in your onClick method. Like so:
spinner_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Region.this, Participant_Details.class)
.putExtra("catment_code", villageCode); //the value is being set here
Region.this.startActivity(intent);
Region.this.finish();
}
})

Android, refresh listview after click on list item

I have one small problem, after i click on list item, checkbox on item dont change state. Update works perfectly, setChecked maybe, but change will appear after exiting and re-running activity. I read lot of about notifyDataSetChange(), it may work, but not. How can i fix it, like after click on item chechbox value will change.
public class SviatokPridajActivity extends Activity
{
private DatabaseOp mDbHelper;
ListView listview;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sviatok_pridaj);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
listview = (ListView) findViewById(R.id.listSviatok);
showUserSettings();
mDbHelper = new DatabaseOp(this);
mDbHelper.open();
Cursor sviatokCursor = mDbHelper.fetchAllSviatokNastav(username, 3);
if (sviatokCursor.getCount()==0)
{
mDbHelper.naplnSviatky(username);
sviatokCursor = mDbHelper.fetchAllSviatokNastav(username, 3);
}
final SviatokCursorAdapter adapter = new SviatokCursorAdapter(this, sviatokCursor);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int stlpec, long arg3)
{
// TODO Auto-generated method stub
Cursor cur = (Cursor) adapter.getItem(stlpec);
String odosli = cur.getString(cur.getColumnIndex("_id"));
String zobraz = cur.getString(cur.getColumnIndex("dlzka"));
CheckBox check = (CheckBox)findViewById(R.id.checkBox);
if (Integer.parseInt(zobraz)==0)
{
mDbHelper.updateSviatok(odosli, username, 1);
} else {
mDbHelper.updateSviatok(odosli, username, 0);
}
check.setChecked(!check.isChecked());
adapter.notifyDataSetChanged();
}
});
}
#Override
public void onPause()
{
super.onPause();
mDbHelper.close();
}
private void showUserSettings()
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
username = sharedPrefs.getString("prefUsername", "NULL");
}
}
you have checked your CheckBox in itemclick but it's not reflected to your itemList so before calling adapter.notifyDataSetChanged(); you should have to refresh listItems with new changes.
I ve answered this question in this : https://stackoverflow.com/a/22954806/1332870
can you check it? if it does not solve your problem please let me know
Reload your Cursor and instead of adapter.notifyDataSetChanged(); use adapter.changeCursor(reloadedCursor);
Not sure if this is a strain on the main thread but you could just set the adapter again in the on click method.

How can get ListView object in setOnClickListener?

In Code 2, I use final ListView lv=this.getListView() to get ListView object, it's OK.
In Code 1, I try to use ListView lv=((ListActivity)getApplicationContext()).getListView() to get ListView object, but it's bad.
Is there a simple way to get get ListView object in setOnClickListener? Thanks
Code 1
private void IniControl(){
findViewById(R.id.btnCancel).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ListView lv=((ListActivity)getApplicationContext()).getListView();
for(int i=0;i<lv.getCount();i++){
EditText number = (EditText)lv.findViewWithTag("editNumber"+i);
Toast.makeText(getApplicationContext(),number.getText().toString()+"CW",Toast.LENGTH_SHORT).show();
}
}
});
}
Code 2
public class StepList extends ListActivity{
private ListNumberAdapter mListNumberAdapter=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_step_list);
}
private void IniControl(){
final ListView lv=this.getListView();
findViewById(R.id.btnCancel).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<lv.getCount();i++){
EditText number = (EditText)lv.findViewWithTag("editNumber"+i);
Toast.makeText(getApplicationContext(),number.getText().toString()+"CW",Toast.LENGTH_SHORT).show();
}
}
});
}
}
Is IniControl also a method of StepList in your Code 1 ?
If so, you can simply call getListView() from there (the OnClickListener being an inner class of your StepList), or more explicitely StepList.this.getListView().
The ListView is not a member of the ApplicationContext. Why cant you add the ListView as a member of the Activity instead? Or use the getListView() on the ListActivity's context.
You can write separate OnClickListener method and pass ListView to it.
private View.OnClickListener onClick(final ListView lv) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
};
}
You can use onListItemClick Method
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "hoohoo..you clicked me at " + position,Toast.LENGTH_SHORT).show();
}
It will display the the row number you clicked
Make your ListView a class member Variable
private ListView mListView;
Then in onCreate(), call mListView = (ListView) this.getListView();
And then you can use the mListView object anywhere in the rest of the code.

How to select itemclick event for listview with multiple rows in android?

I am trying to get values from server and retrieved response from server, the details responsed from server are need to be displayed in a listview, i achieved that too, but while onitemclick process only first row in list view performs the click action but it is not performing for the remaining rows, how can i achieve it, dat is whatever the row and item i'm selecting it has to be processed by my code, here is my code for the reference, .........
public void userInterface() throws JSONException
{
if(json_user.get(0) != null)
{
downloadList1 = (ListView)findViewById(R.id.lvinbox);
populateData();
downloadList1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
fma=(TextView)findViewById(R.id.src);
st=(TextView)findViewById(R.id.sub);
fma.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String fm=fma.getText().toString();
String s=st.getText().toString();
Intent m = new Intent(getApplicationContext(), InActivity.class);
m.putExtra("f", fm);
m.putExtra("s", s);
startActivity(m);
}
});
st.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String fm=fma.getText().toString();
String s=st.getText().toString();
Intent m = new Intent(getApplicationContext(), InActivity.class);
m.putExtra("f", fm);
m.putExtra("s", s);
startActivity(m);
}
});
}
});
}
else
{
Toast.makeText(getApplicationContext(),"Empty", Toast.LENGTH_LONG).show();
finish();
Intent menu = new Intent(getApplicationContext(), MenActivity.class);
menu.putExtra("username", dest);
startActivity(menu);
}
}
public void populateData() throws JSONException
{
resultVector = new Vector<ListDataItemInbox>();
int len = json_user.length();
System.out.println("length--------------------->"+len);
for(int i=0;i<len;i++)
{
JSONObject obj=json_user.getJSONObject(i);
listData = new ListDataItemInbox();
listData.sets(obj.getString(KEY_S));
listData.setd(obj.getString(KEY_D));
resultVector.add(listData);
myHandler.post(myRunnable);
}
}
private Handler myHandler = new Handler();
private Runnable myRunnable = new Runnable()
{
public void run()
{
customListAdapter = new ListViewAdapterInbox(InActivity.this);
customListAdapter.setResultsData(resultVector);
downloadList1.setAdapter(customListAdapter);
}
};
You can do something like this.
make the ArrayList in list adapter class
ArrayList<Integer> selectedIds = new ArrayList<Integer>();
and create this method also in that same class.
public void toggleSelected(Integer position){
selectedIds.clear();
selectedIds.add(position);
}
Now whenever you click on any item of listview pass that item position to this method. And inside your getView method set the check before setting the text. something like this..
if (selectedIds.contains(position)){
----- your code ----
}else{
----- your code ----
}
it perform the operation only on selected position . Try it.!

How to access values defined in AsyncTask from an activity

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

Categories

Resources