description:
the page have 4 tabs, when i first open the page. The getOrders(null, type) function will run once, type='all',
when i slip to the second,third or forth tab, The getOrders(null, type) function always will run twice, type='all' and type='paid' | 'settled' | 'invalid',
but then when i slip back, The getOrders(null, type) function always run once, and the type is correct.It is very strange,i want the getOrders always run once.
and when i do not slip but clcik the top tab,the getOrders(null, type) run normal. I need some help
the code is below
// activity
package com.sugar.sugarmall.app.pages.order;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.OrderViewPagerAdapter;
import com.sugar.sugarmall.app.base.BaseActivity;
import com.sugar.sugarmall.app.config.Router;
import com.sugar.sugarmall.app.pages.mine.FragmentSetting;
import java.util.ArrayList;
import java.util.Arrays;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
#Route(path = Router.ORDER_LIST)
public class OrderActivity extends BaseActivity {
#BindView(R.id.orderPage)
ViewPager2 viewPager2;
#BindView(R.id.tabLayout)
TabLayout tabLayout;
#BindView(R.id.tv_left)
TextView backBtn;
#BindView(R.id.tv_title)
TextView topTitle;
#BindView(R.id.tv_right)
TextView topRight;
#BindView(R.id.bg_head)
LinearLayout topBox;
#BindView(R.id.topSearchCenterView)
EditText topSearchCenterView;
private final ArrayList<String> tabTitles = new ArrayList<>(Arrays.asList("全部", "已付款", "已结算", "已失效"));
private String topType = "title";
private Context context;
#Override
protected void initUI() {
setContentView(R.layout.order);
ButterKnife.bind(this);
context = getApplication();
OrderViewPagerAdapter orderViewPagerAdapter = new OrderViewPagerAdapter(this, context);
viewPager2.setAdapter(orderViewPagerAdapter);
viewPager2.setUserInputEnabled(false);
new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int i) {
tab.setText(tabTitles.get(i));
}
}).attach();
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
backBtn.setVisibility(View.VISIBLE);
topTitle.setVisibility(View.VISIBLE);
topRight.setVisibility(View.VISIBLE);
topTitle.setText("订单明细");
topRight.setText("搜索");
}
#OnClick({R.id.tv_left, R.id.tv_right})
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_left:
onBackPressed();
break;
case R.id.tv_right:
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
break;
}
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
}
#Override
protected void initData() {
}
#Override
protected void initListener() {
}
}
// OrderViewPagerAdapter
package com.sugar.sugarmall.app.adapter;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.pages.order.FragmentOrder;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import java.util.ArrayList;
public class OrderViewPagerAdapter extends FragmentStateAdapter {
private String searchType = "";
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private Context context;
private FragmentOrder fragmentOrder = new FragmentOrder("all");
private TabLayout tabLayout;
public OrderViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, Context context) {
super(fragmentActivity);
this.context = context;
}
#NonNull
#Override
public Fragment createFragment(int i) {
switch (i) {
case 0:
searchType = "all";
break;
case 1:
searchType = "paid";
break;
case 2:
searchType = "settled";
break;
default:
searchType = "invalid";
break;
}
System.out.println("-----createFragment" + searchType);
return new FragmentOrder(searchType);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public boolean containsItem(long itemId) {
return super.containsItem(itemId);
}
#Override
public int getItemCount() {
return 4;
}
}
// FragmentOrder
package com.sugar.sugarmall.app.pages.order;
import static com.sugar.sugarmall.config.ResStatusCode.STATUS_OK;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
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.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.ItemOrderAdapter;
import com.sugar.sugarmall.app.base.BaseLazyFragment;
import com.sugar.sugarmall.app.base.DefaultObserver;
import com.sugar.sugarmall.https.ApiManger;
import com.sugar.sugarmall.https.CheckResponse;
import com.sugar.sugarmall.https.response.OrderResponse;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import com.sugar.sugarmall.utils.RxTools;
import com.sugar.sugarmall.utils.T;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class FragmentOrder extends BaseLazyFragment {
#BindView(R.id.fragmentOrderList)
RecyclerView fragmentOrderList;
private ViewPager2 viewPager2;
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private String type = "all";
private ItemOrderAdapter itemOrderAdapter;
private TabLayout tabLayout;
private Context context;
private String[] typeArr = new String[]{"all", "paid", "settled", "invalid"};
public FragmentOrder(String type) {
this.type = type;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order, container, false);
ButterKnife.bind(this, view);
context = getContext();
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
fragmentOrderList.setLayoutManager(linearLayoutManager);
viewPager2 = getActivity().findViewById(R.id.orderPage);
itemOrderAdapter = new ItemOrderAdapter(orderList);
fragmentOrderList.setAdapter(itemOrderAdapter);
tabLayout.removeAllTabs();
tabLayout.clearOnTabSelectedListeners();
tabLayout.addTab(tabLayout.newTab().setText("all"));
tabLayout.addTab(tabLayout.newTab().setText("paid"));
tabLayout.addTab(tabLayout.newTab().setText("settled"));
tabLayout.addTab(tabLayout.newTab().setText("invalid"));
TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println("-----pageScroll4" + tab.getPosition());
String type = typeArr[tab.getPosition()];
getOrders(null, type); // type:"all" | "paid" | "settled" | "invalid"
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
onTabSelectedListener.onTabSelected(tabLayout.getTabAt(tabLayout.getSelectedTabPosition()));
tabLayout.setOnTabSelectedListener(onTabSelectedListener);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void lazyload() {
}
public void getOrders(String searchKey, String type) {
RxTools.setSubscribe(ApiManger.sugarApi().getOrderList(type, pageNo, searchKey), new DefaultObserver<OrderResponse>() {
#Override
public void onNext(#io.reactivex.rxjava3.annotations.NonNull OrderResponse orderResponse) {
CheckResponse.checkResponse(orderResponse);
orderList.clear();
if (orderResponse.code != STATUS_OK) {
T.showShort(getContext(), orderResponse.msg);
}
orderList.addAll(orderResponse.data);
itemOrderAdapter.notifyDataSetChanged();
}
#Override
public void onError(#Nullable #io.reactivex.rxjava3.annotations.NonNull Throwable e) {
super.onError(e);
}
});
}
}
Related
I want to get total price in Activity from Price and Quantity in Adapter, it's mean like qty * price = total_price.
Here is my Adapter for handling the list of Items Activity:
package com.example.aulaherbalfinal.Adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.R;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
public class AdapterDataPembelian extends RecyclerView.Adapter<AdapterDataPembelian.HolderDataPembelian>{
private Context ctx;
private List<DataModel> listDataPembelian;
private int count;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
}
#NonNull
#Override
public HolderDataPembelian onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item_pembelian, parent, false);
HolderDataPembelian holder = new HolderDataPembelian(layout);
return holder;
}
#Override
public void onBindViewHolder(#NonNull HolderDataPembelian holder, int position) {
DataModel dm = listDataPembelian.get(position);
holder.tvId.setText(String.valueOf(dm.getId()));
holder.tvBarang.setText(dm.getBarang());
holder.tvStok.setText("Stok : "+String.valueOf(dm.getStok()));
holder.tvHarga.setText(formatRupiah(Double.parseDouble(String.valueOf(dm.getHarga()))));
holder.jmlBarang.setText(String.valueOf(dm.getQuantity()));
//holder.totalHarga.setText(String.valueOf(dm.getTotalHarga()));
Intent intent = new Intent("custom-message");
holder.btnRemove.setOnClickListener(v -> {
minusCartItem(holder,listDataPembelian.get(position));
});
holder.btnAdd.setOnClickListener(v -> {
plusCartItem(holder,listDataPembelian.get(position));
});
}
private void plusCartItem(HolderDataPembelian holder, DataModel dataModel) {
dataModel.setQuantity(dataModel.getQuantity()+1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
}
private void minusCartItem(HolderDataPembelian holder, DataModel dataModel) {
if (dataModel.getQuantity() > 0){
dataModel.setQuantity(dataModel.getQuantity()-1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
} else {
holder.jmlBarang.setText("0");
}
}
#Override
public int getItemCount() {
return listDataPembelian.size();
}
public class HolderDataPembelian extends RecyclerView.ViewHolder {
TextView tvId, tvBarang, tvStok, tvHarga;
Button btnAdd, btnRemove;
TextView jmlBarang, totalHarga;
public HolderDataPembelian(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.tv_id);
tvBarang = itemView.findViewById(R.id.tv_barang);
tvStok = itemView.findViewById(R.id.tv_stok);
tvHarga = itemView.findViewById(R.id.tv_harga);
btnAdd = itemView.findViewById(R.id.btn_add);
btnRemove = itemView.findViewById(R.id.btn_remove);
jmlBarang = itemView.findViewById(R.id.jml_barang);
totalHarga = itemView.findViewById(R.id.total_harga);
}
}
private String formatRupiah(Double number){
Locale localeID = new Locale("IND", "ID");
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(localeID);
String formatRupiah = numberFormat.format(number);
String[] split = formatRupiah.split(",");
int length = split[0].length();
return split[0].substring(0,2)+". "+split[0].substring(2,length);
}
public int getTotalPrice(){
int totalPrice = 0;
for (int i=0 i<listDataPembelian.size(); i++){
}
}
}
And here is my Activity
package com.example.aulaherbalfinal.Activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aulaherbalfinal.API.APIRequestData;
import com.example.aulaherbalfinal.API.RetroServer;
import com.example.aulaherbalfinal.Adapter.AdapterDataPembelian;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.Model.ResponseModel;
import com.example.aulaherbalfinal.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PembelianActivity extends AppCompatActivity {
private RecyclerView rvData;
private RecyclerView.Adapter adData;
private RecyclerView.LayoutManager lmData;
private List<DataModel> listDataPembelian = new ArrayList<>();
private SwipeRefreshLayout srlData;
private ProgressBar pbData;
private TextView totalHarga;
private EditText jmlBarang;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pembelian);
rvData = findViewById(R.id.rv_data);
lmData = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rvData.setLayoutManager(lmData);
srlData = findViewById(R.id.srl_data);
pbData = findViewById(R.id.pb_data);
totalHarga = findViewById(R.id.total_harga);
jmlBarang = findViewById(R.id.jml_barang);
totalHarga = findViewById(R.id.total_harga);
//retrieveData();
CardView cvTotal = findViewById(R.id.cv_total);
rvData.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE){
cvTotal.setVisibility(View.INVISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP){
cvTotal.setVisibility(View.VISIBLE);
}
return false;
}
});
BottomNavigationView bottom_navigation = findViewById(R.id.bottom_navigation);
bottom_navigation.setItemIconTintList(null);
bottom_navigation.setSelectedItemId(R.id.navigation_pembelian);
ImageView profile =findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PembelianActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
});
bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch ( (item.getItemId())){
case R.id.navigation_stok:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.navigation_pembelian:
return true;
case R.id.navigation_penjualan:
startActivity(new Intent(getApplicationContext(), PenjualanActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
srlData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
srlData.setRefreshing(true);
retrieveData();
srlData.setRefreshing(false);
}
});
}
#Override
protected void onResume() {
super.onResume();
retrieveData();
}
public void retrieveData(){
pbData.setVisibility(View.VISIBLE);
APIRequestData ardData = RetroServer.konekRetrofit().create(APIRequestData.class);
Call<ResponseModel> tampildata = ardData.ardRetrieveData();
tampildata.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
//Toast.makeText(MainActivity.this, "Kode : "+kode+" | Pesan : "+pesan, Toast.LENGTH_SHORT).show();
listDataPembelian = response.body().getData();
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian);
rvData.setAdapter(adData);
adData.notifyDataSetChanged();
pbData.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(PembelianActivity.this, "Gagal Menghubungi Server", Toast.LENGTH_SHORT).show();
pbData.setVisibility(View.INVISIBLE);
}
});
}
}
Here is my app
I would do something like this:
Create an Interface for your activity to implement:
public interface CallbackIF {
double tally(double amount, int quantity)
}
public class PembelianActivity extends AppCompatActivity implements CallbackIF {
#Override
public double tally(double amount, int quantity) {
return amount * quantity;
}
}
Then when you initialize your recyclerview adapter pass in the interface like so:
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian, PembelianActivity.this);
And change your constructor for the data adapter to be
private CallbackIF callback;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian, CallbackIF callback) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
this.callback = callback;
}
Then in your onClicklistener for your list / wherever you want to trigger a tally just call
double value = callback.tally(amount, quantity);
If you have any questions please ask
I am trying to get the position of the item in a recycler view in order to pass it down to other activities, but after actually managing to get the item id, I found out that I'm getting a -1, therefore not getting a correct id there. What could be causing this?
The activity:
package com.gmproxy.pastilarma;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;
import androidx.recyclerview.*;
import com.gmproxy.Adapters.PathologyListAdapter;
import com.gmproxy.Adapters.PathologyViewHolder;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Util.PathologyViewModel;
public class PathologiesSearchScreen extends AppCompatActivity {
private PathologyViewModel viewModel;
SearchView searchView;
RecyclerView recyclerView;
private PathologyDAO pathDao;
private Pathology pathology;
private PathologyViewHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pathology_search_list);
searchView = findViewById(R.id.SearchView);
recyclerView = findViewById(R.id.recyclerview);
final PathologyListAdapter adapter = new PathologyListAdapter(new PathologyListAdapter.UserDiff());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
viewModel = new ViewModelProvider(this).get(PathologyViewModel.class);
viewModel.pathologies.observe(this, adapter::submitList);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
viewModel.setFilter(searchView.getQuery().toString());
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
long start;
start = System.currentTimeMillis();
if ((newText.length() > 3) && (System.currentTimeMillis() - start > 500)) {
viewModel.setFilter(searchView.getQuery().toString());
}
return false;
}
});
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
pathology = getSelectedPathology(findViewById(R.id.recyclerview));
Log.println(Log.INFO, "PathologyTest", pathology.toString());
final CharSequence[] options = {"Si", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(PathologiesSearchScreen.this);
builder.setTitle("¿Añadir la patología " + pathology.getPathologyName() + "?");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Si")) {
Toast.makeText(PathologiesSearchScreen.this, "Has añadido la patología " + pathology.getPathologyName() + ".", Toast.LENGTH_SHORT).show();
Intent mainAct = new Intent(PathologiesSearchScreen.this, UserAddScreen.class);
mainAct.putExtra("path", pathology);
} else if (options[item].equals("No")) {
dialog.dismiss();
}
}
});
builder.show();
return true;
}
#Override
public void onTouchEvent(#NonNull #org.jetbrains.annotations.NotNull RecyclerView rv, #NonNull #org.jetbrains.annotations.NotNull MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public Pathology getSelectedPathology(View v){
holder = new PathologyViewHolder(v);
long idlongo = recyclerView.getAdapter().getItemId(holder.getAdapterPosition());
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}
}
The view holder:
package com.gmproxy.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.gmproxy.DAO.PathologyDAO;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.R;
import java.nio.file.Path;
public class PathologyViewHolder extends RecyclerView.ViewHolder {
public final TextView objItemView;
public PathologyViewHolder(View itemView) {
super(itemView);
objItemView = itemView.findViewById(R.id.textView);
}
public void bind(String text) {
objItemView.setText(text);
}
static PathologyViewHolder create(ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pathologies_item, parent, false);
return new PathologyViewHolder(view);
}
}
The list adapter:
package com.gmproxy.Adapters;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.pastilarma.PathologiesSearchScreen;
import com.gmproxy.pastilarma.UserAddScreen;
public class PathologyListAdapter extends ListAdapter<Pathology, PathologyViewHolder> {
public PathologyListAdapter(#NonNull DiffUtil.ItemCallback<Pathology> diffCallback) {
super(diffCallback);
}
#Override
public PathologyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return PathologyViewHolder.create(parent);
}
#Override
public void onBindViewHolder(PathologyViewHolder holder, int position) {
Pathology current = getItem(position);
holder.bind(current.getPathologyName());
}
public static class UserDiff extends DiffUtil.ItemCallback<Pathology> {
#Override
public boolean areItemsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem == newItem;
}
#Override
public boolean areContentsTheSame(#NonNull Pathology oldItem, #NonNull Pathology newItem) {
return oldItem.getPathologyName().equals(newItem.getPathologyName());
}
}
}
The entity DAO:
package com.gmproxy.DAO;
import androidx.lifecycle.LiveData;
import androidx.room.*;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
#Dao
public interface PathologyDAO {
#Query("SELECT * FROM condiciones")
LiveData<List<Pathology>> getAllObjects();
//This will come in handy for getting all those pathologies, will need to get them on a for loop since I'm not completely sure
//that the query will handle int[]
#Query("SELECT id_condiciones FROM condiciones WHERE id_condiciones LIKE :id_condiciones")
int getPathologiesForUser(int id_condiciones);
#Query("SELECT nombreCondicion FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
String getPathologiesForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE :pathologyName")
Pathology getPathologiesCompleteForName(String pathologyName);
#Query("SELECT * FROM condiciones WHERE id_condiciones = :id")
Pathology findObjectbyId(int id);
#Query("SELECT * FROM condiciones WHERE nombreCondicion LIKE '%' || :filter || '%'")
LiveData<List<Pathology>> filterText(String filter);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllObjects(List<Pathology> listObjects);
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertObject(Pathology object);
#Update
void updateObject(Pathology object);
#Delete
void delete(Pathology obj);
}
The entity repository:
package com.gmproxy.DAO;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class PathologyRepository {
private PathologyDAO concerningDao;
private LiveData<List<Pathology>> pathologyList;
public PathologyRepository(Application application) {
DatabaseHelper db = DatabaseHelper.getDatabase(application);
concerningDao = db.pathologyDao();
pathologyList = concerningDao.getAllObjects();
}
public LiveData<List<Pathology>> getAllObjects() {
return concerningDao.getAllObjects();
}
void insertAllObjects(List<Pathology> objectsList) {
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertAllObjects(objectsList);
});
}
public void insertObject(Pathology obj){
DatabaseHelper.databaseWriteExecutor.execute(() ->{
concerningDao.insertObject(obj);
});
}
public void deleteObject(Pathology obj) {
concerningDao.delete(obj);
}
public LiveData<List<Pathology>> filter(String input){
try{
return new FilterNoteAsyncTask(concerningDao).execute(input).get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
private static class FilterNoteAsyncTask extends AsyncTask<String, Void, LiveData<List<Pathology>>> {
private PathologyDAO pathologyDAO;
private FilterNoteAsyncTask(PathologyDAO pathologyDAO) {
this.pathologyDAO = pathologyDAO;
}
#Override
protected LiveData<List<Pathology>> doInBackground(String... strings) {
return pathologyDAO.filterText(strings[0]);
}
}
}
Move your PathologyListAdapter to global, and get adapter position using adapter object instead of getting adapter from recyclerview.
public Pathology getSelectedPathology(){
long idlongo = adapter.getAdapterPosition();
Log.println(Log.INFO, "PathologyTest", String.valueOf(idlongo));
int id = (int) idlongo;
Pathology path = pathDao.findObjectbyId(id);
return path;
}
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter, but I get an error a null object reference in mOnItemClickListener.onClick(i).
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter.
I want to passing data to DetailMoviesFragment Class.
this is my CardviewMovieAdapter Class
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardviewMovieAdapter extends RecyclerView.Adapter<CardviewMovieAdapter.CardViewViewHolder> {
private ArrayList<Movie> listMovie;
Context context;
OnItemClickListener mOnItemClickListener;
public void setListMovie(ArrayList<Movie> listMovie) {
this.listMovie = listMovie;
}
public ArrayList<Movie> getListMovie() {
return listMovie;
}
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public CardviewMovieAdapter(ArrayList<Movie> listMovie, Context context) {
this.listMovie = listMovie;
this.context = context;
}
#NonNull
#Override
public CardviewMovieAdapter.CardViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_movie, viewGroup,false);
return new CardViewViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final CardviewMovieAdapter.CardViewViewHolder cardViewViewHolder, final int i) {
final Movie movie = listMovie.get(i);
Glide.with(cardViewViewHolder.itemView.getContext())
.load(movie.getImageMovie())
.apply(new RequestOptions().override(350, 550))
.into(cardViewViewHolder.imgPhoto);
cardViewViewHolder.tvTitle.setText(movie.getTitleMovie());
cardViewViewHolder.tvDesc.setText(movie.getDescription());
cardViewViewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Detail "+
listMovie.get(cardViewViewHolder.getAdapterPosition()).getTitleMovie(), Toast.LENGTH_SHORT).show();
}
});
cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
mOnItemClickListener.onClick(i);
}
});
// cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return listMovie.size();
}
public class CardViewViewHolder extends RecyclerView.ViewHolder {
ImageView imgPhoto;
TextView tvTitle, tvDesc;
Button btnDetail;
public CardViewViewHolder(#NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.img_item_photo);
tvTitle = itemView.findViewById(R.id.tv_title);
tvDesc = itemView.findViewById(R.id.tv_desc);
btnDetail = itemView.findViewById(R.id.btn_detail);
}
}
}
This is my MoviesFragment Class
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MoviesFragment extends Fragment implements View.OnClickListener{
private RecyclerView rvMovie;
private String[] dataMovieTitle;
private String[] dataDescription;
private TypedArray dataPhoto;
private ArrayList<Movie> movies;
Button btnDetail;
private CardviewMovieAdapter adapter;
View view;
final static String KEY = "KEY";
public MoviesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_movies, container, false);
//adapter = new CardviewMovieAdapter(movies,getContext());
rvMovie = view.findViewById(R.id.rv_movies);
prepare();
addItem();
showRecyclerCardView();
adapter = new CardviewMovieAdapter(movies, getContext());
adapter.setOnItemClickListener(new CardviewMovieAdapter.OnItemClickListener() {
#Override
public void onClick(int position) {
final Movie movie = movies.get(position);
DetailMoviesFragment detailMoviesFragment = new DetailMoviesFragment();
// Bundle mBundle = new Bundle();
// mBundle.putString(detailMoviesFragment.EXTRA_TITLE, movie.getTitleMovie());
// mBundle.putString(detailMoviesFragment.EXTRA_DESCRIPTION, movie.getDescription());
// mBundle.putInt(detailMoviesFragment.EXTRA_PHOTO, movie.getImageMovie());
// detailMoviesFragment.setArguments(mBundle);
MoviesFragment.newInstance(movie.getTitleMovie(), movie.getDescription(), movie.getImageMovie());
FragmentManager mFragmentManager = getFragmentManager();
if (mFragmentManager!= null) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containterFragment, detailMoviesFragment, DetailMoviesFragment.class.getSimpleName());
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
}
}
});
return view;
}
public static MoviesFragment newInstance(String title, String desc, int image) {
MoviesFragment moviesFragment = new MoviesFragment();
Bundle args = new Bundle();
args.putInt("image", image);
args.putString("title", title);
args.putString("desc", desc);
moviesFragment.setArguments(args);
return moviesFragment;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void showRecyclerCardView(){
rvMovie.setLayoutManager(new LinearLayoutManager(getActivity()));
CardviewMovieAdapter adapter = new CardviewMovieAdapter(movies,getActivity());
rvMovie.setAdapter(adapter);
}
private void prepare() {
dataMovieTitle = getResources().getStringArray(R.array.data_movie_name);
dataDescription = getResources().getStringArray(R.array.data_desc_movie);
dataPhoto = getResources().obtainTypedArray(R.array.data_photo_movie);
}
private void addItem(){
movies = new ArrayList<>();
for (int i=0; i < dataMovieTitle.length; i++){
Movie movie = new Movie();
movie.setImageMovie(dataPhoto.getResourceId(i, -1));
movie.setTitleMovie(dataMovieTitle[i]);
movie.setDescription(dataDescription[i]);
movies.add(movie);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.card_view){
}
}
}
and this is DetailMoviesActivity Class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailMovieActivity extends AppCompatActivity {
Movie movie;
TextView tvTitle, tvDesc;
ImageView ivMovie;
Button btnDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_movie);
initView();
}
private void initView() {
movie = (Movie) getIntent().getSerializableExtra("informasi");
String judul = movie.getTitleMovie();
String desc = movie.getDescription();
int img = movie.getImageMovie();
tvTitle.setText(judul);
tvDesc.setText(desc);
Picasso.get().load(img).into(ivMovie);
}
}
You can try with delete the setOnItemClickListener and call intent from cardViewViewHolder.itemView.setOnClickListener
When i tap search donor then it shows blank screen in listview i don't know why This is the response that i get back from server
This is my custom adapter code:
package com.example.kamran.ebloodbank;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Kamran on 4/12/2017.
*/
public class DonorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> donorItems;
public DonorAdapter(Activity activity,List<DataSet> donorItems) {
this.activity = activity;
this.donorItems = donorItems;
}
#Override
public int getCount() {
return donorItems.size();
}
#Override
public Object getItem(int location) {
return donorItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.donor_search_list_theme, null);
TextView nameTextView = (TextView) convertView.findViewById(R.id.donor_name);
TextView areaTextView = (TextView) convertView.findViewById(R.id.donor_area);
DataSet d = donorItems.get(position);
nameTextView.setText(d.getName());
areaTextView.setText(d.getArea());
return convertView;
}
}
This is my model code:
package com.example.kamran.ebloodbank;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Created by Kamran on 4/12/2017.
*/
public class DataSet {
private String name;
private int area;
public void setArea(int area) {
this.area = area;
}
public void setName(String name) {
this.name = name;
}
public int getArea() {
return area;
}
public String getName() {
return name;
}
}
This is my first activity code:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.kamran.ebloodbank.data.BloodContract.BloodEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindDonor extends AppCompatActivity {
Spinner bloodgroup;
Spinner area;
String findDonorUrl = "https://wwwkamranalitk.000webhostapp.com/findDonor.php";
int mBlood = BloodEntry.BLOOD_GROUP_A_POS;
int mArea = BloodEntry.DONOR_AREA_MALIR;
Button searchButton;
RequestQueue requestQueue;
StringRequest request;
JSONObject jsonObject;
JSONArray result;
private List<DataSet> donorList = new ArrayList<DataSet>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_donor);
bloodgroup = (Spinner) findViewById(R.id.bloodspinnerfinddonor);
area = (Spinner) findViewById(R.id.areaSpinner);
searchButton = (Button) findViewById(R.id.searchDonor);
setupSpinnerBlood();
setupSpinnerArea();
requestQueue = Volley.newRequestQueue(getApplicationContext());
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, findDonorUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = new JSONObject(response);
result = jsonObject.getJSONArray("result");
JSONObject donorData = result.getJSONObject(0);
DataSet donorSet = new DataSet();
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("bloodgroup", String.valueOf(mBlood));
parameters.put("area", String.valueOf(mArea));
return parameters;
}
};
requestQueue.add(request);
}
});
}
private void setupSpinnerBlood() {
ArrayAdapter bloodGroupSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.blood_group, android.R.layout.simple_spinner_item);
bloodGroupSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bloodgroup.setAdapter(bloodGroupSpinnerAdapter);
bloodgroup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blood_apos))) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
} else if (selection.equals((getString(R.string.blood_bpos)))) {
mBlood = BloodEntry.BLOOD_GROUP_B_POS;
} else if (selection.equals(getString(R.string.blood_opos))) {
mBlood = BloodEntry.BLOOD_GROUP_O_POS;
} else if (selection.equals((getString(R.string.blood_oneg)))) {
mBlood = BloodEntry.BLOOD_GROUP_O_NEG;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
}
});
}
private void setupSpinnerArea() {
ArrayAdapter areaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.area, android.R.layout.simple_spinner_item);
areaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
area.setAdapter(areaSpinnerAdapter);
area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.donor_area_malir))) {
mArea = BloodEntry.DONOR_AREA_MALIR;
} else if (selection.equals(getString(R.string.donor_area_defence))) {
mArea = BloodEntry.DONOR_AREA_DEFENCE;
} else if (selection.equals(getString(R.string.donor_area_korangi))) {
mArea = BloodEntry.DONOR_AREA_KORANGI;
} else if (selection.equals(getString(R.string.donor_area_johar))) {
mArea = BloodEntry.DONOR_AREA_JOHAR;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mArea = BloodEntry.DONOR_AREA_MALIR;
}
});
}
}
and This is the code in which data will be shown:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DonorSearchList extends AppCompatActivity {
private String mArea;
private List<DataSet> donorList = new ArrayList<DataSet>();
private ListView listView;
private DonorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donor_search_list);
listView = (ListView) findViewById(R.id.donorListView);
adapter = new DonorAdapter(this, donorList);
listView.setAdapter(adapter);
}
}
You need to transfer data from the search to list activity.
Try something like this:
public class bridge {
public static List<DataSet> donorList = new ArrayList<DataSet>();
}
Then, in the class FindDonor:
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
//here put this line
bridge.donarList = donarList;
//rest code
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
Then, in the DonorSearchList class:
adapter = new DonorAdapter(this, bridge.donorList);
I want to create a loader for my list view but got
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, context)
know this error is very common but tried to import different library still error. Really appreciate if someone can point out why. Thanks in advance!
my code:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.app.Fragment;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.app.Activity;
public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
//showNoteList();
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
//String ds = note_database.getData();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.noteListAdapter);
getLoaderManager().initLoader(0, null, context);
note_database.close();
//note_list.setText(ds);
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context, note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context,data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
// THE LOADER
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_note_items;
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
this.loader_db = db;
}
#Override
protected void onStartLoading() {
if (loader_note_items != null) {
deliverResult(loader_note_items); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open(); // Query the database
ArrayList<NoteItems> note_items = loader_db.getNote_items();
loader_db.close();
return loader_note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
loader_note_items = data; // Caching
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_note_items = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_note_items = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}