Listview setonitemclicklistener - android

I've looked up similar post regarding this question but they didn't solve my issue, so here it is.
I'm trying to set a setOnItemClickListener, for when I click on any item of my list I will open a dialog with the info (retrieve from the list) on the clicked list and more info. But i'm struggling to implement the setOnItemClickListener part.
I'm getting and error in line: myList.setOnItemClickListener(new OnItemClickListener()){
package com.example.proyectoprueba;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;;
public class PlantillaChina extends ActionBarActivity{
// DB Class to perform DB related operations
DBController controller = new DBController(this);
// Progress Dialog Object
ProgressDialog prgDialog;
HashMap<String, String> queryValues;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.lista);
Intent myIntent = getIntent();
String value = myIntent.getStringExtra("key");
TextView titulo=(TextView)findViewById(R.id.titulo);
// Get Platos records from SQLite DB
ArrayList<HashMap<String, String>> platoList = controller.getAllEntremeses();
if (value.equals("entremeses")){
platoList = controller.getAllEntremeses();
titulo.setText(value);
}else if(value.equals("arroces y pasta")){
platoList = controller.getAllArrocesyPasta();
titulo.setText(value);
}else if(value.equals("mar")){
platoList = controller.getAllMar();
titulo.setText(value);
}else if(value.equals("carnes")){
platoList = controller.getAllCarnes();
titulo.setText(value);
}
// If Platos exists in SQLite DB
if (platoList.size() != 0) {
// Set the Plato Array list in ListView
ListAdapter adapter = new SimpleAdapter(PlantillaChina.this, platoList, R.layout.itemlista, new String[] {
"platoId", "platoNombre", "platoDescripcion", "platoPrecio" }, new int[] {R.id.codigo, R.id.nombre, R.id.descripcion, R.id.precio });
ListView myList = (ListView) findViewById(R.id.listaplatos);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener()){
}
}
Thank you for your time

It think you want something like this.
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id)
{
// You have the position available here as well as the clicked view.
}
});

You need to actual define the OntItemClickListener to do something.
First, the code you have doesn't make much sense. You want something like this:
myList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Your code here
}
});
Basically you are creating your own OnItemClickListener class, and overriding the OnItemClick method. This callback will get called whenever an item in your list is clicked. You can do whatever processing you would like inside that function.

Related

setting values from an json array to spinner on application level

