Open New Activity by id on Listview Item Click - java

My ListView is opening and everything is ok. I don´t know how to pass params from onPostExecute() to onItemClick() to open a new activity (SingleItem.java) by id.
Nothing that I´ve tried has worked.
ListItems.java
public class ListItems extends Activity {
private ListView listV;
TextView estado, cidade, noItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_items);
listV = (ListView) findViewById(R.id.listV);
estado = (TextView) findViewById(R.id.Estado);
cidade = (TextView) findViewById(R.id.Cidade);
noItem = (TextView) findViewById(R.id.noItem);
estado.setText(getIntent().getExtras().getString("state"));
cidade.setText(getIntent().getExtras().getString("city"));
Task task = new Task();
task.execute();
listV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getApplicationContext(), SingleItem.class);
startActivity(intent);
}
});
}
public class Task extends AsyncTask<String, String, Void>{
private ProgressDialog progressDialog = new ProgressDialog(ListItems.this);
InputStream is = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Listing Items...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Task.this.cancel(true);
}
});
};
#Override
protected Void doInBackground(String... params) {
String url = "http://myip/webviews/jsonlistItems.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error connecting to database " + e.toString());
Toast.makeText(ListItems.this, "Try again.", Toast.LENGTH_LONG).show();
}
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line = br.readLine()) != null){
sb.append(line+"\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v){
try {
JSONArray Jarray = new JSONArray(result);
for (int i = 0; i < Jarray.length(); i++) {
JSONObject jsonObject = null;
jsonObject = Jarray.getJSONObject(i);
// output
String item_id = jsonObject.getString("item_id");
String item_name = jsonObject.getString("item_name");
String item_color = jsonObject.getString("item_color");
String city = jsonObject.getString("city");
String statee = jsonObject.getString("state");
if(estado.getText().toString().equalsIgnoreCase(statee) &&
cidade.getText().toString().equalsIgnoreCase(city)){
String[] values = new String[] {item_name, item_color};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);
listV.setAdapter(adapter);
break;
}
else{
noItem.setText("No Item to show");
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
public class ItemById{
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list_events, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SingleItem.java
public class SingleItem extends Activity {
TextView item_name, item_color;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleitem);
item_name = (TextView) findViewById(R.id.item_name);
item_color = (TextView) findViewById(R.id.item_color);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.event, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
How to pass params from onPostExecute() to onItemClick() to open a new activity (SingleItem.java) by id?

It all depends what your SingleItem Activity is supposed to show when it's opened.
If you only need the name of the selected item then you simply retrieve the item name in the onItemClick method and pass it as parameter to SingleItem:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), SingleItem.class);
String name = adapter.getItem(position);
intent.putExtra("yourItem", name);
startActivity(intent);
}
In order for this to work the adapter needs to be a variable in the Activity:
public class ListItems extends Activity {
private ArrayAdapter<String> adapter;
and this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);
becomes this:
adapter = new ArrayAdapter<String>(ListItems.this, android.R.layout.simple_list_item_1, values);
If you need more information in the SingleItem Activity than just the name of the item you'd have to create an Item class to hold that information:
public static class Item implements Serializable {
String mName;
String mColor;
// more data
#Override
public String toString() {
return mName;
}
}
your onItemClick becomes:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), SingleItem.class);
Item item = adapter.getItem(position);
intent.putExtra("yourItem", name);
startActivity(intent);
}
Your adapter would be:
ArrayAdapter<Item> adapter;
adapter = new ArrayAdapter<Item>(ListItems.this, android.R.layout.simple_list_item_1, itemArray);
Of course you'd need to create the itemArray when parsing the json stream.
The activity could easily read the selected item from the intent like so:
getIntent().getSerializableExtra("yourItem");

The adapter looks like it's populated only by each attribute of your JSON object (one row for item_name, one row for item_color). If this is what you want the naturally you won't get item_id because it's not there.
If you want each row to correspond to each of your JSON objects then you should modify your adapter.
First make your own class like so
class Wrap{
String itemId, itemName, city, statee;
}
And then create your own Adapter class that extends ArrayAdapter<Wrap>.
This way every time a row is clicked, you can get the Wrap object which contains everything, including id. Then you can pass these values to your next Activity.

