Creating a very custom list - android-studio

I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>
filled by data from database.
Thank you

Here it is:
public class Avancee extends Activity {
// Log tag
private static final String TAG = MainActivity2.class.getSimpleName();
// Movies json url
private static final String url = "http://blabla.com/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// 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();
String result = getIntent().getStringExtra("ITEM_EXTRAA");
System.out.println(result);
try{
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
try {
JSONObject obj = ja.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setLocation(obj.getString("location_search_text"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
// 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);
}
#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;
}
}
It's the "id" that I want to get in the OnClick event.

use this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Movie movie= movieList.get(position);
}
});
//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object

Related

Searchview should filter only first 5 characters from a listview androidstudio

When i search it should only search first five characters from the array,
this is an app for finding dreams meaning, its like a dictionary app.
I added 2 listviews, and using a searchview to filter the results. but when i use searchview its searching the whole content in the array, and listing the result based on it which cause wrong results.
if i could search only the first five characters from these arrays, it will help me to get right results.
this is how i get the data from database
listView2 = findViewById(R.id.listView2);
sr_txt = findViewById(R.id.sr_txt);
listView = findViewById(R.id.listView);
databaseReference = FirebaseDatabase.getInstance().getReference("dreamapp");
dream1 = new Dream();
title_list = new ArrayList<>();
answer_list = new ArrayList<>();
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.item, title_list);
arrayAdapter2 = new ArrayAdapter<>(this, R.layout.item2, R.id.item2, answer_list);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot d : snapshot.getChildren()) {
dream1 = d.getValue(Dream.class);
title_list.add(dream1.getTitle());
answer_list.add(dream1.getAnswer());
}
listView.setAdapter(arrayAdapter);
listView2.setAdapter(arrayAdapter2);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, answer.class);
// String q = answer_list.get(i);
// String p =answer_list.get(i);
String q = (String) arrayAdapter2.getItem(i);
intent.putExtra("answer", q);
startActivity(intent);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
this is my searchview.
sr_txt.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
MainActivity.this.arrayAdapter.getFilter().filter(query);
MainActivity.this.arrayAdapter2.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
MainActivity.this.arrayAdapter.getFilter().filter(newText);
MainActivity.this.arrayAdapter2.getFilter().filter(newText);
return false;
}
});
Please give more detail of what you want.It would be more clear if you dont mind uploading image of what you are getting and what you want.

If Statement Not Executed in AutocompleteTextView

I'm new to Android Studio and currently working on my first app. Thanks to numerous examples on here i have managed to catch up on the basics very quickly. I now have a problem with my autocompletetextview, i want to get the text selected then use it in a if statement to determine what is shown on the "results" textview. The if statement works fine but only for the "else" part and i can't figure out where i went wrong.
I have commented out the onItemClickListener because the "testfoodph" method does the same.
Here is the activity code:
public class phTester extends AppCompatActivity {
Intent intent = getIntent();
AutoCompleteTextView text;
MultiAutoCompleteTextView text1;
TextView results;
String foodies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ph_tester);
String[] foods = getResources().getStringArray(R.array.foodlist);
text=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foods);
text.setAdapter(adapter);
text.setThreshold(1);
results=(TextView)findViewById(R.id.phResults);
foodies = text.getText().toString();
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if (foodies.equalsIgnoreCase("Mango")) {
//results.setText(getString(R.string.phAlk));
}
//else {
//results.setText(getString(R.string.Error));
//}
//}
});
}
public void TestFoodPH(View view) {
if (foodies.equalsIgnoreCase("Mango")) {
results.setText(getString(R.string.phAlk));
}
else {
results.setText(getString(R.string.Error));
}
}

How to implement Custom Suggestions in SearchView from fragment

i have a view pager with 3 fragment one of the fragment
have searchview widget and i get to know that i can,t implement the standard search interface so i implement some thing like this but how to implement Custom Suggestions in SearchView
public class LoaderCursor extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
// Create the list fragment and add it as our sole content.
if (fm.findFragmentById(android.R.id.content) == null) {
CursorLoaderListFragment list = new CursorLoaderListFragment();
fm.beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class CursorLoaderListFragment extends ListFragment
implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {
// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
// If non-null, this is the current filter the user has provided.
String mCurFilter;
#Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null,
new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
#Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Place an action bar item for searching.
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
SearchView sv = new SearchView(getActivity());
sv.setOnQueryTextListener(this);
item.setActionView(sv);
}
public boolean onQueryTextChange(String newText) {
// Called when the action bar search text has changed. Update
// the search filter, and restart the loader to do a new query
// with this filter.
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
getLoaderManager().restartLoader(0, null, this);
return true;
}
#Override public boolean onQueryTextSubmit(String query) {
// Don't care about this.
return true;
}
#Override public void onListItemClick(ListView l, View v, int position, long id) {
// Insert desired behavior here.
Log.i("FragmentComplexList", "Item clicked: " + id);
}
// These are the Contacts rows that we will retrieve.
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
Contacts.CONTACT_STATUS,
Contacts.CONTACT_PRESENCE,
Contacts.PHOTO_ID,
Contacts.LOOKUP_KEY,
};
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
Uri.encode(mCurFilter));
} else {
baseUri = Contacts.CONTENT_URI;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
}
}

Android Contextual Action Bar not appearing after item selection