I want to set Json values into a spinner list. The data I have:
JSONArray lang = jsonObject.getJSONArray("languages");
for (int i = 0; i < lang.length(); i++) {
String language = lang.getString(i);
}
How can i load String values into a spinner list?
ArrayAdapter<String> arrayAdapter = new ArrayAdapter(yourContext, android.R.layout.activity_list_item)
arrayAdapter.addAll(langList); // you need to add your lang.getString(i) to an array
yourSpinner.setAdapter(arrayAdapter);
and voila!
As i understand your problem, you have list of records and you want to show them in spinner in multiple activity.
For this you can create an Class that extends Application Class and create a list in that class.
once You receive response from you web api set data in list of application class.
Now where ever you want to display data in Spinner get it from Application class and render your spinner
See below Example -
public class MyApp extends Application{
private static ArrayList<String> mDataArrayList;
public static ArrayList<String> getmDataArrayList() {
return mDataArrayList;
}
public static void setmDataArrayList(ArrayList<String> mDataArrayList) {
MyApp.mDataArrayList = mDataArrayList;
}
#Override
public void onCreate() {
super.onCreate();
}
}
Call your web api and parse data as you code in your question -
ArrayList<String> mArrayList = new ArrayList<String>();
for (int i = 0; i < lang.length(); i++) {
String language = lang.getString(i);
mArrayList.add(language);
}
//Set Application class list
MyApp.setmDataArrayList(mArrayList);
Now when you want to display data in any class then get list by calling -
ArrayList<String> mArrayList = MyApp.getmDataArrayList();
//Code to display data in Spinner
Hope it will help you.
And dont forgot to add it to manifest of your application -
<application
android:allowBackup="true"
android:name=".MyApp"
....>
....
</application>
I'd suggest you to use Spinner class activity for future usages. Here is the example of spinner activity class (data receiver and displayer):
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class mySpinnerClass extends Activity implements
OnItemSelectedListener {
Spinner spinner;
int selectedValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
selectedValue = -1;
Intent i = getIntent();
dataSelector = i.getStringExtra("MessageText");
// Spinner element
spinner = (Spinner) findViewById(R.id.mySpinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data
loadSpinnerData();
}
private void loadSpinnerData() {
// Spinner Drop down elements
List<String> lables = yourData.get(dataSelector);
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String label = parent.getItemAtPosition(position).toString();
//get the label and do anything you want with it
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
In caller activity:
Intent i = new Intent(getApplicationContext(), mySpinnerClass.class);
i.putExtra("MessageText",yourData);
startActivity(i);
If you want to send non-primitive data (in your example, this is a list) you need to use Serializable type while sending and receiving it. The following link illustrates this technique well:
http://javatechig.com/android/pass-a-data-from-one-activity-to-another-in-android

How to see text in toast

I'm trying to see text from GridView using a toast when I selected or clicked on GridView's data. I can see position, but don't know what to put to see a text.
Here is a code.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
String [] data = {"a","b", "c","d","e","f", "g","h"};
GridView gdView;
ArrayAdapter<String> adapter;
String result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tvText, data);
gdView = (GridView) findViewById(R.id.gdView);
gdView.setAdapter(adapter);
gdView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getBaseContext(), position, Toast.LENGTH_SHORT).show();
}
});
}
}
Could someone suggest me, what I need to use or where to look for it?
Thank you
The parameter int position of the method onItemClick() on AdapterView.OnItemClickListener gives you:
The position of the view in the adapter.
See here: https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html#onItemClick(android.widget.AdapterView, android.view.View, int, long)
You can use this to retrieve the content of this view from your ArrayAdapter with:
adapter.getItem(position)
See here: https://developer.android.com/reference/android/widget/ArrayAdapter.html#getItem(int)
This will return the content of your ArrayAdapter at the given position, in your case as a String, which you can store in a variable if you like or pass directly into Toast.makeText().
Turn last string to
Toast.makeText(getBaseContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();

Change Text From Listview if Clicked

i need help here.
Lets say that I have a listview taken from database :
-- car
-- refrigerator
-- pencil
-- motorcycle
This is what i want. When i clicked at car or other option, it will change to broken.
-- broken
-- refrigerator
-- pencil
-- motorcycle
I used this before
lv = (ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
TextView mTextView = (TextView) arg1;
mTextView.setText("broken");
//Toast.makeText(getApplicationContext(), data.get(arg2).toString(),3000).show();
}});
the problem is when i use back button and go to that page again, it will be back like before....
Any idea ?????
Here is my full code
package com.test.first;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Listview extends Activity
{
SQLiteDatabase mydb;
ListView lv;
ArrayList data;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
//=====CODE FOR SHOWING THE DATA IN TOAST =======
lv = (ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
TextView mTextView = (TextView) arg1;
mTextView.setText(data.get(arg2) + " has been bought !");
//Toast.makeText(getApplicationContext(), data.get(arg2).toString(),3000).show();
}});
mydb = Listview.this.openOrCreateDatabase("My", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS list (id INTEGER PRIMARY KEY AUTOINCREMENT,list varchar);");
data = new ArrayList();
//=VIEW BUTTON TO SHOW DATA INSERTED IN THE LISTVIEW=======
Cursor cursor2=mydb.rawQuery("SELECT * FROM LIST;", null);
if (cursor2.moveToFirst())
{
Toast.makeText(getApplicationContext(), "Shop List", 3000).show();
data.clear();
do
{
data.add(cursor2.getString(cursor2.getColumnIndex("list")));
}
while (cursor2.moveToNext());
//====CODE FOR SHOWING DATA AS A SIMPLE LIST ITEM=========================================
ArrayAdapter <String> adapter=new ArrayAdapter<String> (Listview.this,android.R.layout.simple_list_item_1,data);
lv.setAdapter(adapter);
}
else
{
Toast.makeText(getApplicationContext(), "DATA NOT AVAILABLE", 3000).show();
}
cursor2.close();
}
}
The problem is that when you press the back button and then reopen the activity the ListView is recreated with the original information. This information is not changed and contains the Car text thus is normal that the ListView containts car text other time.
You shall to update your List information and then call to modify the ListView:
adapter.notifyDataSetChanged()
If you change the information and then press back and reopen the Activty the ListView will be ok.

