error in accessing variable of main activity's class from mapactivity - android

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

Related

relationship between EditText and TextView

If I have an EditText in layout and Text view in another layout my code take which in EditText to another layout and put it in the textView ..
the format of TextView is different from format of EditText like font-size and font-family .. i want my code to take the format also to another layout and apply it on textview which exist in another layout
so to be more specific : I write something in the 1st layout and change its font size ... this EditText will be a textView in the second layout but without saving format of EditText .. I want textView be same format of EditText ..
can I do that ?? and how ??
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int position = spinner.getSelectedItemPosition();
int fontSizeInt;
try
{
fontSizeInt = Integer.parseInt(items[position]);
}
catch (NumberFormatException e)
{
fontSizeInt = 12; // Default size.
}
et.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) fontSizeInt);
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
and this is my touch listener
public void addListenerOnImageg1() {
final Context context = this;
imageView = (ImageView) findViewById(R.id.g1);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(context , g1.class);
intent1.putExtra("fname" , et.getText().toString());
intent1.putExtra("font_size", fontSizeInt);
startActivity(intent1);
}
}); }
what should i write in the second layout ??
Since you do let user change format of the text in EditText, keep those changes, put 'em as more extras to your Intent, and read extras in the other activity.
You should have only one Intent and one call to startActivity(), unless you really want to start two activities, which I doubt.
I don't see where format data is, from this code, but if you have, for instance, your font size stored in int fontSize, call:
intent.putExtra("font_size", fontSize);
In that other activity, call:
int receivedFontSize = intent.getIntExtra("font_size", defaultFontSize);
As defaultFontSize, put 12 instead of the variable, if it's 12. Put 18, if it's 18. The purpose of this variable is to avoid absence of the value passed from parent activity. For instance:
int receivedFontSize = intent.getIntExtra("font_size", 18);

Passing values to Activities with putExtra()

I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");

pass an imageview in listview from activity 1 and recieve in activity 2 in an imageview

this is my code in activity 1 :
ImageView imgg=(ImageView)findViewById(R.id.iv_flag);
Bitmap mImage1 = BitmapFactory.decodeResource
(imgg.getResources),R.id.iv_flag);
imgg.setImageBitmap(mImage1);
String pid = ((TextView) view.findViewById(R.id.tv_country)).getText()
.toString();
String pid2 = ((TextView) view.findViewById(R.id.tv_country_details)).getText()
.toString();
String pid3 = ((ImageView) view.findViewById(R.id.iv_flag))
.toString();
Intent i = new Intent(NewsPage.this,
NewsPageDetails.class);
// //i.setClass(Cafe.this,cafelistselected.class);
i.putExtra("newspage", pid);
i.putExtra("newspages", pid2);
i.putExtra("images", pid3); // this is the string which contain the image
startActivity(i);
this is my code in activity 2 :
public class NewsPageDetails extends Activity{
String hospitalpress;
String hospitalpress2;
String hospitalpress3;
TextView textmain;
TextView textmain2;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newspagedetails);
textmain=(TextView)findViewById(R.id.textmainss);
textmain2=(TextView)findViewById(R.id.textonee);
image=(ImageView)findViewById(R.id.imgview);
Intent i = getIntent();
hospitalpress = i.getExtras().getString("newspage");
hospitalpress2 = i.getExtras().getString("newspages");
int hodddddspitalpress3= i.getExtras().getInt("images", R.id.iv_flag);
Bitmap mImage1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// /////////////////////////////INSTRUCT//////////////////
textmain.setText(hospitalpress);
textmain2.setText(hospitalpress2);
image.setImageResource(hodddddspitalpress3);
}
}
please let me now what exactly i write in the first activity and what i write in the second activity to let the imageview (in activity 2)display the image that is in listview of (avtivity 1)
Hint : the images in listview is coming from mysql database not drawable .
If U need to transfer data from one activity to another on click of list view then fallow undermentioned ( Hope U can do list view part by your own. Hoping U have created Adapter class as well )
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(Service.this, SelectedService.class);
intent.putExtra("sp_name", m_ArrayList.get(arg2).sp_name);
intent.putExtra("image_url",
m_ArrayList.get(arg2).your_image);
startActivity(intent);
}
});

Get value in HashMap 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>();

Unable to start activity ComponentInfo: java.lang.NullPointerException

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.

Categories

Resources