How to get listview item string? - java

How to get item where i click in list-view?
Here is my code:
public class MainClass extends Activity {
ArrayList <String> listItems = new ArrayList<String>();
ArrayAdapter <String> adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listItems.add("Item 1");
listItems.add("Item 2");
listItems.add("Item 3");
adapter.notifyDataSetChanged();
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
but it force closes everytime.

change:
listView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});
to:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), listView.getItemAtPosition(arg2).toString(), Toast.LENGTH_LONG).show();
}
});

You need to use a onItemClickListener if you want to interact with the items in the list. This has a position argument in the method which you can then use to retrieve the value at that position.

try :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent,
View view, int pos, long id) {
String item=(String)((TextView) view).getText();
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(0).toString(),
Toast.LENGTH_LONG).show();
}
});

Related

How do i copy an item in an list into a list in another activity?

Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.

deleting a row in parse server?

the problem is the list item on which it is clicked does not get deleted but an item behind or in front of it gets deleted (for list2.get(d) or list2.get(d-1))how to get the item which is clicked to get deleted?)
Intent intent=getIntent();
k=intent.getStringExtra("this is a");
list=(ListView)findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
d=i;
AlertDialog.Builder dialog=new AlertDialog.Builder(Main3Activity.this);
dialog.setMessage("this is a");
dialog.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int l){
ParseQuery<ParseObject> b=new ParseQuery<ParseObject>("message");
b.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e)
{
if(e==null) {
for (ParseObject n : objects) {
if (n.getString("message").equals(list2.get(d))&&(n.getString("receiver").equals(ParseUser.getCurrentUser().getUsername().toString())&&n.getString("sender").equals(k)))
{
try {
Toast.makeText(Main3Activity.this,list2.get(d+1), Toast.LENGTH_SHORT).show();
n.delete();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
else
{
Log.i("this is a",e.getMessage());
}
}
});
list2.remove(d);
a.notifyDataSetChanged();
this in this case refers to onItemClickListener context. You can either use application context by calling getApplicationContext() OR if you need local context, use CLASSNAME.this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent=getIntent();
list=(ListView)findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder dialog=new AlertDialog.Builder(getApplicationContext());
}
});
OR
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent=getIntent();
list=(ListView)findViewById(R.id.listview);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);
}
});

How to call method of activity in Fragment?

I have the following listView:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//CheckBoxAdapter cb = new CheckBoxAdapter(this.getActivity(),R.layout.item, getResources().getStringArray(R.array.products));
//lv.setAdapter(cb);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_list_item_1, categories);
ListView lv = (ListView) this.getActivity().findViewById(R.id.listProduct);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String type = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getContext(), parent.getItemAtPosition(position)+" is selected", Toast.LENGTH_LONG).show();
try {
MainActivity.AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
} catch (TimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
But currently I cannot reference addSubscription which is nonstatic
MainActivity.AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
I need to create a non static listener which can call addsubscription, is it possible with a listview? If not can I use another type of view?
Simply if your fragment is placed in MainActivity do this:
((MainActivity)getActivity()).AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
Do the following in the listener:
YourFragmentName.this.((MainActivity)getActivity()).AddSubscription(String.valueOf(parent.getItemAtPosition(position)));
I would not use getActivity() and cast it as this approach seems to fragile to me.
I typed this out of my head without an IDE so there might be typos.
Let the Activity implement an interface SubscriptionHandler
public interface SubscriptionHandler {
public void addSubscription(String identifier);
}
Actitiy
public MainActivity extends AppCompatActivity implements SubscriptionHandler {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_id);
fragment.setSubscriptionHandler(this);
}
#Override
public void addSubscription(String identifier){
//logic
}
}
and then use this in the Fragment
public class MyFragment extends Fragment {
#Nullable private SubscriptionHandler subscriptionHandler;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_list_item_1, categories);
ListView lv = (ListView) this.getActivity().findViewById(R.id.listProduct);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String type = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getContext(), parent.getItemAtPosition(position)+" is selected", Toast.LENGTH_LONG).show();
try {
if(subscriptionManager != null) {
subscriptionHandler.addSubscription(String.valueOf(parent.getItemAtPosition(position)));
}
} catch (TimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
public void setSubscriptionHandler (SubscriptionHandler subscriptionHandler) {
this.subscriptionHandler = subscriptionHandler;
}
}

