how can split the string in java and using in spinner in android - android-spinner

I am an android developer, I am trying to split the input string, divide the state and city and using the two spinners when lode the state in first spinner corresponding city can load to the second spinner.
ArrayList arrayList1 = new ArrayList();
private String[] arr,arr1;
String input= "Tamilnadu-Chennai,Madurai,Trichy~Kerala-Kochi,Trivandrum~Karnataka-Bengaluru,Mangalore";
arr = input.split("~");
for (String output: arr) {
// Log.e("output1",output);
arr1 = output.split("-");
for (String output2 : arr1) {
Log.e("output2", output2);
arrayList1.add(output3);
ArrayAdapter<String> adp = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_dropdown_item,arrayList1);
s1.setAdapter(adp);
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String sp1= String.valueOf(s1.getSelectedItem());
Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show();
if(sp1.contentEquals("Income")) {
}
if(sp1.contentEquals("Expense")) {
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}

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.

I want add multiple Data Items of same date in single Card View in Android

I want data to be displayed as shown in imageenter image description here
I want to add multiple item of same date in single card view instead of creating another card view for the item of same date
I have tried in Android Studio grouping recycler view called as sanctioned Recycler view where I used date as header but it's not the solution
My Adapter Class
private Context mContext;
List<ListItem> consolidatedList = new ArrayList<>();
public AttendanceAdapter(Context context, List<ListItem>
consolidatedList) {
this.consolidatedList = consolidatedList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater =
LayoutInflater.from(parent.getContext());
switch (viewType) {
case ListItem.TYPE_GENERAL:
View v1 =
inflater.inflate(R.layout.attendance_adapter_layout, parent,
false);
viewHolder = new GeneralViewHolder(v1);
break;
case ListItem.TYPE_DATE:
View v2 =
inflater.inflate(R.layout.attn_item_header, parent, false);
viewHolder = new DateViewHolder(v2);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder
viewHolder, int position)
{
switch (viewHolder.getItemViewType()) {
case ListItem.TYPE_GENERAL:
GeneralItem generalItem = (GeneralItem)
consolidatedList.get(position);
GeneralViewHolder generalViewHolder=
(GeneralViewHolder) viewHolder;
//generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate());
generalViewHolder.txt_month.setText(
generalItem.getAttendance_data().getMonth_name());
generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate_no());
generalViewHolder.txt_out.setText(
generalItem.getAttendance_data().getAttn_out_time());
generalViewHolder.txt_in.setText(
generalItem.getAttendance_data().getAttn_In_time());
generalViewHolder.txtreason.setText
(generalItem.getAttendance_data().getRemark());
break;
case ListItem.TYPE_DATE:
DateItem dateItem = (DateItem)
consolidatedList.get(position);
DateViewHolder dateViewHolder = (DateViewHolder) viewHolder;
dateViewHolder.txtTitle.setText(dateItem.getDate());
// Populate date item data here
break;
}
}
class DateViewHolder extends RecyclerView.ViewHolder {
protected TextView txtTitle;
public DateViewHolder(View v) {
super(v);
this.txtTitle = (TextView)
v.findViewById(R.id.attn_date);
}
}
// View holder for general row item
class GeneralViewHolder extends RecyclerView.ViewHolder {
protected TextView
txt_in,txtreason,txt_out,txt_date,txt_month;
public GeneralViewHolder(View v) {
super(v);
this.txt_in =v.findViewById(R.id.attn_in_txt);
this.txt_out=v.findViewById(R.id.attn_out_txt);
this.txtreason=v.findViewById(R.id.attn_reason_txt);
this.txt_date=v.findViewById(R.id.date_view);
this.txt_month=v.findViewById(R.id.month_view);
}
}
#Override
public int getItemViewType(int position) {
return consolidatedList.get(position).getType();
}
#Override
public int getItemCount() {
return consolidatedList != null ? consolidatedList.size() : 0;
}
}
MainActivity.Java
public class CurrentMonth extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
attn_list_data_cur_month();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
updateUi();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void attn_list_data_cur_month(){
try {
this.connection=createConnection();
Statement stmt=connection.createStatement();
Calendar current_month_data = Calendar.getInstance();
current_month_data.add(Calendar.MONTH, 0);
//Calendar current_month_date = Calendar.getInstance();
//current_month_date.set(Calendar.DAY_OF_MONTH,0);
n=current_month_data.get(Calendar.DAY_OF_MONTH);
String current_month_year = new SimpleDateFormat("MMM-
yyyy").format(current_month_data.getTime());
String month_name=currentMonth.getText().toString();
for (int i=1;i<=n;i++) {
String date = i + "-" + current_month_year;
ResultSet resultSet = stmt.executeQuery("Select * from
MATTN_MAS where ATTN_DATE='" + date + "' and Username='" +
Username + "'");
String Attn_Type;
if (resultSet.next()) {
while (resultSet.next()) {
Attn_Type = resultSet.getString(8);
String Time = null;
String Reason = resultSet.getString(11);
if (Attn_Type.equals("I")) {
String Attn_Type_In = "I";
String Attn_Type_Out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
} else {
String Attn_Type_Out = "O";
String Attn_Type_In = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
}
}
} else {
Attn_Type = "Absent";
String Time = null;
String Reason = null;
String out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type, date, Reason,
out, i, date_no, month_name));
}
}
}catch (Exception e){
System.out.println("my Error"+e);
}
}
public void updateUi(){
//sortedData= (List<PojoOfJsonArray>)
PojoOfJsonArray.sortList(myOptions);
HashMap<String, List<Attendance_Data>> groupedHashMap =
groupDataIntoHashMap(myOptions);
for (String date1 : groupedHashMap.keySet()) {
DateItem dateItem = new DateItem();
dateItem.setDate(date1);
consolidatedList.add(dateItem);
for (Attendance_Data pojoOfJsonArray : groupedHashMap.get(date1))
{
GeneralItem generalItem = new GeneralItem();
generalItem.setAttendance_data(pojoOfJsonArray);
consolidatedList.add(generalItem);
}
}
adapter = new AttendanceAdapter(this, consolidatedList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
attn_report_view.setLayoutManager(layoutManager);
attn_report_view.setAdapter(adapter);
}
private HashMap<String, List<Attendance_Data>>
groupDataIntoHashMap(List<Attendance_Data> listOfPojosOfJsonArray) {
HashMap<String, List<Attendance_Data>> groupedHashMap = new HashMap<>
();
for (Attendance_Data pojoOfJsonArray : listOfPojosOfJsonArray) {
String hashMapKey = pojoOfJsonArray.getDate();
if (groupedHashMap.containsKey(hashMapKey)) {
// The key is already in the HashMap; add the pojo object
// against the existing key.
groupedHashMap.get(hashMapKey).add(pojoOfJsonArray);
} else {
List<Attendance_Data> list = new ArrayList<>();
list.add(pojoOfJsonArray);
groupedHashMap.put(hashMapKey, list);
}
}
return groupedHashMap;
}
I want to add multiple items of same date in same single single card view but instead it is creating multiple Card View for multiple items of same date
You have to use RecyclerView Multiple ViewTypes. for detail please check this example.
Also visit this example.
Yeah I found the solution it worked perfect for Me.....we
have to just make changes to the card View by removing
spaces..
.
like this below...
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardMaxElevation="0.1dp"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:background="#303030"
card_view:cardElevation="5dp"
android:foreground="?android:attr/selectableItemBackground"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_marginLeft="#dimen/dp_2"
android:layout_marginRight="#dimen/dp_2">
<...Your All Text Boxes and further Layout inside this
cardView...>
</android.support.v7.widget.CardView>
and I have add Header for each CardView....and it looks like
this
Outout is shown in below image

How to save the content of custom array class and adapter in list view save into text in android

I need your help I am new in android programming. How can I save all the content in the list view save into text file this is my code of try to save the file but the problem is how can i put the listview array list to get the data i don't know how to put it where to put it please help how to do it to save the content of my listview
Button code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
for (int i = 0; i < ChatBubbles.length; i++) {
myOutWriter.append(ChatBubbles[i] +"\n");
}
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Chatbubble class:
package com.example.ezminute;
public class ChatBubble {
private String content;
private boolean myMessage;
public ChatBubble(String content, boolean myMessage) {
this.content = content;
this.myMessage = myMessage;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
}
MessageAdapter:
package com.example.ezminute;
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.left_chat_bubble;
} else {
layoutResource = R.layout.right_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime. Value 2 is returned because of left and right views.
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
}
}
}

