Async and skipping frames - android

So I've run into an issue where I have an item that I click in a listview, it does a makes a few extras, and moves on the my next activity. I get an issue where my app goes to a black screen and the Console tells me
I/Choreographer: Skipped 630 frames! The application may be doing too much work on its main thread.
I've tried reading up on Async but I'm not sure how to use it in my code. So I'm posting my Main activity since this happens without interacting with the second activity.
public class MainActivity extends AppCompatActivity {
ListView ListofList;
ArrayList<String> Lists;
ArrayAdapter<String> ListAdapter;
Button button;
ArrayList<String> Subject = new ArrayList<>();
int Size = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListofList = findViewById(R.id.LofL);
Lists = new ArrayList<String>();
ListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Lists);
ListofList.setAdapter(ListAdapter);
button = findViewById(R.id.AddList);
Lists.add("Test");
ListofList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getBaseContext(), ItemList.class);
String s = (String) ListofList.getItemAtPosition(position);
i.putExtra("Title", s);
i.putExtra("size", Size);
int a = 0;
for (String t : Subject) {
i.putExtra("Item" + a, t);
a++;
}
startActivityForResult(i, 2);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), CreateItem.class);
String message = "Please enter the name of the list below.";
i.putExtra("mess", message);
startActivityForResult(i, 1);
}
});
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
Bundle extras = getIntent().getExtras();
if (data == null) {
}
if (data != null) {
if (requestCode == 1) {
String item = (data.getStringExtra("item"));
Lists.add(item);
ListAdapter.notifyDataSetChanged();
}
}
if (requestCode == 2) {
ArrayList<String> subject = new ArrayList<String>();
int i = 0;
assert data != null;
int size = (data.getIntExtra("ListSize", 0));
Size = size;
while (i <= size) {
String item = (data.getStringExtra("item" + i));
subject.add(item);
i++;
}
Subject = subject;
}
}
}
At the request of Ben P.
public class ItemList extends AppCompatActivity {
static ArrayList<String> customItems;
ArrayAdapter<String> adapter;
ListView lvItems;
Button button;
Button button2;
ArrayAdapter<String> trashAdapter;
ArrayList<String> trash;
ListView itemtrash;
static TextView Title;
String Tit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
Title = findViewById(R.id.Title);
//set up Item List
customItems = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, customItems);
lvItems = (ListView) findViewById(R.id.lvItems);
//Set up trash List
trash = new ArrayList<String>();
trashAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, trash);
itemtrash = findViewById(R.id.itemtrash);
//Initialize Buttons
button = findViewById(R.id.AddItem);
button2 = findViewById(R.id.ClearTrash);
Bundle extras = getIntent().getExtras();
if (extras != null) {
((TextView)findViewById(R.id.Title)).setText(extras.getString("Title"));
Tit = extras.getString("Title");
int i = 0;
int size = (extras.getInt("size", 0));
while (i <= size) {
String item = (extras.getString("Item" + i));
if (item == null) {
continue;
}
customItems.add(item);
i++;
}
}
//CharSequence Titlefilter = Title.getText();
//lvItems.setTextFilterEnabled(true);
//ItemList.this.adapter.getFilter().filter(Titlefilter);
//adapter.notifyDataSetChanged();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), CreateItem.class);
String message = "Please enter new item below.";
i.putExtra("mess", message);
startActivityForResult(i, 1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
trashAdapter.clear();
trashAdapter.notifyDataSetChanged();
}
});
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = adapter.getItem(position);
trashAdapter.add(s);
adapter.remove(s);
assert s != null;
adapter.notifyDataSetChanged();
trashAdapter.notifyDataSetChanged();
}
});
itemtrash.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = trashAdapter.getItem(position);
customItems.add(s);
trash.remove(s);
adapter.notifyDataSetChanged();
trashAdapter.notifyDataSetChanged();
}
});
lvItems.setAdapter(adapter);
itemtrash.setAdapter(trashAdapter);
}
#Override
public void onBackPressed() {
Intent i = new Intent();
int a = 0;
for (String s : customItems){
String t = adapter.getItem(a);
i.putExtra("item" + a, t);
a++;
}
int size = customItems.size();
i.putExtra("ListSize", size);
setResult(2, i);
finish();
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
Bundle extras = getIntent().getExtras();
if (data == null) {
}
if (data != null) {
String item = (data.getStringExtra("item"));
String title = Tit;
customItems.add(title + "\n\n" + item);
adapter.notifyDataSetChanged();
}
}
}