Related

Mimic the back button on the actionbar

So I have the action bar back button which returns me from an activity to my main activity. The problem I have is that it calls loadData() (which loads data from an API) when you press the action bar back button.
If I press the back button on the device (the button beside the home button) then I will be brought back to the previous view (the mainactivity) and won't have to call the API again.
So I'm trying to find a way to mimic the physical back button as an action bar widget.
I don't want MainActivity's code to be called again as it will execute another API call (I can only have 5 per minute) and it is also slower. I just want it to go back to the view I was just at.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<ListItem> listItems;
private String defaultQuery = "ham";
private String builtURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadData(defaultQuery);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
listItems.clear();
loadData(query);
(menu.findItem(R.id.action_search)).collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setIconified(false);
return true;
}
public void loadData(String query) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading recipes...");
progressDialog.show();
Log.d("q", "loadData: " + query);
builtURL = buildURL(query);
StringRequest request = new StringRequest(Request.Method.GET,
builtURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject obj = new JSONObject(response);
JSONArray hits = obj.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject a = hits.getJSONObject(i);
JSONObject recipe = a.getJSONObject("recipe");
String ingredients = recipe.getString("ingredientLines");
ingredients = ingredients.replace("[", "");
ingredients = ingredients.replace("]", "");
ingredients = ingredients.replace("\"", "");
ingredients = ingredients.replace("\\", "");
ingredients = ingredients.replace(",", "\n");
ListItem item = new ListItem(
recipe.getString("label"),
recipe.getString("source"),
recipe.getString("image"),
ingredients,
recipe.getString("url")
);
listItems.add(item);
}
adapter = new Adapter(listItems, getApplicationContext(), builtURL);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(request);
}
private String buildURL(String query) {
Log.d("q", "buildURL: " + query);
Uri.Builder builder = new Uri.Builder();
//url built here but I removed it because it shows API key etc.
String urlToSend = builder.build().toString();
//debugging purposes to show the url created
Log.d("url", "doInBackground: " + urlToSend);
return urlToSend;
}
#Override
public boolean onNavigateUp(){
finish();
return true;
}
This is the activity that I'm coming from.
public class recipe_view extends AppCompatActivity {
ImageView ivRecipeImage;
TextView tvRecipeName;
TextView tvRecipeCreator;
TextView tvRecipeIngredients;
String url;
Integer pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_view);
Bundle data = getIntent().getExtras();
ArrayList<ListItem> list = data.getParcelableArrayList("list");
pos = data.getInt("pos");
for (int i = 0; i < list.size() ; i++) {
System.out.println(list.get(i));
System.out.println(pos);
}
ivRecipeImage = findViewById(R.id.recipeImage);
tvRecipeName = findViewById(R.id.recipeName);
tvRecipeCreator = findViewById(R.id.recipeCreator);
tvRecipeIngredients = findViewById(R.id.ingredients);
tvRecipeName.setText(list.get(pos).getTitle());
tvRecipeCreator.setText(list.get(pos).getAuthor());
Picasso.with(getApplicationContext())
.load(list.get(pos).getImageUrl())
.centerCrop()
.fit()
.into(ivRecipeImage);
tvRecipeIngredients.setText(list.get(pos).getListOfIngredients());
url = list.get(pos).getRecipeUrl();
final Button button = findViewById(R.id.bViewInstructions);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
}
});
}
}
In your manifest xml
set
<activity
android:name=".your_activity"
android:label="#string/title_activity_sign_up"
android:parentActivityName=".whateveractivity"
android:screenOrientation="portrait" >
</activity>
then in code
#Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
// Otherwise defer to system default behavior.
super.onBackPressed();
}
To elaborate what you are doing is overriding the onbackpressed hardware button.
Also make your parent activity's launchmode singleInstance.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
finish();
}
});

How can i do Asynctask in ListView illegal start

