I'm new to android. I'm building an app for city bus fare. I will use two spinners as 'starting' point and 'destination'. I want to match these two input and get the result as 'fare cost' in a textview. Please give me some easy idea of how to implement this.
use spinner.getSelectedItem() it return selected object or spinner.getSelectedItemPosition() it will return selected item position based on selection of both spinner you will calculate you fare cost
Here is the working example:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="#+id/text_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:text="RESULT"/>
<Spinner
android:id="#+id/spinner_source"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
</Spinner>
<Spinner
android:id="#+id/spinner_destination"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
</Spinner>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView textResult;
Spinner spinnerSource;
Spinner spinnerDestination;
String source;
String destination;
int cost = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Views
textResult = (TextView) findViewById(R.id.text_result);
spinnerSource = (Spinner) findViewById(R.id.spinner_source);
spinnerDestination = (Spinner) findViewById(R.id.spinner_destination);
// Spinner Drop down elements
List<String> locations = new ArrayList<String>();
locations.add("Location 1");
locations.add("Location 2");
locations.add("Location 3");
// Initialize
source = locations.get(0);
destination = locations.get(0);
// Creating adapter for spinner
ArrayAdapter<String> adapterSpinnerSource = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);
ArrayAdapter<String> adapterSpinnerDestination = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);
// attaching data adapter to spinners
spinnerSource.setAdapter(adapterSpinnerSource);
spinnerDestination.setAdapter(adapterSpinnerDestination);
// Spinner item select listener
spinnerSource.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Source location
source = parent.getItemAtPosition(position).toString();
calculateCost();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Destination location
destination = parent.getItemAtPosition(position).toString();
calculateCost();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void calculateCost() {
if ((source.equals("Location 1") && destination.equals("Location 2"))
|| (source.equals("Location 2") && destination.equals("Location 1"))) {
cost = 100;
} else if ((source.equals("Location 1") && destination.equals("Location 3"))
|| (source.equals("Location 3") && destination.equals("Location 1"))) {
cost = 200;
} else if ((source.equals("Location 2") && destination.equals("Location 3"))
|| (source.equals("Location 3") && destination.equals("Location 2"))) {
cost = 300;
}
// Output
textResult.setText(String.valueOf(cost));
}
}
OUTPUT:
Hope this will help~
Related
im new to android development and i have managed to develop an application with a listview of name, phone number and district, which is searchable and it is working really well. im using positions to click and take me to the dial pad, but the problem is, if an item is searched, it does not mantain its position given to it initially. what i want when a user searches for a name or district, it opens in the dial pad with a number written there.
Here is my contacts.java
public class Contacts extends AppCompatActivity {
ListView listView;
String[] name = {"Achibu john peter - Serere - 0772698033", "Agaba - Amon - Rukiga -
0782090694\n", "Agaja joseph - kaberamaido - 0775004193/0752451894\n",}
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("DFO Contacts");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0){
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel: +256772698033"));
startActivity(intent);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search for your DFO");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
arrayAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
and menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/search_view"
android:title="Search"
app:showAsAction="always"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
/>
</menu>
And the activity_contacts
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Contacts">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#D4AC0D"
app:subtitleTextColor="#0A0A0A"
app:titleTextColor="#111111"
/>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/poppinsmedium"
android:textSize="20sp"
android:layout_marginLeft="15dp"
android:clickable="true"
/>
</LinearLayout>
You need to use custom Array Adapter with custom Layout with a TextView and add OnClickListener for each TextView.
I've changed your code to make it work.
contacts.java
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SearchView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class Contacts extends AppCompatActivity {
ListView listView;
List<String> name;
CustomAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set Toolbar & title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("DFO Contacts");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
listView = findViewById(R.id.listview);
// Creating List<String> from valus
name = new ArrayList<>();
name.add("Achibu john peter - Serere - 0772698033");
name.add("Agaba - Amon - Rukiga - 0782090694");
name.add("Agaja joseph - kaberamaido - 0775004193");
arrayAdapter = new CustomAdapter(name, this);
listView.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem menuItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search for your DFO");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
arrayAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
CustomAdapter.java
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<String> {
private final LayoutInflater mInflater;
private final int mResource;
private Context mContext;
private List<String> orig;
private List<String> dataSet;
private int selectedPosition;
public CustomAdapter(List<String> data, Context context) {
super(context, android.R.layout.simple_list_item_1, data);
mContext = context;
// We need to make backup of original list
dataSet = data;
orig = data;
// Store for later use
mInflater = LayoutInflater.from(context);
mResource = android.R.layout.simple_list_item_1;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return createItemView(position, convertView, parent);
}
private View createItemView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(mResource, parent, false);
viewHolder.txtName = convertView.findViewById(android.R.id.text1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String item = getItem(position);
viewHolder.txtName.setText(item);
// Here we will try to extract phone number from current item
// it looks like xxxxx - xxxxx - 1234567890
// or like xxxxx - xxxxx -xxxxxx - 1234567890
// we need to extract 1234567890 here
// we will split by "-" & last one in array will be the phone number
// you may try another way to get so
String[] s = item.split("-");
String p = s[s.length-1].trim(); // Extracted Phone Number
viewHolder.txtName.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel: " + p));
mContext.startActivity(intent);
});
return convertView;
}
// View lookup cache
private static class ViewHolder {
TextView txtName;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<String> results = new ArrayList<String>();
if (orig == null)
orig = dataSet;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final String g : orig) {
if (g.toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
dataSet = (List<String>) results.values;
notifyDataSetChanged();
}
};
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public String getItem(int position) {
return dataSet.get(position);
}
}
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/search_view"
android:icon="?android:attr/actionModeWebSearchDrawable"
android:title="Search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always" />
</menu>
and activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="15dp"
android:clickable="true"
android:textSize="20sp"
tools:listitem="#android:layout/simple_list_item_1"
android:focusable="true" />
</LinearLayout>
Hope it will help.
click on textview on listview on fragment
TextView On category_row.xml textViewCategoryName
onclick SetText this textViewCategoryName ok!
CategoriesFragment.java
package com.example;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.adapter.CategoryArrayAdapter;
import com.example.model.CategoryDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class CategoriesFragment extends Fragment {
private ListView listView;
private ArrayList<CategoryDataModel> list;
private CategoryArrayAdapter adapter;
private TextView categoryCurrent;
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_categories, null);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
adapter = new CategoryArrayAdapter(getActivity(), list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getCategoryName(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
//if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataCategories().execute();
//} else {
//Snackbar.make(getActivity().findViewById(R.id.parentLayout), "اتصال به اینترنت برقرار نیست", Snackbar.LENGTH_LONG).show();
//}
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataCategories extends AsyncTask<Void, Void, Void> {
ContentLoadingProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Bar for User Interaction
*/
progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
progressBar.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_categories/");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Categories" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_CATEGORIES);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
CategoryDataModel model = new CategoryDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String category_name = innerObject.getString(Keys.KEY_CATEGORY_NAME);
String category_link = innerObject.getString(Keys.KEY_CATEGORY_LINK);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setCategoryName(category_name);
model.setCategoryLink(category_link);
/**
* Adding data in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
/**
* Progress Bar for User Interaction
*/
progressBar.hide();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
}
}
}
}
CategoryArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.CategoryDataModel;
import java.util.List;
public class CategoryArrayAdapter extends ArrayAdapter<CategoryDataModel> {
List<CategoryDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public CategoryArrayAdapter(Context context, List<CategoryDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public CategoryDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.category_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
CategoryDataModel item = getItem(position);
vh.textViewCategoryName.setText(item.getCategoryName());
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewCategoryName;
private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
this.rootView = rootView;
this.textViewCategoryName = textViewCategoryName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
return new ViewHolder(rootView, textViewCategoryName);
}
}
}
fragment_categories.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="visible" />
<ListView app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
category_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/imageViewProfilePhoto">
<TextView
android:id="#+id/textViewCategoryName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Quote Content" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
You have to set an onClickListener to your TextView in your ViewHolder.
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewCategoryName;
private ViewHolder(RelativeLayout rootView, TextView textViewCategoryName) {
this.rootView = rootView;
this.textViewCategoryName = textViewCategoryName;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewCategoryName = (TextView) rootView.findViewById(R.id.textViewCategoryName);
textViewCategoryName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do whatever you want
}
});
return new ViewHolder(rootView, textViewCategoryName);
}
}
Toast On ArrayAdapter
How to Show Toast message On QuoteArrayAdapter OnClick textViewQuoteLike
Show message Like is Done
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
/*Toast.makeText(Need Activity, "Like is done.",
Toast.LENGTH_LONG).show();*/
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
If there is a way that in HomeFragment Put it, Please give an example
QuoteArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {
List<QuoteDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public QuoteDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.quote_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
QuoteDataModel item = getItem(position);
vh.textViewQuoteContent.setText(item.getQuoteContent());
vh.textViewProfileName.setText(item.getProfileName());
vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
vh.textViewQuoteCopy.setText("کپی کردن");
vh.textViewQuoteShare.setText("اشتراک گزاری");
vh.textViewQuoteId.setText(item.getQuoteId());
Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final ImageView imageViewProfilePhoto;
public final TextView textViewQuoteContent;
public final TextView textViewProfileName;
public final TextView textViewQuoteLike;
public final TextView textViewQuoteCopy;
public final TextView textViewQuoteShare;
public final TextView textViewQuoteId;
private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId) {
this.rootView = rootView;
this.imageViewProfilePhoto = imageViewProfilePhoto;
this.textViewQuoteContent = textViewQuoteContent;
this.textViewProfileName = textViewProfileName;
this.textViewQuoteLike = textViewQuoteLike;
this.textViewQuoteCopy = textViewQuoteCopy;
this.textViewQuoteShare = textViewQuoteShare;
this.textViewQuoteId = textViewQuoteId;
}
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
}
static class GetDataLike extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Nullable
#Override
protected String doInBackground(String... params) {
String quoteId = params[0];
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?platform=true&id="+quoteId);
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
JSONObject innerObject = array.getJSONObject(jIndex);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
return quote_like;
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "circle";
}
}
}
HomeFragment.java
package com.example;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private ListView listView;
private ArrayList<QuoteDataModel> list;
private QuoteArrayAdapter adapter;
private TextView likeCurrent;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, null);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
adapter = new QuoteArrayAdapter(getActivity(), list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
if (!MainActivity.NetworkUtil.isOnline(getActivity().getApplicationContext())) {
Toast.makeText(getActivity(), "اتصال به اینترنت برقرار نیست",
Toast.LENGTH_LONG).show();
}
new GetDataHome().execute();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
new GetDataHome().execute();
}
}
});
/*
likeCurrent = (TextView) getActivity().findViewById(R.id.textViewQuoteLike);
likeCurrent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
likeCurrent.setText("Boiling Point K");
}
});*/
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataHome extends AsyncTask<Void, Void, Void> {
ContentLoadingProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Bar for User Interaction
*/
progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
progressBar.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_home/?platform=true");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Home" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_HOME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
QuoteDataModel model = new QuoteDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String profile_photo = innerObject.getString(Keys.KEY_PROFILE_PHOTO);
String profile_name = innerObject.getString(Keys.KEY_PROFILE_NAME);
String profile_link = innerObject.getString(Keys.KEY_PROFILE_LINK);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
String quote_id = innerObject.getString(Keys.KEY_QUOTE_ID);
String quote_content = innerObject.getString(Keys.KEY_QUOTE_CONTENT);
String quote_category = innerObject.getString(Keys.KEY_QUOTE_CATEGORY);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setProfilePhoto(profile_photo);
model.setProfileName(profile_name);
model.setProfileLink(profile_link);
model.setQuoteLike(quote_like);
model.setQuoteId(quote_id);
model.setQuoteContent(quote_content);
model.setQuoteCategory(quote_category);
/**
* Adding data in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
/**
* Progress Bar for User Interaction
*/
progressBar.hide();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
}
}
}
}
quote_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewProfilePhoto"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="5dp"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:src="#drawable/empty_profile_photo" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/imageViewProfilePhoto">
<TextView
android:id="#+id/textViewQuoteContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Quote Content" />
<TextView
android:id="#+id/textViewProfileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Profile Name" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textViewQuoteCopy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:clickable="true"
tools:text="Copy" />
<TextView
android:id="#+id/textViewQuoteShare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Share" />
<TextView
android:id="#+id/textViewQuoteLike"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Like" />
</LinearLayout>
</LinearLayout>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textViewQuoteId"
android:visibility="invisible" />
</RelativeLayout>
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
<ListView app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You just need a context, so:
Toast.makeText(rootView.getContext(), "Like is done.",
Toast.LENGTH_LONG).show();
But you need to make rootView final first:
public static ViewHolder create(final RelativeLayout rootView){...
^^
This activity consists of typing an ingredient (then showing it) and check a checkbox next to it. I have the following bugs that I can't get rid of (I've been searching for 5 hours for a solution):
If I press back so the keyboard hides,when I click on the search view,it never shows again but for going to the home screen and entering back again.
If I check a checkbox and scroll,there will be other checkboxes randomly checked.
How can I put in an array the ingredients that I have checked and send that array to the next activity?(activity_ingredient list)
Here is the code:
package ro.mosgoreanu.andu.foodholic;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.Arrays;
public class typing_window extends AppCompatActivity implements view.OnClickListener {
private static Button button;
String[] items;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_typing_window);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
editText = (EditText) findViewById(R.id.txtsearch);
initList();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
});
}
public void buttononClick()
{
startActivity(new Intent("ro.mosgoreanu.andu.foodholic.ingredient_list"));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
buttononClick();
break;
}
}
public void searchItem(String textToSearch){
for(String item:items) {
if(!item.contains(textToSearch)){
listItems.remove(item);
}
}
adapter.notifyDataSetChanged();
}
public void initList(){
items = new String[]{"breadcumb","butter","capiscum","carrot","cheese","cherry","chicken cutlets","cucumber","egg","flour","garlic","ham","lemon juice","mayonnaise","milk","mushroom","onion (red)","onion (white)","peas","pepper","pork","pickles","potato (red)","potato (white)","soy sauce","tomato","yogurt"};
listItems = new ArrayList<>(Arrays.asList(items));
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txt, listItems );
listView.setAdapter(adapter);
}
}
and the xml for the activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="ro.mosgoreanu.andu.foodholic.typing_window"
android:background="#89913f">
<include layout="#layout/content_typing_window" />
<EditText
android:id="#+id/txtsearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search Ingredient"
android:textAlignment="textStart"
android:paddingLeft="50dp"
android:layout_toLeftOf="#+id/imageButton"
android:layout_toStartOf="#+id/imageButton"
android:allowUndo="true" />
<SearchView
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingEnd="0dp"
android:paddingLeft="0dp"
android:translationY="-5dp"
android:focusable="true"
android:clickable="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View list"
android:id="#+id/button"
android:layout_marginRight="26dp"
android:layout_marginEnd="26dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#00ffffff"
android:translationX="280dp"
android:translationY="-2dp"
android:clickable="true"
android:allowUndo="true" />
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:foregroundTint="#ffffff"
android:paddingTop="50dp" />
</android.support.design.widget.CoordinatorLayout>
and the layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="19dp"
android:text="Add"
android:id="#+id/checkBox"
android:layout_gravity="right"
android:translationY="25dp"
android:translationX="0dp"
android:layout_marginLeft="280dp"
android:focusable="false"/>
<TextView
android:id="#+id/txt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
/>
</LinearLayout>
Hey i have done one with using ArrayAdapter and SearchViewHolder
Check it and Provide any Response.
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static Button button;
String[] items;
private Fruits[] itemss;
ArrayList<String> listItems;
ArrayAdapter<Fruits> adapter;
ListView listView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_typing_window);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
editText = (EditText) findViewById(R.id.txtsearch);
initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fruits it = adapter.getItem(position);
it.toggleChecked();
SelectViewHolder viewHolder = (SelectViewHolder) view.getTag();
viewHolder.getCheckBox().setChecked(it.isChecked());
}
});
}
private void initList() {
itemss = (Fruits[]) getLastNonConfigurationInstance();
ArrayList<Fruits> items = new ArrayList<Fruits>();
items.add(new Fruits("breadcumb"));
items.add(new Fruits("butter"));
items.add(new Fruits("capiscum"));
items.add(new Fruits("carrot"));
items.add(new Fruits("cheese"));
items.add(new Fruits("cherry"));
items.add(new Fruits("chicken cutlets"));
items.add(new Fruits("cucumber"));
items.add(new Fruits("egg"));
items.add(new Fruits("flour"));
items.add(new Fruits("garlic"));
items.add(new Fruits("ham"));
items.add(new Fruits("lemon juice"));
items.add(new Fruits("mayonnaise"));
items.add(new Fruits("milk"));
items.add(new Fruits("mushroom"));
items.add(new Fruits("onion (red)"));
items.add(new Fruits("onion (white)"));
items.add(new Fruits("peas"));
items.add(new Fruits("pepper"));
items.add(new Fruits("pork"));
items.add(new Fruits("pickles"));
items.add(new Fruits("potato (red)"));
items.add(new Fruits("potato (white)"));
items.add(new Fruits("soy sauce"));
items.add(new Fruits("tomato"));
items.add(new Fruits("yogurt"));
adapter = new ActivityAdapter(this, items);
listView.setAdapter(adapter);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.this.adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private static class Fruits {
private String name = "";
private boolean checked = false;
public Fruits() {
}
public Fruits(String name) {
this.name = name;
}
public Fruits(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
private static class SelectViewHolder {
private CheckBox checkBox;
private TextView textView;
public SelectViewHolder() {
}
public SelectViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
private static class ActivityAdapter extends ArrayAdapter<Fruits>{
private LayoutInflater inflater;
public ActivityAdapter(Context context, List<Fruits> list) {
super(context, R.layout.content_typing_window, R.id.txt, list);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruits fruit = (Fruits) this.getItem(position);
CheckBox checkBox;
TextView textView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.content_typing_window, null);
textView = (TextView) convertView
.findViewById(R.id.txt);
checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(new SelectViewHolder(textView, checkBox));
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Fruits li = (Fruits) cb.getTag();
li.setChecked(cb.isChecked());
}
});
}
else {
SelectViewHolder viewHolder = (SelectViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
checkBox.setTag(fruit);
checkBox.setChecked(fruit.isChecked());
textView.setText(fruit.getName());
return convertView;
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
break;
}
}
// public void initList(){
// items = new String[]{"breadcumb","butter","capiscum","carrot","cheese","cherry"
// ,"chicken cutlets","cucumber","egg","flour","garlic","ham","lemon juice","mayonnaise",
// "milk","mushroom","onion (red)","onion (white)","peas","pepper","pork","pickles","potato (red)",
// "potato (white)","soy sauce","tomato","yogurt"};
// listItems = new ArrayList<>(Arrays.asList(items));
// adapter = new ArrayAdapter<mItems>(this, R.layout.content_typing_window, R.id.txt, listItems );
// listView.setAdapter(adapter);
// }
#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;
}
#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);
}
}
I just want to identify that which groupView has been clicked from an expandableListView. Cause I want to send the clicked groupView's text to another activity. I have also seen this link, but it didn't solve my problem.
Identifying the group that has been clicked in an expandableListView
I also tried by sending the groupPosition and it still didn't solve my problem.
Here is my code.
CategoryList.java:
package com.remindme.sayem.remindme;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class CategoryList extends AppCompatActivity {
private ExpandableListView categoryListView;
private CategoryListAdapter categoryListAdapter;
List<String> listDataHeader;
HashMap<String, List<String> > listDataChild;
int group_size, child_size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_list);
categoryListView = (ExpandableListView) findViewById(R.id.categoryListView);
prepareListData();
categoryListAdapter = new CategoryListAdapter(this, listDataHeader, listDataChild);
categoryListView.setAdapter(categoryListAdapter);
categoryListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if(categoryListAdapter.getChildrenCount(groupPosition) == 0){
Intent intent = new Intent(CategoryList.this, ItemEditorActivity.class);
intent.putExtra("GROUP_POSITION", groupPosition);
startActivity(intent);
}
return false;
}
});
}
private void prepareListData(){
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String> >();
// Adding group data
listDataHeader.add("Pharmacy");
listDataHeader.add("Super Shop");
listDataHeader.add("Stationery Shop");
listDataHeader.add("Market");
listDataHeader.add("Hotel");
listDataHeader.add("Hardware shop");
listDataHeader.add("Computer Accessories Shop");
listDataHeader.add("Others");
// Adding child data
List<String> pharmacy = new ArrayList<String>();
pharmacy.add("a");
pharmacy.add("a");
pharmacy.add("a");
pharmacy.add("a");
pharmacy.add("a");
List<String> super_shop = new ArrayList<String>();
List<String> stationery_shop = new ArrayList<String>();
List<String> market = new ArrayList<String>();
List<String> hotel = new ArrayList<String>();
List<String> hardware_shop = new ArrayList<String>();
List<String> computer_accessories_shop = new ArrayList<String>();
List<String> others = new ArrayList<String>();
listDataChild.put(listDataHeader.get(0), pharmacy);
listDataChild.put(listDataHeader.get(1), super_shop);
listDataChild.put(listDataHeader.get(2), stationery_shop);
listDataChild.put(listDataHeader.get(3), market);
listDataChild.put(listDataHeader.get(4), hotel);
listDataChild.put(listDataHeader.get(5), hardware_shop);
listDataChild.put(listDataHeader.get(6), computer_accessories_shop);
listDataChild.put(listDataHeader.get(7), others);
}
public class CategoryListAdapter extends BaseExpandableListAdapter{
private Context _context;
private List<String> _listDataHeader; // Header titles
private HashMap<String, List<String> > _listDataChild; // Child Items
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
public CategoryListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listDataChild;
}
#Override
public int getGroupCount() {
group_size = this._listDataHeader.size();
return group_size;
}
#Override
public int getChildrenCount(int groupPosition) {
child_size = this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
//CategoryList.this.group_size = groupPosition;
return child_size;
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.category_item, null);
}
TextView categoryItem = (TextView) convertView.findViewById(R.id.categoryItem);
categoryItem.setText(getGroup(groupPosition).toString());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = layoutInflater.inflate(R.layout.item_name, null);
}
TextView itemName = (TextView) convertView.findViewById(R.id.itemName);
itemName.setText(getChild(groupPosition, childPosition).toString());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
ItemEditorActivity.java:
package com.remindme.sayem.remindme;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ItemEditorActivity extends AppCompatActivity implements View.OnClickListener{
EditText itemEditorEditText;
Button doneButton;
Button addDataButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_editor);
itemEditorEditText = (EditText) findViewById(R.id.itemEditorEditText);
doneButton = (Button) findViewById(R.id.doneButton);
addDataButton = (Button) findViewById(R.id.addDataButton);
addDataButton.setOnClickListener(this);
doneButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addDataButton:
String itemEditorString = itemEditorEditText.getText().toString();
ItemListDatabase itemListDatabase = new ItemListDatabase(ItemEditorActivity.this);
itemListDatabase.open();
if (getIntent().getIntExtra("GROUP_POSITION", 0) == 0)
{
itemListDatabase.insertDataIntoPharmacy(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 1){
itemListDatabase.insertDataIntoSuperShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 2){
itemListDatabase.insertDataIntoStationeryShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 3){
itemListDatabase.insertDataIntoMarket(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 4){
itemListDatabase.insertDataIntoHotel(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 5){
itemListDatabase.insertDataIntoHardwareShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
else if (getIntent().getIntExtra("GROUP_POSITION", 0) == 6){
itemListDatabase.insertDataIntoComputerAccessoriesShop(itemEditorString);
Toast.makeText(this, "Added", Toast.LENGTH_SHORT).show();
itemEditorEditText.setText("");
}
itemListDatabase.close();
break;
case R.id.doneButton:
Intent intent = new Intent(ItemEditorActivity.this, CategoryList.class);
startActivity(intent);
break;
}
}
}
activity_category_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.remindme.sayem.remindme.CategoryList"
>
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/categoryListView"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:dividerHeight="0.5dp"
android:divider="#7AA410"
/>
</RelativeLayout>
activity_item_editor.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.remindme.sayem.remindme.ItemEditorActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/itemEditorEditText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="Add Data"
android:id="#+id/addDataButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="DONE"
android:id="#+id/doneButton" />
</LinearLayout>
</RelativeLayout>
category_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textAllCaps="false"
android:textColor="#7AA410"
android:text="Large Text"
android:paddingLeft="30dp"
android:id="#+id/categoryItem" />
</LinearLayout>
item_name.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textAllCaps="false"
android:text="Medium Text"
android:id="#+id/itemName" />
</LinearLayout>
EDIT_CODE
I made this change of categoryListView.setOnGroupClickListener() method inside the CategoryList.java.
categoryListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if(categoryListAdapter.getChildrenCount(groupPosition) == 0){
Intent intent = new Intent(CategoryList.this, ItemEditorActivity.class);
String text = categoryListAdapter.getGroupText(groupPosition);
intent.putExtra("GROUP_POSITION", text);
Toast.makeText(CategoryList.this, "Group Position: " + text, Toast.LENGTH_LONG).show();
startActivity(intent);
}
return false;
}
});
Also I added a new function getGroupText() in the CategoryListAdapter class inside the CategoryList.java.
public String getGroupText(int groupPosition){
return this._listDataHeader.get(groupPosition).toString();
}
After that I edited the ItemEditorActivity.java like this.
package com.remindme.sayem.remindme;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ItemEditorActivity extends AppCompatActivity implements View.OnClickListener{
EditText itemEditorEditText;
Button doneButton;
Button addDataButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_editor);
itemEditorEditText = (EditText) findViewById(R.id.itemEditorEditText);
doneButton = (Button) findViewById(R.id.doneButton);
addDataButton = (Button) findViewById(R.id.addDataButton);
addDataButton.setOnClickListener(this);
doneButton.setOnClickListener(this);
}
#Override
protected void onPause() {
super.onPause();
finish();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.addDataButton:
ItemListDatabase itemListDatabase = new ItemListDatabase(this);
String itemEditorString = itemEditorEditText.getText().toString();
ItemNameClass itemNameClass = new ItemNameClass(itemEditorString);
String group_position = getIntent().getStringExtra("GROUP_POSITION");
if (group_position.equals("Pharmacy"))
{
itemListDatabase.insertDataIntoPharmacy(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Super Shop")) {
itemListDatabase.insertDataIntoSuperShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Stationery Shop")) {
itemListDatabase.insertDataIntoStationeryShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Market")) {
itemListDatabase.insertDataIntoMarket(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Hotel")) {
itemListDatabase.insertDataIntoHotel(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Hardware Shop")) {
itemListDatabase.insertDataIntoHardwareShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
else if (group_position.equals("Computer Accessories Shop")){
itemListDatabase.insertDataIntoComputerAccessoriesShop(itemNameClass);
Toast.makeText(getApplicationContext(), "Added to " + group_position, Toast.LENGTH_LONG).show();
itemEditorEditText.setText("");
}
break;
case R.id.doneButton:
Intent intent = new Intent(ItemEditorActivity.this, CategoryList.class);
startActivity(intent);
break;
}
}
}