How to change setText when i delete the data - android

I want to change my Button text when i delete the items
i already checked it getText, when i getText it shows that the data
already changed but when i try to setText, it's not show to me
In this case what shold i do?
This is my f_productAdapter
package com.example.together.Adapter;
import android.content.Context;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.example.together.Activities.EditProfileActivity.TAG;
public class f_productAdapter extends BaseAdapter {
Button b;
LayoutInflater inflater = null;
private ArrayList<FuneralProdcutOrder> list;
public f_productAdapter(ArrayList<FuneralProdcutOrder> f_order) {
super();
list = f_order;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return list.get(position).hashCode();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_funeralorder, parent, false);
}
TextView tv_name = convertView.findViewById(R.id.productnm); //상품이름
TextView tv_price = convertView.findViewById(R.id.productpri); //상품 가격
ImageView tv_img = convertView.findViewById(R.id.pro_img);
Button tv_delete = convertView.findViewById(R.id.deleteBtn);
FuneralProdcutOrder getProlist = list.get(position);
tv_name.setText(getProlist.getName());
tv_price.setText(getProlist.getPrice());
Picasso.get().load(getProlist.getImg()).fit().into(tv_img);
LayoutInflater inflaters = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View Toplayout = inflaters.inflate(R.layout.activity_goodbyepet_reservation_result, null );
//
b = Toplayout.findViewById(R.id.f_orderBtn);
TextView test = Toplayout.findViewById(R.id.toolbar_title);
Log.e("test",test.getText()+"");
// Log.e("view context", parent.getContext()+"");
// Log.e("view position", position+"");
// Log.e("view count", list.size()+"");
// Log.e("view",b.getText()+"");
// b.setText("테스트");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("view alert" ,"확실히 버튼 객체를 찾았습니다 눌림");
}
});
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
return convertView;
}
}
This is my reservationResultActivity
package com.example.together.Activities.GoodbyePet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import com.example.together.Adapter.f_productAdapter;
import com.example.together.Model.FuneralProdcutOrder;
import com.example.together.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class GoodbyepetReservationResultActivity extends AppCompatActivity {
// private TextView tvParent, tvChild;
Toolbar myToolbar;
ListView funeralview;
Button Btn;
private ArrayList<FuneralProdcutOrder> f_order = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goodbyepet_reservation_result);
int total_price = 0;
//리스트뷰선언
funeralview = findViewById(R.id.funeral_order);
//예약 버튼
Btn = findViewById(R.id.f_orderBtn);
//툴바 선언
myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
//액션바 왼쪽에 버튼
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_btn_back);
getSupportActionBar().setDisplayShowTitleEnabled(false);
for (int i = 0; i < MyCategoriesExpandableListAdapter.parentItems.size(); i++ ) {
for (int j = 0; j < MyCategoriesExpandableListAdapter.childItems.get(i).size(); j++ ){
String isChildChecked = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.IS_CHECKED);
if (isChildChecked.equalsIgnoreCase(ConstantManager.CHECK_BOX_CHECKED_TRUE)) {
// tvParent.setText(tvParent.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME));
// tvChild.setText(tvChild.getText() + MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE));
String name = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_NAME);
String price = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_PRICE);
String img = MyCategoriesExpandableListAdapter.childItems.get(i).get(j).get(ConstantManager.Parameter.SUB_CATEGORY_IMAGE);
f_order.add(new FuneralProdcutOrder(name,price,img));
total_price = total_price + Integer.parseInt(price);
}
}
}
f_productAdapter orAdapter = new f_productAdapter(f_order);
// orAdapter.setHasStableId(true);
Log.e("view activiey", f_order.size()+"안녕");
funeralview.setAdapter(orAdapter);
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//액션바 등록
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alldelete_manu, menu) ;
return true ;
}
//액션바 클릭 이벤트
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// ((TextView)findViewById(R.id.textView)).setText("SEARCH") ;
return true;
case R.id.settings:
// ((TextView)findViewById(R.id.textView)).setText("ACCOUNT") ;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
What i want to do
when i delete the button directly change buttons text also change
but setText() is not working
how to change that?
Click delete button
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
What i want to change the button text
Btn.setText(f_order.size()+"개 " + total_price+" 원 예약 신청하기");
This is my XML That include button what i want to change the text
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".Activities.GoodbyePet.GoodbyepetReservationResultActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/mdtp_white"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="예약 상세서"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
/>
</android.support.v7.widget.Toolbar>
<ListView
android:id="#+id/funeral_order"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:drawSelectorOnTop="false">
</ListView>
<Button
android:id="#+id/f_orderBtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:layout_margin="10dp"
android:text="바뀌어주세요"
android:background="#drawable/button_radius"
android:textSize="18dp"/>
</LinearLayout>