Passing content values form one activity to another in Android Studio

Activity1
private Cursor model = null;
private ClientAdapter adapter = null;
private ClientHelper helper = null;
private SharedPreferences prefs = null;
private ArrayAdapter<String> adapters;
private ArrayAdapter<String> adaptera;
private String[] available_locations;
private String[] selected_locations;
private ListView list1;
private ListView list2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locations);
list1 = (ListView) findViewById(R.id.available_locations);
list2 = (ListView) findViewById(R.id.selected_locations);
available_locations = getIntent().getStringExtra("List");
.....
Activity 2
....
public String getID(Cursor c) {
return (c.getString(0));
}
public String getclientName(Cursor c) {
return (c.getString(1));
}
public String getAddress(Cursor c) {
return (c.getString(2));
}
public String getTelephone(Cursor c) {
return (c.getString(3));
}
public String getCuisineType(Cursor c) {
return (c.getString(4));
}
public double getLatitude(Cursor c) {
return (c.getDouble(5));
}
public double getLongitude(Cursor c) {
return (c.getDouble(6));
}
public ArrayList<String> getclient;
getclient.add("clientName");
getclient.add("Address");
getclient.add("Telephone");
getclient.add("cuisineType");
getclient.add("lat");
getclient.add("lon");
public Intent intenti;
intenti = new Intent(ClientHelper.this, SetDestination.class);
intenti.putExtra("List", getclient);
startactivity(intenti);
How do I pass information from Activity2 to Activity1?
I want to do a Listview where I can select clients from the list that I have already added (hence two activity, list1 and list2, in activity1)
Use can use the Bundle to pass the data from one activity to other.
First make the object parcelable.You can do that using the plugin of Parcelable in android studio.
Example.
Intent intent=new Intent(getActivity(),targetclassname.class);
HomeScreenData homeScreenData=new HomeScreenData();//Pojo class
intent.putExtra("categorydesc",homeScreenData);
startActivity(intent);
{
//Pojo Class`enter code here`
public class HomeScreenData implements Parcelable {
private String imagePath;
private String imageTitle;
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getImageTitle() {
return imageTitle;
}
public void setImageTitle(String imageTitle) {
this.imageTitle = imageTitle;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.imagePath);
dest.writeString(this.imageTitle);
}
public HomeScreenData() {
}
protected HomeScreenData(Parcel in) {
this.imagePath = in.readString();
this.imageTitle = in.readString();
}
public static final Parcelable.Creator<HomeScreenData> CREATOR = new Parcelable.Creator<HomeScreenData>() {
public HomeScreenData createFromParcel(Parcel source) {
return new HomeScreenData(source);
}
public HomeScreenData[] newArray(int size) {
return new HomeScreenData[size];
}
};
}