How to make fragment transaction when clicked on a listitem?

I have an activity where it contains an ActionBar (with four tabs) a fragment respectively assigned to each of these tabs. In these fragments I've assigned some ListAdapters filled with string values, clickable that furthermore I want to operate. When clicking on an item I want that app to send from that fragment to another. I know that I have to use FragmentManager() and FragmentTransaction() but since I'm new to Android dev I demand of any kind of help, help that is appreciated.
Here's the snippet code of one of the tabs(UserFragment.java):
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/** This is a listfragment class */
public class UserFragment extends ListFragment
{
/** An array of items to display in ArrayList */
String user_items[] = new String[]
{
"Account",
"Addresses",
"Payment Providers",
"Profile",
"Transactions",
"Wallet"
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
/** Creating array adapter to set data in listview */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_expandable_list_item_1, user_items);
/** Setting the array adapter to the listview */
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id)
{
Intent myIntent = new Intent(getActivity().getBaseContext(), Profile.class);
startActivity(myIntent);
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart()
{
super.onStart();
/** Setting the multiselect choice mode for the listview */
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
The Profile.java activity code:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class Profile extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
//Button test = (Button) findViewById(R.id.btnTest);
}
}
You need to define OnItemClickListener for your ListFragment to handle item click events. For example:
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
// start your new activity here
}
});
I found what was wrong. After a long search I learnt that if the onCreateView() method is static than it's all good to set listener/s but in this case while we fill an array-adapter of string than it's a no-go since first of first it has to created its View therefore doesn't let the app to make any further listeners. In order to make that available, the onActivityCreated(Bundle) should be initiated/created between onCreateView() and onStart() methods and insert the rest of the code.
Here's the solution to link a ListFragment to another FragmentActivity class:
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
getListView().setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id)
{
Intent myIntent = new Intent(getActivity().getBaseContext(), Profile.class);
startActivity(myIntent);
}
});
}

array that starts a new activity

OK, I realize this is prolly pretty basic, but im so new to this its unreal.
What I have is an array. What I want is for when a user clicks an item in the array, it opens a new activity that is specific to that item. Its a list of festivals, and when you click on one of the festivals, and when you click on it, it opens an activity that provides information about that festival.
I have no idea what I'm doing here. Im pretty sure I need to use an OnClickListener, but thats it.
Activity
package com.MADONK.LAFESTS;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class Home extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.main, Festivals));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
static final String[] Festivals = new String[] {
"Lake Arthur Regatta", "Contraband Days", "Iowa Rabbit Festival",
};
}
Since you're extending ListActivity, you can override onListItemClick(). You could do something like this, which gets the appropriate Festival object, and passes a member of it into an Intent, the Intent is then used to start another Activity:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Festival item = (Festival) l.getItemAtPosition(position);
Intent i = new Intent(v.getContext(),YourFestivalDetailActivity.class);
i.putExtra("some_attribute", item.getSomeAttribute());
startActivity(i);
}
And then in the Activity you start that is meant to show the Festival detail, which in the above example is called YourFestivalDetailActivity, you should extract the Festival information from the Intent used to start it:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String someAttribute = getIntent().getStringExtra("some_attribute");
}
Note that in this example I only pass a single String via the Intent, but know that you can pass more than that via an Intent. See the docs.

Categories

Resources