Create an interface class like this;
You can set many kind of information as a parameter about your deleted item and send it to your activity.
public interface ItemSelectedListener{
void onItemSelected(boolean isDeleted);
}
In your adapter initialize your interface;
private List<ItemSelectedListener> mItemSelectedSubscribers = new ArrayList<ItemSelectedListener>();
Add this method in your adapter ;
public void subscribeItemSelection(ItemSelectedListener listener) {
mItemSelectedSubscribers .add(listener);
}
Set this loop in your click events;
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (ItemSelectedListener listener : mItemSelectedSubscribers ) {
listener.onItemSelected(true);
}
list.remove(position);
b.setText("Show me~~~~ u r change!!!");
notifyDataSetChanged();
Log.d(TAG, "onClick: What is you?"+list.size());
}
});
In your activity, implement your interface and you will set a implemented methods. this methods look like this;
boolean isDeleted;
#Override
public void onItemSelected(boolean isDeleted) {
this.isDeleted = isDeleted;
}
You know now item is deleted or not. When a button deleted you can change text by using your method.
if(isDeleted){
btn.setText(changeText)
}
Hope this help!

Related

How do I get each textview resource amount and add them all together into a single variable to be converted into a two sliced pie chart?

This is the code I have been working on for a while. The only issue is I cannot seem to be able to get the sum of values input into the editText fields that are dynamically added into the program and then place them into a pie chart. The data is to be transferred from the second activity to the third where the third activity will add up all resource amounts and display them into a pie chart.
SecondActivity.class
package com.example.a4mob;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.drawerlayout.widget.DrawerLayout;
import java.util.ArrayList;
import java.util.List;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
private LinearLayout linearLayout;
private Button add;
//for button add resource
List<String> ColourList = new ArrayList<>();
ArrayList<Results> resultList = new ArrayList<>();
private Button submit;
private Number uinput;
#Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.secondactivity);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout = findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// to make the Navigation drawer icon always appear on the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
// Define ColorDrawable object and parse color
// using parseColor method
// with color hash code as its parameter
ColorDrawable colorDrawable
= new ColorDrawable(Color.parseColor("grey"));
// Set BackgroundDrawable
actionBar.setBackgroundDrawable(colorDrawable);
//Adds more objects
linearLayout = findViewById(R.id.layout_list);
add = findViewById(R.id.CreateNew);
add.setOnClickListener(this);
ColourList.add("grey");
ColourList.add("green");
ColourList.add("blue");
ColourList.add("yellow");
// Creating submit button click listener
submit = findViewById(R.id.Submit);
submit.setOnClickListener(this);
}
public void onClick(View view){
switch (view.getId()){
case R.id.CreateNew:
addView();
break;
case R.id.Submit:
if(isValid()){
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", resultList);
intent.putExtras(bundle);
startActivity(intent);
}
break;
}
}
private boolean isValid() {
resultList.clear();
boolean valid = true;
for(int i = 0; i < linearLayout.getChildCount(); i++){
View resultView = linearLayout.getChildAt(i);
EditText resultName = (EditText) resultView.findViewById(R.id.RName);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) resultView.findViewById(R.id.ColourOP);
Results results = new Results();
if(!resultName.getText().toString().equals("")){
results.setResName(resultName.getText().toString());
}else{
valid = false;
break;
}
if(!resultNumber.getText().toString().equals("")){
results.setResAmount(Integer.parseInt(resultNumber.getText().toString()));
}else{
valid = false;
break;
}
if(COP.getSelectedItemPosition()!=0){
}else{
valid = false;
break;
}
resultList.add(results);
}
if(resultList.size() == 0){
valid = false;
Toast.makeText(this, "Complete all fields first", Toast.LENGTH_SHORT).show();
} else if(!valid){
Toast.makeText(this, "Enter details correctly", Toast.LENGTH_SHORT).show();
}
return valid;
}
public void addAmount(){
for(int i = 0; i < linearLayout.getChildCount(); i++) {
View resultView = linearLayout.getChildAt(i);
EditText resultNumber = (EditText) resultView.findViewById(R.id.RAmount);
Results results = new Results();
}
}
private void sub(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please input inventory space:");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
uinput = input.getInputType();
changeAct();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private void changeAct(){
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
private void addView(){
View newResource = getLayoutInflater().inflate(R.layout.row_add_data, null, false);
ImageView imageClose = (ImageView)newResource.findViewById(R.id.Remove);
TextView RN = (TextView) newResource.findViewById(R.id.RName);
TextView RA = (TextView) newResource.findViewById(R.id.RAmount);
AppCompatSpinner COP = (AppCompatSpinner) newResource.findViewById(R.id.ColourOP);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ColourList);
COP.setAdapter(arrayAdapter);
imageClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeView(newResource);
}
});
linearLayout.addView(newResource);
}
private void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
super.onPointerCaptureChanged(hasCapture);
}
}
ThirdActivity.class
package com.example.a4mob;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ThirdActivity extends AppCompatActivity {
RecyclerView recycle_results;
ArrayList<Results> resultList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
recycle_results = findViewById(R.id.res_results);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recycle_results.setLayoutManager(linearLayoutManager);
resultList = (ArrayList<Results>) getIntent().getExtras().getSerializable("list");
recycle_results.setAdapter(new ResultsAdapter(resultList));
}
}
Results.class
package com.example.a4mob;
import java.io.Serializable;
public class Results implements Serializable {
public String resourceName;
public int resourceAmount;
public int totalAmount;
public Results(){
}
public int getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(int totalAmount) {
this.totalAmount = totalAmount;
}
public int getResAmount() {
return resourceAmount;
}
public void setResAmount(int resourceAmount) {
this.resourceAmount = resourceAmount;
}
public Results(String resourceName, int resourceAmount){
this.resourceName = resourceName;
this.resourceAmount = resourceAmount;
}
public String getResName() {
return resourceName;
}
public void setResName(String resourceName) {
this.resourceName = resourceName;
}
}
ResultsAdapter.class
package com.example.a4mob;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.ResultsView> {
ArrayList<Results> resultList = new ArrayList<>();
int total;
public ResultsAdapter(ArrayList<Results> resultList) {
this.resultList = resultList;
}
#NonNull
#Override
public ResultsView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_results,parent,false);
return new ResultsView(view);
}
#Override
public void onBindViewHolder(#NonNull ResultsView holder, int position) {
Results results = resultList.get(position);
holder.resourceName.setText(results.getResName());
holder.resourceAmount.setText(String.valueOf(results.getResAmount()));
}
#Override
public int getItemCount() {
return resultList.size();
}
public class ResultsView extends RecyclerView.ViewHolder{
TextView resourceName, resourceAmount, resourceTotal;
public ResultsView(#NonNull View itemView) {
super(itemView);
resourceName = (TextView) itemView.findViewById(R.id.resNa);
resourceAmount = (TextView) itemView.findViewById(R.id.resAm);
resourceTotal = (TextView) itemView.findViewById(R.id.resTot);
}
}
}
thirdactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".ThirdActivity">
<LinearLayout
android:id="#+id/layoutThird"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/res_results"
android:layout_width="match_parent"
android:layout_height="match_parent"></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
row_results.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="#color/white"
android:layout_margin="5dp"
android:layout_marginBottom="20dp"
app:cardCornerRadius="10dp"
app:cardElevation="10dp">
<LinearLayout
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginBottom="0dp">
<TextView
android:id="#+id/resNa"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Name"
android:textSize="18sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resAm"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
<TextView
android:id="#+id/resTot"
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Resource Amount"
android:textSize="14sp"
android:textColor="#color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>