I want to add listview but i get error . how can i do it ??Only listview and all https://jsonplaceholder.typicode.com/users add users
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myListView = (ListView) findViewById(R.id.listview);
txtResult = (TextView) findViewById(R.id.txt_result);
btnItemList = (Button) findViewById(R.id.btn_item_list);
/* btnItemList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetItemListTask().execute();
}
});
}*/
public void populateListView(ArrayList<String> myData){
myListView = (ListView) findViewById(R.id.listview);
//Creating an array adapter and populating it with data fetched in Async task i.e. myData
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
(List<String>) new GetItemListTask().execute());
myListView.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void setResult(Post post) {
txtResult.setText(post.getName());
}
private void setResult(ArrayList<Post> posts) {
for (Post post : posts) {
txtResult.append(post.getName());
}
}
private class GetItemListTask extends AsyncTask<Void, Void, String> {
HttpURLConnection urlConnection;
#Override
protected String doInBackground(Void... params) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://jsonplaceholder.typicode.com/users");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ArrayList<Post> posts = new Gson().fromJson(s,
new TypeToken<ArrayList<Post>>() {
}.getType());
setResult(posts);
}
}
}
My image and error
Your advice important for me
Calling Async task in activity can be done
It depend on where you are going to call it, since you run asyn task when user press a button you can call it on OnCreate() or anywhere else.
1.
new GetItemTask().execute();`
2.
.post(new Runnable() {
public void run() {
new GetItemTask().execute();
}
});

Parse Query Get Data To List

I have a list parameter List list that I am trying to pass the sList back to. How do I get the data to the super class?
Error message says Unable to resolve this.addGroups. I've tried creating a sub list of groups and assigning it, and I have tried directly assigning with List.add
UPDATED FULL CLASS
public class GroupActivity extends ActionBarActivity {
Context context;
RecyclerView groupRecyclerView;
GroupAdapter groupAdapter;
private Toolbar toolbar;
public List<Group> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("POLICE APP");
context = this;
Helpers.setTabs(context, this, 2);
groupRecyclerView = (RecyclerView) findViewById(R.id.ui_Groups_RecyclerView);
this.GetData();
groupAdapter = new GroupAdapter(this, list);
groupRecyclerView.setAdapter(groupAdapter);
groupRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void addGroups(List<Group> grps) {
this.list = grps;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_group, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void GetData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Group");
query.findInBackground(new FindCallback<ParseObject>() {
List<Group> sList;
public void done(List<ParseObject> groupList, ParseException e) {
if (e == null) {
for (int i = 0; i < groupList.size(); i++) {
try {
Group grp1 = new Group("1", groupList.get(i).getString("Name"), " Turn in your time sheets", "d");
sList.add(grp1);
Log.d("group1:", "inserted the group");
} catch (Exception c) {
c.printStackTrace();
Log.d("group1:", c.getMessage().toString());
}
}
this.addGroups.add(sList);
Log.d("groups1", "Retrieved " + groupList.size() + " groups");
} else {
Log.d("groups1", "Error: " + e.getMessage());
}
}
});
}
}
All subclasses can access all fields and methods from super class if they are not private. So, in your case, you have two options:
setList(clist); // I suppose list is private and in super class you made a setter for it
// or
this.list=cList; // if list isn't private
EDIT
How I would make super class:
public class SuperClass{
private List<Group> list;
// class's methods
public void setList(ArrayList<Group> list){
this.list = list;
}
}
EDIT No2
Inspired by your edited question ( :) ), I changed a bit your code and it should work. Test it and post results.
public class GroupActivity extends ActionBarActivity {
Context context;
RecyclerView groupRecyclerView;
GroupAdapter groupAdapter;
private Toolbar toolbar;
public List<Group> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("POLICE APP");
context = this;
Helpers.setTabs(context, this, 2);
groupRecyclerView = (RecyclerView) findViewById(R.id.ui_Groups_RecyclerView);
this.GetData();
groupAdapter = new GroupAdapter(this, list);
groupRecyclerView.setAdapter(groupAdapter);
groupRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
public void addGroups(List<Group> grps) {
this.list = grps;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_group, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void GetData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Group");
query.findInBackground(new FindCallback<ParseObject>() {
List<Group> sList = new ArrayList<Group>();
public void done(List<ParseObject> groupList, ParseException e) {
if (e == null) {
for (int i = 0; i < groupList.size(); i++) {
try {
Group grp1 = new Group("1", groupList.get(i).getString("Name"), " Turn in your time sheets", "d");
sList.add(grp1);
Log.d("group1:", "inserted the group");
} catch (Exception c) {
c.printStackTrace();
Log.d("group1:", c.getMessage().toString());
}
}
addGroups(sList);
Log.d("groups1", "Retrieved " + groupList.size() + " groups");
} else {
Log.d("groups1", "Error: " + e.getMessage());
}
}
});
}
}
You made some obvious coding mistakes, so that was the problem if I'm right. Try it.
I found the issue. I needed to add this code after the for loop.
groupAdapter = new GroupAdapter(context, list);
groupRecyclerView.setAdapter(groupAdapter);
Basically, Parse was returning async and the view didnt have the new content. Just update the view after your for loop

Row selection ListView Android

my question is how can i do something when the user touches a row on the ListView
My app loads a json file and parses it using the Volley Library then everything is loaded nicely on a custom list row
But when I hit a row it does nothing
Really annoying thing ...
Im using a custom view and it has been impossible to assign the OnListItemClick
Here is my code
//all necessary libraries here
public class InicioPasajero extends Activity {
private static final String TAG = InicioPasajero.class.getSimpleName();
// Movies json url
private static final String url = "URL_RETURNING_JSON";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
ImageButton b_ajustes;
ImageButton b_filtros;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio_pasajero);
b_ajustes= (ImageButton) findViewById(R.id.Bajustes);
b_filtros= (ImageButton) findViewById(R.id.Bfiltros);
b_ajustes.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent a=new Intent(InicioPasajero.this, MiPerfil.class);
startActivity(a);
}
});
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Cargando...");
pDialog.show();
// changing action bar color
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("n"));
movie.setThumbnailUrl(obj.getString("i"));
movie.setRating(obj.getString("r"));
movie.setYear(obj.getString("h"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("g");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
protected void onListItemClick(ListView movieList, View view, int posicion, long id) {
Log.i("Sel:","si");
// Hacer algo cuando un elemento de la lista es seleccionado
TextView textoTitulo = (TextView) view.findViewById(R.id.title);
CharSequence texto = "Seleccionado: " + textoTitulo.getText();
Toast.makeText(getApplicationContext(), texto, Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// no hacemos nada.
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Thanks in advance.
I don't see you calling setOnItemClickListener on your ListView anywhere? It also looks like you meant to have the Activity implement AdapterView.OnItemClickListener - then the overridden method named onItemClick would get called when a list item is clicked.

OnClickListener for launching webview from a listview row

A search api is returning me some meta data along with a URL "eventURL". I am placing the data in the listview, each row containing some data and a unique URL.I want when the user taps on the row in the listview,that unique URL should open in a webview.I have created a WebViewActivity for it,I am having issue with implementing the onClickListener.
MainActivity
public class MainActivity extends Activity {
//private EditText m_search_text;
private EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_search_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null ||m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("\\<.*?\\>", ""));
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
t.setText ("When:" + "\t"+meta.getString("startDate")+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" +"More Info:"+"\t" +meta.getString("eventURL")+"\n");
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}}
WebViewActivity
public class WebViewActivity extends MainActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("url");
}}
Thanks.
You need to use OnItemClickListener:
MainActivity implements OnItemClickListener {
onCreate() {
m_search_results.setOnItemClickListener(this);
Make this method:
onItemClick(AdapterView<?> parent, View view, int position, long id) {
url = JSON.getHowever(position);
//get the intent, load the url, and launch the activity
}
You also need to handle the intent in your WebViewActivity, but that's beside the question

Categories

Resources