Delete item from listview when the item is clicked

I currently have this code to display chosen items in a listview:
public class DisplayOrder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_order);
bar();
Button btn = (Button) findViewById(R.id.btnHome);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(DisplayOrder.this, Options.class);
startActivity(myIntent);
}
});
}
private void bar() {
ListView lv = (ListView) findViewById(R.id.listViewDisplay);
List<String> itemsOrdered = new ArrayList<String>();
for (Map.Entry<Item, Integer> entry : Datastore.currentTable.getOrder().getItems().entrySet()) {
itemsOrdered.add((entry.getKey().name) + " x " + String.valueOf(entry.getValue()) + " £" + (entry.getKey().price * entry.getValue()));
}
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.activity_display_order, R.id.textView8, itemsOrdered);
lv.setAdapter(arrayAdapter);
}
}
What i want to do is, when I click one of the items, for it to be deleted but Im not sure how to do that. Any guidance would be much appreciated.
You should detect when you click in each item of ListView by setOnItemClickListener.
Then inside this method, just delete the list datasource and notifyDataSetChanged
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView < ? > parent, View view,int position, long id) {
itemsOrdered.remove(position); // remove item at index in list datasource
arrayAdapter.notifyDataSetChanged(); // call it for refresh ListView
Toast.makeText(getApplicationContext(), "remove item at " + position, Toast.LENGTH_LONG).show();
}
});
You have to override the listener “setOnItemClickListener” like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
itemsOrdered.remove(item);
arrayAdapter.notifyDataSetChanged();
}
});
This code removes the ítem from the list, but you have to notify the change to the adapter. When the adapter is notified the listview is updated.

How to Pass an Int from non-activity class to Activity class

Android is similar to Java in terms of convention but why does my setter and getter methods won't work.
I have a spinner(which is a non-activity class) with code like this:
int finalposition;
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
for(int i=0; i<40; i++) {
if (i==pos){
setPosition(pos);
}
}
}
public void setPosition(int position){
finalposition= position;
}
public int getPosition(){
return finalposition;
}
and in onCreate(), here is my MainActivity(which extends Activity):
//spinner
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener2());
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CustomOnItemSelectedListener2 coisl2= new CustomOnItemSelectedListener2();
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
What I need to do is that if I select the item at position 1 in my spinner and clicked gPath button, a toast saying "It Works!" should be displayed. However, it does not work. I put a toast(displaying the position that was taken from calling getPosition()) on the button. When I selected the item at position 1 and click the button, it returned position:0. So that's why it won't enter the if-condition that I implemented and I'm wondering why. I do this in Java but why am I having troubles in Android. What is wrong/missing in my code?
Any help is appreciated
Try this.
You are creating a new instance of the listener on each onClick, and that listener would obviously not know which item was selected in the spinner, since it isn't effectively listening over anything.
//declare this as a class object
CustomOnItemSelectedListener2 coisl2= new CustomOnItemSelectedListener2();
//This follows in your onCreate
//spinner
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(coisl2);
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
You Can try this:
Under MainActivity.java
spinner2 = (Spinner)findViewById(R.id.spinner2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, paths);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
coisl2= new CustomOnItemSelectedListener2(MainActivity.this,spinner2);
//button
gPath = (Button) findViewById(R.id.getPath);
gPath.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(coisl2.getPosition()==1)
Toast.makeText(getApplicationContext(), "It Works!", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "position:"+coisl2.getPosition(), Toast.LENGTH_SHORT).show();
}
});
Under CustomOnItemSelectedListener2.java( You can create this class like below)
public class CustomOnItemSelectedListener2
{
int finalposition;
public CustomOnItemSelectedListener2(Context context,Spinner spinner)
{
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
setPosition(pos);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
public void setPosition(int position){
finalposition= position;
}
public int getPosition(){
return finalposition;
}
}
Hope this is what you want...

Categories

Resources