Change the text in search view when item in listview is clicked

When I write query in Searchview a list of items(Suggestions list) is apppeared and filtered as per the QueryText changed. When i click the list item the text of filtered list does not appear in the search view.
I want the filtered list item to appear in the search view when clicked. But Here the Item of the unfiltered list appears when i click the filtered list
How can I Solve this problem?
Xml file:
<?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"
tools:context=".MySearchView"
android:orientation="vertical"
android:padding="30dp">
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="Search here..."
android:iconifiedByDefault="false"
android:focusedByDefault="true"
android:transitionName="Search_box"
android:id="#+id/search_view">
</SearchView>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:id="#+id/list_view">
</ListView>
</LinearLayout>
java file:
package edmt.dev.androidgridlayout;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import edmt.dev.androidgridlayout.HelperClasses.HomeAdapter.FeaturedHelperClass;
import edmt.dev.androidgridlayout.HelperClasses.HomeAdapter.ProductAdapter;
public class MySearchView extends AppCompatActivity {
SearchView searchView;
ListView listView;
ArrayList<String> list,catid;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_search_view);
searchView=findViewById(R.id.search_view);
searchView.requestFocusFromTouch();
listView=findViewById(R.id.list_view);
list =new ArrayList<String>();
catid =new ArrayList<String>();
String url = getResources().getString(R.string.url);
String SelectCategory = url + "request=SelectCategory";
System.out.println(SelectCategory);
AndroidNetworking.get(SelectCategory)
.setPriority(Priority.LOW)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
JSONObject jo;
try {
for (int i = 0; i < response.length(); i++) {
jo = response.getJSONObject(i);
String sid = jo.getString("id");
String sname = jo.getString("title");
list.add(sname);
catid.add(sid);
}
adapter=new ArrayAdapter<>(getApplicationContext(),R.layout.dropdown_item,list);
listView.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "JSON Error" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onError(ANError anError) {
anError.printStackTrace();
Toast.makeText(getApplicationContext(), "unsuccessful : error is :" + anError.getMessage(), Toast.LENGTH_LONG).show();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent intent=new Intent(getApplicationContext(),AllProductPage.class);
intent.putExtra("categoryid","0");
intent.putExtra("categorytitle",query);
intent.putExtra("request","MySearchView");
startActivity(intent);
Toast.makeText(getApplicationContext(),"searchview"+query,Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
searchView.setQuery(list.get(position),false);
}
});
}
}