I figured it out. I accidentally made an infinite loop with while in the ItemList activity.

Related

Listview is setting text only for first position

Listview is setting the filename only in first position. Even though on clicking any positions of the listview it sets the filename for the first position only. Please let me know what changes i need to make so that filename will be set properly on clicked item only instead of first item always. Thanks in advance.
I have done same with in Recycle view I am sharing my project code with you
package com.deepak.myapplication;
public class DocumentActivity extends AppCompatActivity implements
View.OnClickListener {
ImageView toolbar_back;
TextView next, tvDocName;
RecyclerView listView;
ArrayList<Survey_vehiclepojo> mylist = new ArrayList();
My_document_adapter adapter;
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toolbar_back = ( ImageView ) findViewById(R.id.toolbar_back);
//toolbar_back.setOnClickListener(this);
//next = ( TextView ) findViewById(R.id.next);
//next.setOnClickListener(this);
listView = findViewById(R.id.recycleView);
mylist.add(new Survey_vehiclepojo("Pay Slip", "file1"));
mylist.add(new Survey_vehiclepojo("Insurance", "file2"));
mylist.add(new Survey_vehiclepojo("NA Certificate", "file3"));
mylist.add(new Survey_vehiclepojo("NA 1", "file3"));
mylist.add(new Survey_vehiclepojo("NA 2", "file3"));
mylist.add(new Survey_vehiclepojo("NA 3", "file3"));
listView.setLayoutManager(new LinearLayoutManager(this));
adapter = new My_document_adapter(mylist, DocumentActivity.this);
listView.setAdapter(adapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
/*case R.id.toolbar_back:
finish();
break;
case R.id.next:
Intent n=new Intent(DocumentActivity.this, Loan_checklistActivity.class);
startActivity(n);
break;
}*/
}
}
public void Document(int pos) {
position = pos;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
selectedFile(data, requestCode);
}
private void selectedFile(Intent data, int position) {
String displayName = null;
if (data != null) {
Uri uri = data.getData();
String uriString = null;
if (uri != null) {
uriString = uri.toString();
}
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString != null) {
if (uriString.startsWith("content://")) {
try (Cursor cursor = DocumentActivity.this.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
tvDocName = findViewById(R.id.tvDocName);
Survey_vehiclepojo selected = mylist.get(position);
selected.setFile1(displayName);
//My_document_adapter.display(displayName,position);
adapter.notifyDataSetChanged();
}
}
}
}
This is Adapter
class My_document_adapter extends
RecyclerView.Adapter<My_document_adapter.ViewHolder>{
ArrayList<Survey_vehiclepojo> mylist;
DocumentActivity documentActivity;
public My_document_adapter(ArrayList<Survey_vehiclepojo> mylist,
DocumentActivity documentActivity) {
this.mylist = mylist;
this.documentActivity = documentActivity;
}
#NonNull
#Override
public My_document_adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
return new My_document_adapter.ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull My_document_adapter.ViewHolder holder,
final int position) {
holder.name.setText("name"+position);
holder.ivDocument.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Log.d("**Postion", "Postion: "+position);
documentActivity.Document(position);
} });
}
#Override
public int getItemCount() {
return mylist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final TextView tvDocName,name;
ImageView ivDocument;
public ViewHolder(#NonNull View view) {
super(view);
name = view.findViewById(R.id.tvName);
tvDocName = view.findViewById(R.id.tvDocName);
ivDocument = view.findViewById(R.id.ivDocument);
}
}
}
and my file is selecting see this screenshot