In my android application, I am trying to show contextual action bar (CAB) in listview for item delete. The problem is that whenever an item is pressed for long, the item gets selected, but CAB doesn't appear. I have verified with so many tutorials, can't figure out what am I missing. Any help would be appreciated.
Adapter Class
public class DuasListAdapter extends ArrayAdapter<String>{
// class variables
private final Context context;// to save context
private final List<String> duas;// to save list of stores
LayoutInflater inflater;//
private SparseBooleanArray selectedItemsIds;
public DuasListAdapter(Context ctx,int resourceId, List<String> duasList) {
super(ctx, resourceId, duasList);
selectedItemsIds = new SparseBooleanArray();
context = ctx;// save context
duas = duasList;// save list of stores
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);// save inflater layout
}
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.adapter_list_duas, null);
convertView.setTag(holder);
holder.duaIndex = position;
holder.background = (LinearLayout) convertView.findViewById(R.id.ll_duas_list);
holder.iv_duatype = (ImageView) convertView.findViewById(R.id.iv_duatype);
holder.tv_dua_arabic = (TextView) convertView.findViewById(R.id.tv_dua_arabic);
holder.tv_dua_no = (TextView) convertView.findViewById(R.id.dua_no);
}
else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
static class ViewHolder {
int duaIndex;
LinearLayout background;// background to display color for read and unread messages
ImageView iv_duatype;
TextView tv_dua_arabic;// title of message
TextView tv_dua_ref;// message by and message created on
TextView tv_dua_no;
/**
* #description constructor to save context and list of stores views
* #param v to refer the view
* #return
*/
}
public void remove(List<String> object){
duas.remove(object);
notifyDataSetChanged();
}
public List<String> getDuas(){
return duas;
}
public void toggleSelection(int position) {
selectView(position, !selectedItemsIds.get(position));
}
public void removeSelection() {
selectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
selectedItemsIds.put(position, value);
else
selectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return selectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return selectedItemsIds;
}
}
Fragment Class
Context context;
LinearLayout ll_back_duas_list_header;
TextView ll_back_duas_list_header_title;
ListView lvDuaas;
public static DuasListAdapter duasAdapter;
ActionMode mAction;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = inflater.getContext();
View view = inflater.inflate(R.layout.fragment_list_duas, container, false);
ll_back_duas_list_header = (LinearLayout) view.findViewById(R.id.ll_back_duas_list_header);
ll_back_duas_list_header_title = (TextView) view.findViewById(R.id.ll_back_duas_list_header_title);
lvDuaas = (ListView) view.findViewById(R.id.lv_duas);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
final ArrayList<String> duas = new ArrayList<String>();
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].length() > 0)
duas.add(versesList[i]);
}
duasAdapter = new DuasListAdapter(context,R.layout.adapter_list_duas,duas);
lvDuaas.setAdapter(duasAdapter);
lvDuaas.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
lvDuaas.setChoiceMode(lvDuaas.CHOICE_MODE_MULTIPLE);
lvDuaas.setItemChecked(position, true);
mAction = getActivity().startActionMode(modeCallBack);
view.setSelected(true);
return true;
}
});
super.onActivityCreated(savedInstanceState);
}
ActionMode.Callback modeCallBack = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
mode.getMenuInflater().inflate(R.menu.activity_main, menu);
return false;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = duasAdapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
String selecteditem = duasAdapter.getItem(selected.keyAt(i));
// Remove selected items following the ids
duasAdapter.remove(selecteditem);
}
}
// Close CAB
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
duasAdapter.removeSelection();
}
};
}
XML file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:id="#+id/delete"
android:title="#string/delete"
/>
</menu>
From looking at your code I can see the onCreateActionMode callback function returns false.
onCreateActionMode should return true if the action mode should be created, false if entering this mode should be aborted.
So when the user long clicks on the ListItem and the event is triggered it reaches onCreateActionMode and returns false. Telling it to abort. Hence no CAB menu appears. Try changing it to true and also adding in some logs to see if it ever makes it into the callback function.
This would be the change below:
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
Log.d("Test","In onCreateActionMode");
mode.getMenuInflater().inflate(R.menu.activity_main, menu);
return true;//code updated here
}
Android Link to reference : http://developer.android.com/reference/android/view/ActionMode.Callback.html#onCreateActionMode(android.view.ActionMode, android.view.Menu)

Search Location on Action Bar Android

I want to ask about finding a location using the action bar. I've made ​​the program as shown below :
I've made a class to find location. but at the time I called into the EditText search, class does not work.
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
map.clear();
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++){
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
map.addMarker(markerOptions);
// Locate the first location
if(i==0)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));
}
}
and I had to call the class to the class action bar menu. like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cost_direction, menu);
/** Get the action view of the menu item whose id is search */
View v = (View) menu.findItem(R.id.search).getActionView();
/** Get the edit text from the action view */
EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
/** Setting an action listener */
txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Getting user input location
String location = v.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
Toast.makeText(getBaseContext(), "Search : " + v.getText(), Toast.LENGTH_SHORT).show();
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
please help for those who know about the problems I was having. :)
String strPlace = etSearch.getText().toString();
Geocoder gc = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> adrs = null;
try{
adrs = gc.getFromLocationName(strPlace,5);
}catch(IOException e){
}finally{
if (adrs != null){
if(adrs.size() > 0)
{
LatLng loc = new LatLng(adrs.get(0).getLatitude(), adrs.get(0).getLongitude());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(13), 2000, null);
}

Resources