Trying to get callbacks from DialogFragment to a fragment but the app is crashing

My app's MainActivity has a ViewPager which has three children(swipe views). When swiped to last child, the ActionBar gets two menu items. On clicking one item, a Dialog pops up to add a name of an item into a Database. On clicking second menu item, another Dialog pops up that prompts user to enter the name of the item that is to be removed from the Database. These Dialogs are getting constructed by separate Dialog Fragments. Basically what I want is to get the callback event from the Dialog that the positive or negative button has been clicked and wanna perform some action in the fragment which is as I mentioned is the last child of my ViewPager. I've seen the Android documentation as well as a Youtube video to learn how to implement the interface, yet my app's crashing.
Here's the code for my DialogFragment which shows a Dialog that prompts the user to enter input and save it to the Database.
package com.example.android.mybusiness;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class AddCigaretteNameDialog extends DialogFragment {
EditText userInput;
String cigaretteName;
DbHelper dbHelper;
public AddCigaretteNameDialogListener listener;
public interface AddCigaretteNameDialogListener {
void onDialogPositiveClick(String name);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dbHelper = new DbHelper(getContext());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// SET THE TITLE FOR THE DIALOG.
builder.setTitle(R.string.add_title);
// GET THE LAYOUT INFLATOR
LayoutInflater inflater = getActivity().getLayoutInflater();
// INFLATE THE LAYOUT AND PUT IT INTO A VARIABLE.
// PASS NULL AS PARENT VIEW, BECAUSE IT'S GOING IN THE DIALOG
View view = inflater.inflate(R.layout.edit_text_for_dialogs, null);
// GET THE EDIT_TEXT FROM THE 'VIEW' VARIABLE.
userInput = view.findViewById(R.id.cigarette_name_user_input);
// SET THE LAYOUT FOR THE DIALOG
builder.setView(view);
// SET ACTION BUTTONS
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// GET THE USER INPUT FROM THE EDIT_TEXT ABOVE AND PUT IT INTO A VARIABLE.
cigaretteName = userInput.getText().toString();
// PUT THE USER INPUT IN THE DATABASE.
Boolean result = dbHelper.insertCigaretteName(cigaretteName);
if (result) {
// SHOW SUCCESS MESSAGE THAT CIGARETTE NAME HAS BEEN INSERTED.
Toast.makeText(getContext(), cigaretteName + " has been added successfully!", Toast.LENGTH_SHORT).show();
listener.onDialogPositiveClick(cigaretteName);
} else {Toast.makeText(getContext(), "Something is wrong", Toast.LENGTH_SHORT).show();}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dismiss();
}
});
// RETURN THE DIALOG.
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// VERIFY THAT THE HOST ACTIVITY IMPLEMENTS THE CALLBACK INTERFACE
try {
listener = (AddCigaretteNameDialogListener) getTargetFragment();
} catch (ClassCastException e){
// THE ACTIVITY DOESN'T IMPLEMENT INTERFACE, THROW AN EXCEPTION.
throw new ClassCastException(getActivity().toString() + " must implement listener");
}
}
}
And here's the fragment which is the last child of the view pager.
package com.example.android.mybusiness;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class Purchase extends Fragment implements AddCigaretteNameDialog.AddCigaretteNameDialogListener {
Spinner spinner;
DbHelper dbHelper;
ArrayAdapter<String> arrayAdapter;
// FRAGMENT'S CONSTRUCTOR.
public Purchase() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// KIND OF REQUIREMENT FOR OPTION MENUS.
setHasOptionsMenu(true);
// INSTANTIATING THE OBJECT TO RUN A FUNCTION, WHICH GETS THE CIGARETTES NAME.
dbHelper = new DbHelper(getContext());
// Inflate the layout for this fragment
// AND PUT IT INTO A VARIABLE SO WIDGETS CAN BE ACCESSED.
View view = inflater.inflate(R.layout.fragment_purchase, container, false);
// FIND THE spinner.
spinner = view.findViewById(R.id.spinner);
// CREATING THIS ADAPTER TO POPULATE THE SPINNER WIDGET.
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dbHelper.getAllCigaretteNames());
// SETTING THE ADAPTER TO THE SPINNER, WHICH WILL PROVIDE THE CONTENT TO BE SELECTED BY ME.
spinner.setAdapter(arrayAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
AddCigaretteNameDialog addCigaretteNameDialog = new AddCigaretteNameDialog();
addCigaretteNameDialog.show(getFragmentManager(), "add_cigarette_name");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogPositiveClick(String name) {
arrayAdapter.add(name);
}
}
Here's the crash log:
12-07 13:13:59.278 25327-25327/com.example.android.mybusiness
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.mybusiness, PID: 25327
java.lang.NullPointerException: Attempt to invoke interface method 'void
com.example.android.mybusiness.AddCigaretteNameDialog$AddCigaretteNameDialogListener.onDialogPositiveClick(java.lang.String)'
on a null object reference
at com.example.android.mybusiness.AddCigaretteNameDialog$2.onClick(AddCigaretteNameDialog.java:58)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5296)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
Line 58 is
listener.onDialogPositiveClick(cigaretteName);
Thanks in advance!
If you use custom dialog class with custom view this would solve your problem. I am posting a code below which shows a custom dialog with views. first of all create a layout file for your dialog design by name dlg_add_cigarette_name inside layout folder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/dialog_background_inset"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="16dp"
android:text="Cigrate Name:"
android:id="#+id/tv_label_total"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_total_update"
android:orientation="horizontal"
android:layout_below="#+id/tv_label_total"
android:weightSum="2"
>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:layout_marginLeft="16dp"
android:layout_marginRight="10dp"
android:id="#+id/et_cgrate_name"
android:inputType="text"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:layout_marginRight="70dp"
android:text="OK"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:id="#+id/button_ok"
android:textColor="#color/colorPrimaryDark"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/layout_total_update"
android:layout_toLeftOf="#+id/button_ok"
android:layout_marginRight="30dp"
android:text="Cancel"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:background="#android:color/transparent"
android:id="#+id/button_cancel"
android:textColor="#color/colorPrimaryDark"
/>
Now inside drawable folder create a new file by name dialog_background_insetand update the file by following code
<?xml version="1.0" encoding="utf-8"?>
<inset
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#color/white"
android:insetRight="15dp"
android:insetLeft="15dp">
</inset>
and now in your AddCigaretteNameDialog file update the class by following code
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.drinkwater.reminder.watertracker.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class AddCigaretteNameDialog extends DialogFragment {
private static final float DIM_AMOUNT = 0.4f;
#BindView(R.id.tv_label_total)
TextView tvLabelTotal;
#BindView(R.id.et_cgrate_name)
EditText etCgrateName;
#BindView(R.id.layout_total_update)
LinearLayout layoutTotalUpdate;
#BindView(R.id.button_ok)
Button buttonOk;
#BindView(R.id.button_cancel)
Button buttonCancel;
#OnClick(R.id.button_cancel)
public void onClick(){
dismiss();
}
#OnClick(R.id.button_ok)
public void onClickOkay(){
unitCallBack.addCigarette(cigaretteName);
}
private Unbinder mUnbinder;
private AddCigaretteName unitCallBack;
private String cigaretteName;
public AddCigaretteNameDialog() {
}
public static AddCigaretteNameDialog newInstance(String title) {
AddCigaretteNameDialog frag = new AddCigaretteNameDialog();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (unitCallBack == null && context instanceof AddCigaretteName) {
unitCallBack = (AddCigaretteName) context;
}
}
#Override
public void onDetach() {
super.onDetach();
unitCallBack = null;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = super.onCreateDialog(savedInstanceState);
final Window window = dialog.getWindow();
if (window != null) {
window.requestFeature(Window.FEATURE_NO_TITLE);
window.setBackgroundDrawableResource(android.R.color.transparent);
WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.dimAmount = DIM_AMOUNT;
}
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test, container, false);
mUnbinder = ButterKnife.bind(this, view);
etCgrateName.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) {
cigaretteName=s.toString();
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
final int width = getScreenWidth();
int height = getScreenHeight() / 2;
changeWindowSizes(width, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void changeWindowSizes(int width, int height) {
final Window window = getDialog().getWindow();
if (window != null) {
window.setLayout(width, height);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
#Override
public int getTheme() {
return R.style.CustomDialog;
}
public interface AddCigaretteName {
void addCigarette(String name);
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
create a custom theme inside styles file
<style name="CustomDialog" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowAnimationStyle">#style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">#anim/translate_left_side</item>
<item name="android:windowExitAnimation">#anim/translate_right_side</item>
</style>
create a package anim inside resfolder and create two files translate_left_sideand translate_right_side
translate_right_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
Your AddCigrateDialog is ready to appear.Now its time to call this dialog from button click.Inside Purchase make an object of AddCigaretteDialog class globally
AddCigaretteNameDialog addCigaretteNameDialog;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_cigarette:
addCigaretteNameDialog= new AddCigaretteNameDialog();
addCigaretteNameDialog= AddCigaretteNameDialog.newInstance("AddCigrateNameDialog");
addCigaretteNameDialog.show(manager,"show");
return true;
case R.id.remove_cigarette:
RemoveCigaretteNameDailog RemoveCigaretteNameDailog = new RemoveCigaretteNameDailog();
RemoveCigaretteNameDailog.show(getFragmentManager(), "add_cigarette_name");
; return true;
default:
return super.onOptionsItemSelected(item);
}
}
And yes don't forget to implement the interface of AddCigaretteDialog inside Purchase dialog
As I am using ButterKnife dependency add the following lines inside your app's gradle file
inal BUTTER_KNIFE_VERSION = "8.8.1"
implementation "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"

How to fetch data from a custom list view with multiple radio buttons

I have gone through a lot of links here, but yet i was not able to get my stuff working. Can you please help me fetch data from my custom list.
Details are as under :- My custom list view
<?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" >
<RadioGroup
android:id="#+id/radioGroup_option"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"/>
<RadioButton
android:id="#+id/rb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="#+id/rb_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</LinearLayout>
I am populating a List through the UI the code for that is :-
package com.example.customadapter;
import java.lang.reflect.Array;
import java.util.Arrays;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CustomAdapter extends ActionBarActivity {
AddDataToArray mydata;
EditText qstno,qstn,opt1,opt2;
Button btn_save,btn_display;
int questio_no;
String question,option1,option2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_adapter);
mydata=AddDataToArray.getInstance();
qstno=(EditText)findViewById(R.id.edt_qstn_no);
qstn=(EditText)findViewById(R.id.edt_add_qstn);
opt1=(EditText)findViewById(R.id.edt_opt1);
opt2=(EditText)findViewById(R.id.edt_opt2);
btn_save=(Button)findViewById(R.id.btn_save);
btn_display=(Button)findViewById(R.id.btn_display);
btn_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
questio_no=Integer.parseInt(qstno.getText().toString());
question=qstn.getText().toString();
option1=opt1.getText().toString();
option2=opt2.getText().toString();
System.out.println("Questio added in the UI --> "+ question);
String statusReceived=mydata.AddingQuestions(questio_no, question, option1, option2);
Toast.makeText(getApplicationContext(), statusReceived, Toast.LENGTH_LONG).show();
qstn.setText("");
opt1.setText("");
opt2.setText("");
}
});
btn_display.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i=0;i<mydata.myQstnList.size();i++)
{
System.out.println("Qustion no"+mydata.myQstnList.get(i).getQstno());
System.out.println("Question -->"+mydata.myQstnList.get(i).getQstn());
//System.out.println("The First Option added was:-" + mydata.myQstnList.get(i).getOpt1());
}
Intent myIntent = new Intent(CustomAdapter.this, Mediator.class);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.custom_adapter, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Finally i made an adapter from base adapter as follows:-
package com.example.customadapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Question> mQuestion;
Context context;
public MyAdapter(Context context,List<Question> mQuestion) {
super();
this.context=context;
this.mQuestion = mQuestion;
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mQuestion.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mQuestion.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
ViewHolder holder;
if (convertView == null){
view = mInflater.inflate(R.layout.customized_view, parent,false);
holder = new ViewHolder();
holder.rg=(RadioGroup)view.findViewById(R.id.radioGroup_option);
holder.tv_qstn=(TextView)view.findViewById(R.id.tv_id);
holder.rb_opt1=(RadioButton)view.findViewById(R.id.rb_1);
holder.rb_opt2=(RadioButton)view.findViewById(R.id.rb_2);
view.setTag(mQuestion);
}else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
Question qstnRef=mQuestion.get(position);
holder.tv_qstn.setText(qstnRef.getQstn());
holder.rb_opt1.setText(qstnRef.getOpt1());
holder.rb_opt2.setText(qstnRef.getOpt2());
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
//List<Question> data =(List<Question>) group.getTag();
//Toast.makeText(context,(CharSequence) data.get(checkedId).getOpt2(),Toast.LENGTH_SHORT).show();
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
RadioButton r_btn=(RadioButton)group.getChildAt(i);
if (r_btn.getId() == checkedId){
System.out.println(r_btn.getText().toString());
}
}
}
});
return view;
}
private class ViewHolder {
public TextView tv_qstn;
public RadioButton rb_opt1,rb_opt2;
public RadioGroup rg;
}
}
But i am trying to get this data that i enter in the UI, but I am not able to get this to work, please provide me assistance !!!!
The code in the current format is giving me runtime error :-
05-09 06:01:06.669: E/AndroidRuntime(2420):
java.lang.ClassCastException: android.widget.TextView cannot be cast
to android.widget.RadioButton
05-09 06:01:06.669: E/AndroidRuntime(2420): at
com.example.customadapter.MyAdapter$1.onCheckedChanged(MyAdapter.java:83)
group.getChildCount() returns 3 as it has 3 child. but 1 child is of TextView that's why you were getting java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton
To avoid it do type checking using instanceof before typecasting.
do like this:
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
if(group.getChildAt(i) instanceof RadioButton ) { // check if child is `RadioButton`
RadioButton r_btn = (RadioButton) group.getChildAt(i);
if (r_btn.getId() == checkedId) {
System.out.println(r_btn.getText().toString());
}
}
}