Hashmap order inside the expandable listview varies from device to another

Now i'm making an application that it should display a list of courses in an expandable list view and when the user clicks on a child element it opens a new activity with the course details , everything works pretty fine but , when i tested the application through nexus the order of the courses was the same i put inside the hashmap and in the switch case statement but when i tested it through my galaxy not two here it came the disaster the orders in the list were scrambled so the click event got messed up when supposed to open course details for x it opens for y and so on ,,, what should i do ?
THIS IS THE MAIN
public class Courses extends ActionBarActivity {
HashMap<String,List<String>> Courses_castegory;
List<String> Courses_list;
ExpandableListView expandableListView;
MyCourseAdapter myCourseAdapter;
Intent detaledActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_courses);
expandableListView = (ExpandableListView) findViewById(R.id.simple_expandable_list);
Courses_castegory = CourseProvider.getInfo();
Courses_list=new ArrayList<>(Courses_castegory.keySet());//get all the keys from the hashmap
myCourseAdapter = new MyCourseAdapter(this,Courses_castegory,Courses_list);
expandableListView.setAdapter(myCourseAdapter);
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getBaseContext(), Courses_list.get(groupPosition) + " is collapsed", Toast.LENGTH_SHORT).show();
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//Toast.makeText(getBaseContext(),
//Courses_castegory.get(Courses_list.get(groupPosition)).get(childPosition)+" from "+Courses_list.get(groupPosition)+" is selected",Toast.LENGTH_SHORT).show();
switch(groupPosition) {
case 0:
switch (childPosition) {
case 0:
detaledActivity = new Intent(Courses.this, DetailedCouse.class);
startActivity(detaledActivity);
break;
}
}
return true;
}
});
}
#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_courses, 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);
}
}
THIS IS THE COURSE PROVIDER
public class CourseProvider {
public static HashMap<String,List<String>> getInfo(){
HashMap<String,List<String>>CourseDetails = new HashMap<String,List<String>>();
List<String> CourseType1 = new ArrayList<>();
CourseType1.add("English For Work");
List<String> CourseType2= new ArrayList<>();
CourseType2.add("General English For Work");
CourseType2.add("Intensive English For Work");
List<String> CourseType3 = new ArrayList<>();
CourseType3.add("English Academic Year");
CourseType3.add("English Academic Semester");
List<String> CourseType4 = new ArrayList<>();
CourseType4.add("IELTS Exam Preparation");
CourseType4.add("TOEFL Exam Preparation");
CourseType4.add("GMAT Exam Preparation");
CourseType4.add("GRE Exam Preparation");
List<String> CourseType5 = new ArrayList<>();
CourseType5.add("Young Learners");
List<String> CourseType6 = new ArrayList<>();
CourseType6.add("General English Language");
CourseType6.add("Intensive English Language");
CourseType6.add("30+");
CourseDetails.put("Learn English in Your Teacher's Home",CourseType1);
CourseDetails.put("English For Work",CourseType2);
CourseDetails.put("Academic Semester / Year",CourseType3);
CourseDetails.put("Exam Preparation Courses",CourseType4);
CourseDetails.put("Young Learners",CourseType5);
CourseDetails.put("Flexible Courses",CourseType6);
return CourseDetails;
}}
AND THIS IS THE COURSE ADAPTER
public class MyCourseAdapter extends BaseExpandableListAdapter {
private Context context;
private HashMap<String,List<String>>Courses_Category;
private List<String> Course_List ;
public MyCourseAdapter(Context context ,HashMap<String,List<String>>Courses_Category,List<String> Course_List) {
this.context=context;
this.Courses_Category=Courses_Category;
this.Course_List=Course_List;
}
#Override
public int getGroupCount() {
return Course_List.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return Courses_Category.get(Course_List.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return Course_List.get(groupPosition);
}
#Override
public Object getChild(int parent, int child) {
return Courses_Category.get(Course_List.get(parent)).get(child);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int parent, int child) {
return child;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String group_title = (String) getGroup(groupPosition);
if (convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.parent_courses,parent,false);
}
TextView parent_textview = (TextView) convertView.findViewById(R.id.parent_text_view);
parent_textview.setTypeface(null, Typeface.BOLD);
parent_textview.setText(group_title);
return convertView;
}
#Override
public View getChildView(final int parentPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String child_title = (String) getChild(parentPosition,childPosition);
if (convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.child_courses,parent,false);
}
TextView child_textview = (TextView) convertView.findViewById(R.id.child_text_view);
child_textview.setText(child_title);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void onGroupCollapsed(int groupPosition){
super.onGroupCollapsed(groupPosition);
}
public void onGroupExpanded(int groupPosition){
super.onGroupExpanded(groupPosition);
}}
//
Done using LinkedHashMapinstead of HashMap

Resources