Return Back the Data from the Activity who calls the fragment dialog

I have a code that calls a fragment as an activity. From that fragment I select a data then give it back to the activity caller and here is my code.
Heres how I open the dialog
fragment_customer_list dialog = new fragment_customer_list();
dialog.show(getFragmentManager(),"CustomerList");
And here is how I return the value
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
add callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
}
});
I will call a function from the activity that calls the dialog to update the edittext.
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
The problem is the dialog is fixed in one activity. My question is how can I return the data from the activity caller? Since this fragment will be used by many activity
============================updated=============================
Here is how I open my fragment and i open it as a dialog
/* Open Customer List */
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
show_customer_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment_customer_list dialog = new fragment_customer_list();
dialog.setOnClickItemListener(new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
dialog.show(getFragmentManager(),"CustomerList");
}
});
And here is the whole code fragment_customer_list
public class fragment_customer_list extends DialogFragment {
private static final String TAG = "CustomerList";
DatabaseHelper myDb;
String pattern_email;
SimpleAdapter adapter;
private DialogInterface.OnClickListener listener;
private OnClickItemListener mListener;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_customer_list, container, false);
final ListView listView = (ListView) view.findViewById(R.id.customer_list);
myDb = new DatabaseHelper(getActivity());
pattern_email = credentials.email;
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer(pattern_email);
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
// add_activity callingActivity = (add_activity ) getActivity();
// callingActivity.onUserSelectValue(customer_name, customer_address);
if (mListener != null) {
mListener.value(customer_name, customer_address);
}
getDialog().dismiss();
}
});
android.widget.Button clickButton = (android.widget.Button) view.findViewById(R.id.close);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDialog().dismiss();
}
});
/* Search customer */
EditText customer_search = (EditText) view.findViewById(R.id.search_customer);
customer_search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
final ArrayList<String> result = new ArrayList<>();
Cursor data = myDb.get_customer_search(cs.toString(),pattern_email);
if (data.getCount() == 0) {
//Toast.makeText(getActivity(), "Please sync to check your customers", Toast.LENGTH_LONG).show();
} else {
List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();
while (data.moveToNext()) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("Customer Name", data.getString(1));
datum.put("Address", data.getString(2));
data1.add(datum);
}
adapter = new SimpleAdapter(getActivity(), data1,
R.layout.customer_listview,
new String[]{"Customer Name", "Address"},
new int[]{R.id.list_name,
R.id.list_address});
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
}
});
return view;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new Dialog(getActivity(), R.style.WideDialog);
}
public void setOnClickItemListener(OnClickItemListener l) {
mListener = l;
}
interface OnClickItemListener {
void value(String name, String address);
}
}
As you can see on the code above there is Listview that has a code that same as this
add_activity callingActivity = (add_activity ) getActivity();
callingActivity.onUserSelectValue(customer_name, customer_address);
getDialog().dismiss();
The code above will get the value from listview and call the onUserSelectValue from add_activity then close the dialog
and this is onUserSelectValue and it is located at add_activity
public void onUserSelectValue(String selectedValue1 ,String selectedValue2) {
//Toast.makeText(getBaseContext(), ""+ selectedValue1 + selectedValue2, Toast.LENGTH_LONG).show();
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(selectedValue1);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(selectedValue2);
}
Here is my question.
How can I return the value of the listview to the textfield of the activity who opens the fragment(where the list view is located).
UPDATED CODE
I created a class called DialogHelper.java and this is the code
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
}
fragment_customer_list dialog = wr.get();
dialog.OnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null) return;
wr.get().dismiss();
}
}
In my customer_fragment_list.java I have a listview listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
TextView position3 = (TextView) view.findViewById(R.id.list_code);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
String customer_code = position3.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address,customer_code );
}
}
});
together with this
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address,String KUNNR);
}
public interface OnClickItemListener { void value(String name, String address, String code); }
and on my Activity this the code on how i open the dialog
/* Open Customer List */
DialogHelper.userSelectValue(add_covplan.this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
EditText customer_name = (EditText) findViewById(R.id.cusname);
customer_name.setText(name);
EditText customer_address = (EditText) findViewById(R.id.address);
customer_address.setText(address);
}
});
you can do this. Don't know if you mean this?
public class DialogHelper {
private static WeakReference<fragment_customer_list> wr;
private static WeakReference<Activity> wrActivity;
public static void userSelectValue(Activity context, fragment_customer_list.OnClickItemListener listener) {
if (wr == null || wr.get() == null || wrActivity == null || wrActivity.get() == null || wrActivity.get() != context) {
fragment_customer_list dialog = new fragment_customer_list();
wr = new WeakReference<>(dialog);
wrActivity = new WeakReference<>(context);
}
fragment_customer_list dialog = wr.get();
dialog.setOnClickItemListener(listener);
dialog.show(context.getFragmentManager(),"CustomerList");
}
// dialog dismiss
public static void dismiss() {
if (wr == null || wr.get() == null || !wr.get().isShowing()) return;
wr.get().dismiss();
}
}
use
final EditText show_customer_list = (EditText) findViewById(R.id.cusname);
DialogHelper.userSelectValue(this, new fragment_customer_list.OnClickItemListener()
{
#Override
public void value(String name, String address)
{
show_customer_list.setText(name + " " + address);
}
});
edit answer
// Suppose this is a FragmentDialog
public class FragmentList {
private OnClickListener listener;
private ListView listView;
// Suppose this has your list listener
public void onResume() {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView position1 = (TextView) view.findViewById(R.id.list_name);
TextView position2 = (TextView) view.findViewById(R.id.list_address);
String customer_name = position1.getText().toString();
String customer_address = position2.getText().toString();
if (listener != null) {
listener.click(customer_name, customer_address);
}
}
});
}
public void setOnClickListener(OnClickListener l) {
this.listener = l;
}
interface OnClickListener {
void click(String name, String address);
}
}
// Suppose this is a Activity
class YourActivity extends Activity
{
private FragmentList fragmentList;
EditText customer_address;
EditText customer_name;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
fragmentList = new FragmentList();
customer_address = (EditText) findViewById(R.id.address);
customer_name = (EditText) findViewById(R.id.cusname);
fragmentList.setOnClickListener(new FragmentList.OnClickListener()
{
#Override
public void click(String name, String address)
{
// ...
customer_name.setText(name);
customer_address.setText(address);
}
});
}
}
You can use a ViewModel class implementation to share resources between Activity and Fragment. Share the single context across multiple usages of ViewModel, each sharing a the same ViewModel. It works with the observer and observable pattern and perfect for this use case. You can check details on how to implement it here