Changing Gridview Size from Preferences when Implementing Fragments

I had a gridview activity where I was populating the gridview with a custom object (a picture with some custom methods and an onclick listener). I could change the gridview size from the preferences menu. Everything worked beautifully.
I have since added some complexity to the code. Instead of using the normal Activity class, I am now using the FragmentActivity class, a fragmentPageAdapter, and a fragment to which my gridview is bound. This is because eventually I want the app to allow the user "swipe" from fragment to fragment.
Since using the fragment in this way, I am noticing a repeatable bug whenever I try to resize the gridview from the preferences menu: some of the objects get resized properly, other elements do not resize. Instead, they keep the same size that they had prior to changing the preference. Here is a screenshot:
This only happens when I try resizing from the preferences menu. Other calls to my resize method, such as on a configuration change, resize all of the gridview elements correctly.
I would appreciate any suggestions!
Here is my Code:
MAIN ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.GridView;
public class MainActivity extends FragmentActivity implements OnSharedPreferenceChangeListener{
private MyFragment m_myFragment = new MyFragment();
private ViewPager m_viewPager;
private static SharedPreferences m_prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_prefs = PreferenceManager.getDefaultSharedPreferences(this);
m_prefs.registerOnSharedPreferenceChangeListener(this);
setContentView(R.layout.activity_main);
m_viewPager = (ViewPager) findViewById(R.id.pager);
m_viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), m_myFragment));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i("Khalid","MainActivity: onSharedPreferenceChanged");
if (key.equals("key_prefs_enable_lscape")){
//do nothing for now
}else if (key.equals("key_prefs_picture_size")){
SetColumnWidth(m_myFragment.getM_gridView());
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("Khalid","FragAnimalSounds: onConfigurationChanged");
SetColumnWidth(m_myFragment.getM_gridView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("Khalid","MainActivity: onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lbl_opt_menu_settings:
Intent i = new Intent("android.intent.action.PREFERENCES");
startActivity(i);
break;
case R.id.lbl_opt_menu_quit:
finish();
break;
default:
finish();
break;
}
return true;
}
public static void SetColumnWidth(GridView GV) {
Log.i("Khalid","MainActivity: SetColumnWidth");
int NumColumns, DesiredColumnWidth;
//Get the desired number of columns from the key prefs
NumColumns = Integer.parseInt(m_prefs.getString("key_prefs_picture_size","2"));
//Determine the desired column width
if (NumColumns == 1){
DesiredColumnWidth = 200;
}else if (NumColumns == 2){
DesiredColumnWidth = 100;
}else{
DesiredColumnWidth = 50;
}
//Set the desired column width
GV.setColumnWidth(DesiredColumnWidth);
}
}
class MyAdapter extends FragmentPagerAdapter{
Fragment m_frag_A = null;
public MyAdapter(FragmentManager fm, Fragment A) {
super(fm);
m_frag_A = A;
}
#Override
public Fragment getItem(int i) {
return m_frag_A; //only 1 item for now
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int i) {
return "Title Frag A"; //only 1 item for now
}
}
MY FRAGMENT (THERE IS ONLY ONE FOR NOW):
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class MyFragment extends Fragment {
private GridView m_gridView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i("Khalid","FragAnimalSounds: onCreateView");
View view = inflater.inflate(R.layout.activity_animal_sounds, container, false);
m_gridView = (GridView) view.findViewById(R.id.lbl_gridView);
m_gridView.setAdapter(new VivzAdapter(view.getContext()));
MainActivity.SetColumnWidth(m_gridView);
return view;
}
public GridView getM_gridView() {
return m_gridView;
}
}
MY GRIDVIEW ADAPTER:
package com.KhalidSorensen.animalsounds;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class VivzAdapter extends BaseAdapter {
private Context m_context;
private ArrayList<AnimalKind> m_list = new ArrayList<AnimalKind>();
VivzAdapter(Context ctx) {
m_context = ctx;
int[] animalphotos = { R.drawable.cat_1, R.drawable.cow_1,
R.drawable.dog_1, R.drawable.donkey_1, R.drawable.duck_1,
R.drawable.peacock_1, R.drawable.rooster_1, R.drawable.seal_1 };
for (int i = 0; i <= 7; i++) {
AnimalKind animalKind = new AnimalKind(m_context, animalphotos[i]);
m_list.add(animalKind);
}
}
#Override
public int getCount() {
return m_list.size();
}
#Override
public AnimalKind getItem(int position) {
return m_list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View v, ViewGroup vg) {
return m_list.get(i);
}
}
MY CUSTOM OBJECT CLASS. THESE OBJECTS ARE POPULATING THE GRIDVIEW:
package com.KhalidSorensen.animalsounds;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class AnimalKind extends ImageView implements OnClickListener{
private int m_imageId;
public AnimalKind(Context ctx, int imageId) {
super(ctx);
m_imageId = imageId;
super.setImageResource(imageId);
super.setAdjustViewBounds(true);
super.setScaleType(ImageView.ScaleType.FIT_XY);
super.setPadding(1, 1, 1, 1);
super.setBackgroundColor(Color.BLACK);
super.setOnClickListener(this);
}
//#Override
public void onClick(View v) {
//Do Something
}
#Override
public void setPressed(boolean pressed) {
//Do Something
}
public int getM_imageId() {
return m_imageId;
}
}
MY PREFERENCE ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
public class Preferences extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Log.i("Khalid", "Preferences: onCreate");
}
}
MY XML FOR MY MAIN ACTIVITY:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lbl_title"
android:background="#33B5E5"
android:layout_gravity="top"
android:paddingTop="0dp"
android:paddingBottom="0dp"> "
</android.support.v4.view.PagerTitleStrip>
</android.support.v4.view.ViewPager>
AND FINALLY, MY XML FOR THE GRIDVIEW:
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lbl_gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="0px"
android:alwaysDrawnWithCache="false"
android:animateLayoutChanges="false"
android:background="#android:color/white"
android:columnWidth="130dp"
android:drawSelectorOnTop="true"
android:horizontalSpacing="#dimen/activity_horizontal_margin"
android:listSelector="#null"
android:numColumns="auto_fit"
android:padding="#dimen/activity_horizontal_margin"
android:scrollbarStyle="insideOverlay"
android:smoothScrollbar="true"
android:stretchMode="none"
android:verticalSpacing="#dimen/activity_vertical_margin" >
</GridView>
Use CENTER_INSIDE a scale type for your image view.
super.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
another thing that I would change is the way you handle the column width. I would remove the android:numColumns="auto_fit". On the other hand you know that the number of columns is the cealing of WidthViewGrid/desiderePicSize, where the most common case for WidthViewGrid is the screen's width. On then programmatically you can set number of columns of your GridView with setNumberOfColumns
I would say:
A. After calling setColumnWidth call the gridview.invalidate()
B. After returning from the change preference - call adapter's notifyDataSetChanged in order to make sure it re-creates the views in the adapter (i.e. getView will be called)

Categories

Resources