how to add display images and sort from newest uploaded

I have fork from github this source code
https://github.com/quocnguyenvan/food-sqlite-demo
I need some help here
How to add display image in full screen? If we are in food list and click an image, the image will show at full screen
And one more, how to add sorting file? So the newest uploaded will be at the top of the list, thanks for helping me, i need this for my office
======================================================
here is my code
FoodList class
public class FoodList extends AppCompatActivity {
GridView gridView;
ArrayList<Food> list;
FoodListAdapter adapter = null;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_list_activity);
gridView = (GridView) findViewById(R.id.gridView);
list = new ArrayList<>();
adapter = new FoodListAdapter(this, R.layout.food_items, list);
gridView.setAdapter(adapter);
// get all data from sqlite
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image, id));
}
adapter.notifyDataSetChanged();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Preview", "Download"};
AlertDialog.Builder dialog = new AlertDialog.Builder(FoodList.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent i = new Intent(getApplicationContext(), ImageDisplay.class);
i.putExtra("id", position);
startActivity(i);
Toast.makeText(getApplicationContext(),"You click on " + position, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),"you download " + position, Toast.LENGTH_SHORT).show();
}
}
});
dialog.show();
//return true;
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
CharSequence[] items = {"Update", "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(FoodList.this);
dialog.setTitle("Choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
// update
Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
// show dialog update at here
showDialogUpdate(FoodList.this, arrID.get(position));
} else {
// delete
Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while (c.moveToNext()){
arrID.add(c.getInt(0));
}
showDialogDelete(arrID.get(position));
}
}
});
dialog.show();
return true;
}
});
}
ImageView imageViewFood;
private void showDialogUpdate(Activity activity, final int position){
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.update_food_activity);
dialog.setTitle("Update");
imageViewFood = (ImageView) dialog.findViewById(R.id.imageViewFood);
final EditText edtName = (EditText) dialog.findViewById(R.id.edtName);
final EditText edtPrice = (EditText) dialog.findViewById(R.id.edtPrice);
Button btnUpdate = (Button) dialog.findViewById(R.id.btnUpdate);
// set width for dialog
int width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.95);
// set height for dialog
int height = (int) (activity.getResources().getDisplayMetrics().heightPixels * 0.7);
dialog.getWindow().setLayout(width, height);
dialog.show();
imageViewFood.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// request photo library
ActivityCompat.requestPermissions(
FoodList.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
888
);
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
MainActivity.sqLiteHelper.updateData(
edtName.getText().toString().trim(),
edtPrice.getText().toString().trim(),
MainActivity.imageViewToByte(imageViewFood),
position
);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Update successfully!!!",Toast.LENGTH_SHORT).show();
}
catch (Exception error) {
Log.e("Update error", error.getMessage());
}
updateFoodList();
}
});
}
private void showDialogDelete(final int idFood){
final AlertDialog.Builder dialogDelete = new AlertDialog.Builder(FoodList.this);
dialogDelete.setTitle("Warning!!");
dialogDelete.setMessage("Are you sure you want to this delete?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
MainActivity.sqLiteHelper.deleteData(idFood);
Toast.makeText(getApplicationContext(), "Delete successfully!!!",Toast.LENGTH_SHORT).show();
} catch (Exception e){
Log.e("error", e.getMessage());
}
updateFoodList();
}
});
dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialogDelete.show();
}
private void updateFoodList(){
// get all data from sqlite
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String price = cursor.getString(2);
byte[] image = cursor.getBlob(3);
list.add(new Food(name, price, image, id));
}
adapter.notifyDataSetChanged();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 888){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 888);
}
else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 888 && resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageViewFood.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
i want to display image in fullscreen when user click on it
here is my DisplayImage class
public class ImageDisplay extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageView imageViewFood = (ImageView) findViewById(R.id.fullimage);
imageViewFood.setImageResource(position);
}
}
is it correct code ? please help me, thanks

How can i refresh my ListView for manipulation of data ? like - Insert, Update & Delete

I am trying to refresh my listview for every insert, update, delete data from/into sqlite database.But, it can not work. I already used finishActivityFromChild(getParent(),1); but sometimes my app can not open.
How can i use notifyDataSetChanged(); for this code or any way ?
public class MainActivity extends AppCompatActivity {
DbHelper myDB;
Button btn_feedback;
FloatingActionButton btn_fab;
private String selectedName;
private int selectedID;
private boolean isUserClickedBackButton = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DbHelper(this);
final ListView listView = (ListView)findViewById(R.id.listview_main);
registerForContextMenu(listView);
Intent receivedIntent = getIntent();
selectedID = receivedIntent.getIntExtra("id",-1);
selectedName = receivedIntent.getStringExtra("item");
final ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getListContents();
if (data.getCount() == 0){
Toast.makeText(getApplicationContext(),"Data Empty !",Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
String item1 = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(),"You Select - " + theList.get(position),Toast.LENGTH_SHORT).show();
Cursor data = myDB.getItemID(item1);
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Intent editScreenIntent = new Intent(getApplicationContext(), Edit_Main.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("ITEM1",item1);
startActivity(editScreenIntent);
}
else{
Toast.makeText(getApplicationContext(),"No ID Associated With That Name !",Toast.LENGTH_SHORT);
}
}
});
}
}
btn_fab = (FloatingActionButton)findViewById(R.id.fab);
btn_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), Create_Main.class));
}
});
}}
Just Clear your arrayList inside while loop as below :
while (data.moveToNext()){
//////////////////////////////////////////////////
if(theList!=null && theList.size()>0){
theList.clear();
}
/////////////////////////////////////
theList.add(data.getString(1));
.....
.....
}
Hope, it helps.

How to update and add a new list in listView?

In my Activity A, it has one icon button and one listView. The icon button is used to intent to B and C while the listView is used to intent B to do some edit.
I have 3 activities, A, B and C.The flow of activity is from A to B then C. From C, all the images and value will be returned to B then A. All the returned value and image will be loaded in listView A.
Now what I trying to achieve is load all value which is get from C and B to A. Next, the list can be updated when listView is clicked.
Activity C
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fit_screen);
selectImage();
b = (ImageView) findViewById(R.id.imageView3);
t = (EditText) findViewById(R.id.editText38);
cancel=(Button)findViewById(R.id.button15);
ok=(Button)findViewById(R.id.button16);
cancel.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
finish();
}
});
ok.setOnClickListener(new View.OnClickListener()
{ // return to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
ImageButton imageButton;
ImageView viewImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt = (EditText) findViewById(R.id.editText36);
txt1=(TextView)findViewById(R.id.textView57);
Button b = (Button) findViewById(R.id.button17);
addListenerOnButton();
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img);
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Global.img=null;
Intent i = new Intent(B.this,C.class);
startActivityForResult(i, PROJECT_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) { // receive fom C
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); // image from C can be shown here
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
}
Activity A
public class Claims1 extends Fragment {
private int mClickedPosition;
ListView listV;
TextView c;
ImageView v;
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
String Text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
setHasOptionsMenu(true);
View claims = inflater.inflate(R.layout.receipt_text, container, false);
v=(ImageView)claims.findViewById(R.id.imageView4);
listV = (ListView) claims.findViewById(R.id.listView1);
android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
myActionBar.setHomeButtonEnabled(true);
ImageView imageView = new ImageView(myActionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);
android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL); // for icon in action bar
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
myActionBar.setCustomView(imageView);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
mClickedPosition = position;
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
if(name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap",true);
intent.putExtra("name",name);
intent.putExtra("result",result);
startActivityForResult(intent,0);
}
}
});
return claims;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create1: // icon is clicked
AlertDialogRadio();
return true;
}
return (super.onOptionsItemSelected(item));
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"B", "Petrol"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Class");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(),B.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
if (m_listItems.size() == 0) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition,Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
But now, when I click the icon button to intent class B and C and return values from C and B to A, it only update the listView instead of create a new one. Why would this happen ?
Check my edit
public class Claims1 extends Fragment {
private int mClickedPosition;
ListView listV;
TextView c;
ImageView v;
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
String Text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
setHasOptionsMenu(true);
View claims = inflater.inflate(R.layout.receipt_text, container, false);
v=(ImageView)claims.findViewById(R.id.imageView4);
listV = (ListView) claims.findViewById(R.id.listView1);
android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
myActionBar.setHomeButtonEnabled(true);
ImageView imageView = new ImageView(myActionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL); // for icon in action bar
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
myActionBar.setCustomView(imageView);
setMyAdapter();
return claims;
}
public void setMyAdapter() {
adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV.setAdapter(adapter);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
if(name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap",true);
intent.putExtra("name",name);
intent.putExtra("result",result);
startActivityForResult(intent,0);
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
m_listItems.clear();
if (m_listItems.size() == 0) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
setMyAdapter();
break;
}
}
}

Categories

Resources