I'm creating a dialog alert that will show a radio group, depending on the chosen option it will populate a list with the contents of one array or another.These arrays are populated on the main activity, so they are not null. My problem is try to populate the list in the dialog, the arrays turn out to be empty, and I don't know how to pass the populated value there.
These are the lines that cause problems:
adapter = new populateListView(MainActivity.this, all_times_array, all_runtimes_array);
And this is the code for my dialog:
public void dialog_filter() {
final String[] grpname = {
"Today",
"This Month",
"This Year",
"All time"
};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
//alt_bld.setIcon(R.drawable.icon);
alt_bld.setTitle("See reports from ...");
alt_bld.setSingleChoiceItems(grpname, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
time_filter = item;
System.out.println(time_filter);
Toast.makeText(getApplicationContext(),
grpname[item] + " selected", Toast.LENGTH_SHORT).show();
switch (time_filter) {
case 3:
adapter = new populateListView(MainActivity.this, all_times_array, all_runtimes_array);
bannertext = "Total seizures:" + " " + total_seizures;
banner.setText(bannertext);
list.setAdapter(adapter);
break;
case 0:
adapter = new populateListView(MainActivity.this, today_times_array, today_runtimes_array);
bannertext = "Today seizures:" + " " + today_seizures;
banner.setText(bannertext);
list.setAdapter(adapter);
break;
case 1:
adapter = new populateListView(MainActivity.this, month_times_array, month_runtimes_array);
bannertext = "Month seizures:" + " " + month_seizures;
banner.setText(bannertext);
list.setAdapter(adapter);
break;
case 2:
adapter = new populateListView(MainActivity.this, year_times_array, year_runtimes_array);
bannertext = "Year seizures:" + " " + year_seizures;
banner.setText(bannertext);
list.setAdapter(adapter);
break;
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
These are the methods my pupulateListView class:
class populateListView extends ArrayAdapter <String>
{
Context context;
String [] times;
String [] runtimes;
populateListView(Context c,String [] tms, String [] rts)
{
super(c, seizure_list2,R.id.firstLine,tms);
this.context=c;
this.runtimes=rts;
this.times = tms;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(seizure_list2,parent,false);
TextView runtime_text = (TextView) row.findViewById(R.id.secondLine);
TextView time_text = (TextView) row.findViewById(R.id.firstLine);
time_text.setText(times[position]);
runtime_text.setText(runtimes[position]);
return row;
}
}
Just a suggestion!
Create a layout file with your radio group,and set this layout to your alert dialogue
dialog.setContentView(R.layout.yourlayout);
after that refer to your radioi group in layout
RadioGroup youradiogroup = (RadioGroup) dialog.findViewById(R.id.youradiogroupID);
and get the value of selected item in
youradiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
if (checkedId == R.id.first_radiobutton) {
//do something}
else if (checkedId == R.id.second_radiobutton) {
//do something else }
}
});
Hope it helps !
Related
I wonder if anybody could help me with my code. I have a ListView which lists Devices from database. Each device has a status which is represented with colored icon. Each device has also bunch of buttons to start/stop/etc the device and that works (after logout and login icon changed color). What I want to do is somehow refresh this list so icons color is up-to-date. Thanks in advance!
ListAdapter.java:
public class ListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] deviceName;
private final String[] ip;
private final Integer[] imgid;
public ListAdapter(Activity context, String[] deviceName, String[] ip, Integer[] imgid) {
super(context, R.layout.list_item, deviceName);
this.context = context;
this.deviceName = deviceName;
this.ip = ip;
this.imgid = imgid;
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item, null, true);
TextView titleText = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
Button startBtn = (Button) rowView.findViewById(R.id.startBtn);
Button stopBtn = (Button) rowView.findViewById(R.id.stopBtn);
final String URL3 = "http://damiangozdzi.nazwa.pl/pact-dev/sendstatus.php";
titleText.setText(deviceName[position]);
imageView.setImageResource(imgid[position]);
subtitleText.setText(ip[position]);
startBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Device has been started", Toast.LENGTH_SHORT).show();
SenderStatus s = new SenderStatus(getContext(), URL3, Integer.toString(position +1), "3");
s.execute();
//I tried to refresh my list from here but nothing worked
}
});
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Device has been stopped", Toast.LENGTH_SHORT).show();
SenderStatus s = new SenderStatus(getContext(), URL3, Integer.toString(position +1), "1");
s.execute();
}
});
return rowView;
}
}
User.java:
public class User extends Fragment {
private ListView list;
private Button startBtn;
private Button stopBtn;
private String[] deviceName ={};
private String[] ip ={};
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user, container, false);
Devices d = Devices.getInstance();
String s = d.getString();
String[][] all = getDevices(s);
deviceName = all[0];
ip = all[1];
String[] pre_imgid = all[2];
int x = pre_imgid.length;
Integer[] imgid = new Integer[x];
for (int i = 0; i < x; i++){
switch(pre_imgid[i]){
case "0":
imgid[i] = R.drawable.large_circle_szary; break;
case "1":
imgid[i] = R.drawable.large_circle_czerwony; break;
case "2":
imgid[i] = R.drawable.large_circle_pomarancz; break;
case "3":
imgid[i] = R.drawable.large_circle_zielony; break;
default:
imgid[i] = R.drawable.large_circle_niebieski; break;
}
}
ListAdapter adapter=new ListAdapter(getActivity(), deviceName, ip, imgid);
list = (ListView) view.findViewById(R.id.plcsList);
list.setAdapter(adapter);
return view;
}
public String[][] getDevices(String s){
char c = '{';
int count = 0;
for(int i=0; i < s.length(); i++)
{ if(s.charAt(i) == c)
count++;
}
String[][] all = new String[3][count];
if (s == null) {
Toast.makeText(getContext(), "s is null", Toast.LENGTH_SHORT).show();
} else {
try{
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
all[0][i] = obj.getString("address");
all[1][i] = obj.getString("name");
all[2][i] = Integer.toString(obj.getInt("status"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return all;
}
}
Welcome to Stackoverflow.
Create a method inside the adapter that receives your deviceName, ip, imgid as parameteres. Then you just need to call it when you click on the button.
On the adapter:
public void refreshData(String[] deviceName, String[] ip, Integer[] imgid){
this.deviceName = deviceName;
this.ip = ip;
this.imgid = imgid;
notifyDataSetChanged();
}
Then on the click button:
adapter.refreshData(yourDeviceNameVariable, yourIpVariable, yourImdidVariable);
I suggest you to put this code inside a method, where the deviceName, the ip and the imdid variable are global variables, and you call that method on button click, before refreshing the adapter.
Devices d = Devices.getInstance();
String s = d.getString();
String[][] all = getDevices(s);
deviceName = all[0];
ip = all[1];
String[] pre_imgid = all[2];
int x = pre_imgid.length;
Integer[] imgid = new Integer[x];
for (int i = 0; i < x; i++){
switch(pre_imgid[i]){
case "0":
imgid[i] = R.drawable.large_circle_szary; break;
case "1":
imgid[i] = R.drawable.large_circle_czerwony; break;
case "2":
imgid[i] = R.drawable.large_circle_pomarancz; break;
case "3":
imgid[i] = R.drawable.large_circle_zielony; break;
default:
imgid[i] = R.drawable.large_circle_niebieski; break;
}
}
This is something you need to workaround. I will be giving you the points to change but you need to update your code.
In onclicklistener of both start/stop you need to get the selected object manually and update there data, where by the view will be updated on the fly.
Here, you have to do something like, settag() to your parent layout with object from the list, i see there is multiple list, use the object of the list where you are updating the view.
Eg: // your parentlayout.setTag(devicename[position])
In onclicklistner, you need to get this object
Eg: // get your object from settag:- DeviceName dobj = (DeviceName) view.getTag()
Further:
dobj.updateview, // something your logic of updating view.
that's it, you are good to go but the problem is your class design.
Suggestion:
Create one more model class where your deviname and ip also the data/field you so want to edit/update in onclicklistener
Try to use list/map, preferably list to pass to adapter.
I have a RecyclerView and a button for 'Binding' each item (Moving to another child at the DB).
Most of the time it works well, but sometimes i'm receiving indexOutOfBounds Exception.
This is a screen shot:
When I press at 'BIND' at the top recycler view item, i'm receiving this bug.
I made it print this line:
Log.d("dDebug","Almost bug! Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition);
And it prints this:
D/dDebug: Almost bug! Size: 1 , index: 1
Here you can see the bug - size 1, index 1, so it will have indexOutOfBounds.
This is the code:
public class AvailableFragmentPilot extends Fragment {
private String TAG = "dDEBUG";
private RecyclerView mavailableList;
private DatabaseReference mAvailableMissionsDb, mPendingMissionsDb;
private FirebaseAuth mAuth;
private ProgressDialog mSubmitMsnProgress;
private String mCurrent_pilot_id;
private View mMainView;
// Query queries;
public AvailableFragmentPilot() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_of_recycler_view_user, container, false);
mavailableList = (RecyclerView)mMainView.findViewById(R.id.mission_recycler_user);
mAuth = FirebaseAuth.getInstance();
mSubmitMsnProgress = new ProgressDialog(getContext());
mCurrent_pilot_id = mAuth.getCurrentUser().getUid();
mAvailableMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child("Available");
mAvailableMissionsDb.keepSynced(true);
mPendingMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child("Pending");
mPendingMissionsDb.keepSynced(true);
// queries = mAvailableMissionsDb.orderByChild("user_uid").equalTo(mCurrent_pilot_id);
mavailableList.setHasFixedSize(true);
mavailableList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
mavailableList.setAdapter(new MissionAdapter(mAvailableMissionsDb));
}
private class MissionAdapter extends FirebaseRecyclerAdapter<Mission, AvailableFragmentPilot.MissionsViewHolder> {
public MissionAdapter(Query queries){
super(Mission.class, R.layout.missions_single_layout, AvailableFragmentPilot.MissionsViewHolder.class, queries);
}
#Override
protected void populateViewHolder(AvailableFragmentPilot.MissionsViewHolder missionViewHolder, final Mission missionModel, final int missionPosition) {
Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
missionViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Mission clickedMission = null;
if (((MissionAdapter) MissionAdapter.this).mSnapshots.size()>missionPosition){
clickedMission = AvailableFragmentPilot.MissionAdapter.this.getItem(missionPosition);
Log.d("dDebug","Ein bug. Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition + " , mission: " + clickedMission.getType() + ": " + clickedMission.getDescription());
}
else{
Log.d("dDebug","Almost bug! Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition);
}
if (clickedMission != null){ // for the sake of being extra-safe
// String url_str = getRef(missionPosition).toString();
// String uuid_for_mission = url_str.split("/")[5];
Log.d(TAG,"The button was pressed for mission: " + clickedMission.getType() + " , uid: " + missionModel.getMission_uid());
// removeMission(uuid_for_mission);
bindMission(clickedMission);
}
}
});
}
}
public void bindMission(final Mission mission){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setCancelable(false);
builder.setTitle("Mission bind");
builder.setMessage("Are you sure you want to bind this mission?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mAvailableMissionsDb.child(mission.getMission_uid()).setValue(null);
final HashMap<String, String> missionMap = new HashMap<>();
missionMap.put("username", mission.getUsername());
missionMap.put("user_uid", mission.getUser_uid());
missionMap.put("mission_uid", mission.getMission_uid());
missionMap.put("type", mission.getType());
missionMap.put("status", "Pending");
missionMap.put("description", mission.getDescription());
missionMap.put("x", String.valueOf(mission.getX()));
missionMap.put("y", String.valueOf(mission.getY()));
missionMap.put("pilot_uid", mCurrent_pilot_id);
mPendingMissionsDb.child(mission.getMission_uid()).setValue(missionMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
// Log.d("dDebug","Before");
mSubmitMsnProgress.dismiss();
Toast.makeText(getContext(), ("Bind to mission " + mission.getType()),
Toast.LENGTH_LONG).show();
Log.d("dDebug","Painting in Red 1");
}
else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("dDebug","ok, not binding");
}
});
// Create the AlertDialog object and return it
builder.create().show();
}
public static class MissionsViewHolder extends RecyclerView.ViewHolder {
View mView;
Button button ;
public MissionsViewHolder(View itemView) {
super(itemView);
mView = itemView;
button = (Button)mView.findViewById(R.id.mission_single_button);
button.setText("BIND");
}
public void setMissionName(String name){
TextView mMissionNameView = mView.findViewById(R.id.mission_single_name);
mMissionNameView.setText(name);
}
public void setMissionStatus(String status){
TextView mMissionStatusView = mView.findViewById(R.id.mission_single_status);
mMissionStatusView.setText(status);
if (status.equals("Available")){
mMissionStatusView.setTextColor(Color.parseColor("#008000"));;
} else {
mMissionStatusView.setTextColor(Color.parseColor("#FF0000"));;
}
}
public void setMissionDescription(String description){
TextView mMissionDescriptionView = mView.findViewById(R.id.mission_single_description);
mMissionDescriptionView.setText(description);
}
}
}
In addition - sometimes I will have 5 items, I'll press at the most upper one, (Should be index 0!) - and the SECOND item is being moved (at index 1).
So it means that probarely something is wrong with the way i'm getting the item that was clciked.
Rookie recycler view mistake: the view holder can move around and be reused (thus changing its position) while the onClick callback will only store a reference to the original position. To fix that, use viewHolder.getAdapterPosition(). 👍
I wanted to add swipe to refresh for my listview in a Fragment but it doesn't seem to work as it doesn't update my list view at all. Here is how my activity works:
Users open up PictureFragment where a list of images (listview)
are shown.
Users press "add button" which will open up UploadImageActivity to add in image.
Once done, UploadImageActivity will close and users now get back to PictureFragment (not updated their latest image upload yet).
User swipes down to update, << Doesn't update the latest image into listview!
Hope a kind soul can help me resolve this.
public class PictureFragment extends Fragment {
private ListView listView;
private int smiley_id;
private String title, date, caption, image;
private ImageButton addPicButton;
private SwipeRefreshLayout swipeRefreshLayout;
private PictureAdapter adapter;
private TableDatabase tableDatabase;
private Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_picture, container, false);
// Set listview
listView = (ListView) rootView.findViewById(R.id.piclistView);
adapter = new PictureAdapter(getActivity().getApplicationContext(), R.layout.row_feed);
listView.setAdapter(adapter);
// Retrieve data from database
tableDatabase = new TableDatabase(getActivity());
// Get rows of database
cursor = tableDatabase.getInformation(tableDatabase);
// Start from the last so that listview displays latest image first
// Check for existing rows
if(cursor.moveToLast()) {
do {
// Get items from each column
smiley_id = cursor.getInt(0);
title = cursor.getString(1);
date = cursor.getString(2);
caption = cursor.getString(3);
image = cursor.getString(4);
// Saves images added by user into listview
PictureItem pictureItem = new PictureItem(smiley_id, title, date, caption, image);
adapter.add(pictureItem);
} while (cursor.moveToPrevious());
}
// Swipe on refresh
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 1000);
}
});
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(firstVisibleItem == 0) swipeRefreshLayout.setEnabled(true);
else swipeRefreshLayout.setEnabled(false);
}
});
// Lead user to UploadImageActivity to insert image to listview
addPicButton = (ImageButton) rootView.findViewById(R.id.addPictureButton);
addPicButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity().getApplicationContext(), UploadImageActivity.class));
}
});
return rootView;
}
UploadImageActivity.java
public class UploadImageActivity extends ActionBarActivity implements View.OnClickListener{
private Calendar cal = Calendar.getInstance();
private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy, EEE # hh:mm a");
EditText pic_title, pic_caption;
ImageView picture;
Button smiley1, smiley2, smiley3, smiley4, smiley5, selected_smiley;
// To store in database
int smiley_id = R.drawable.smile1; // Set default smiley as first smiley if not chosen
String title, date, caption;
String uriPicture; // Save uri in string format to store image as text format in database
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture);
// Removes shadow under action bar
getSupportActionBar().setElevation(0);
pic_title = (EditText) findViewById(R.id.picture_title);
pic_caption = (EditText) findViewById(R.id.picture_caption);
picture = (ImageView) findViewById(R.id.imagebutton);
smiley1 = (Button) findViewById(R.id.button1);
smiley2 = (Button) findViewById(R.id.button2);
smiley3 = (Button) findViewById(R.id.button3);
smiley4 = (Button) findViewById(R.id.button4);
smiley5 = (Button) findViewById(R.id.button5);
selected_smiley = (Button) findViewById(R.id.select_smiley);
picture.setOnClickListener(this);
smiley1.setOnClickListener(this);
smiley2.setOnClickListener(this);
smiley3.setOnClickListener(this);
smiley4.setOnClickListener(this);
smiley5.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_event, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_ok) {
title = pic_title.getText().toString();
date = dateFormatter.format(cal.getTime());
caption = pic_caption.getText().toString();
// Do not save data
if(title.isEmpty()) {
alertUser("Upload failed!", "Please enter title.");
}
else if(caption.isEmpty()) {
alertUser("Upload failed!", "Please enter caption.");
}
else if(uriPicture.isEmpty()) {
alertUser("Upload failed!", "Please upload an image.");
}
// Save data when title, caption and image are not empty
else {
// Add information into database
TableDatabase tableDatabase = new TableDatabase(this);
tableDatabase.putInformation(tableDatabase, smiley_id, title, date, caption, uriPicture);
Toast.makeText(getBaseContext(), "Details successfully saved", Toast.LENGTH_LONG).show();
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// Show the image picked by user
case R.id.imagebutton:
picture.setImageDrawable(null);
Crop.pickImage(this);
break;
// Saves the user's smiley choice
case R.id.button1:
selected_smiley.setBackgroundResource(R.drawable.smile1);
selected_smiley.setText("");
setSmileyID(R.drawable.smile1);
break;
case R.id.button2:
selected_smiley.setBackgroundResource(R.drawable.smile2);
selected_smiley.setText("");
setSmileyID(R.drawable.smile2);
break;
case R.id.button3:
selected_smiley.setBackgroundResource(R.drawable.smile3);
selected_smiley.setText("");
setSmileyID(R.drawable.smile3);
break;
case R.id.button4:
selected_smiley.setBackgroundResource(R.drawable.smile4);
selected_smiley.setText("");
setSmileyID(R.drawable.smile4);
break;
case R.id.button5:
selected_smiley.setBackgroundResource(R.drawable.smile5);
selected_smiley.setText("");
setSmileyID(R.drawable.smile5);
break;
default:
break;
}
}
// This method sets the smiley ID according to what the user picks.
private void setSmileyID(int smileyID) {
this.smiley_id = smileyID;
}
// This method calls alert dialog to inform users a message.
private void alertUser(String title, String message) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UploadImageActivity.this);
dialogBuilder.setTitle(title);
dialogBuilder.setMessage(message);
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(data.getData());
} else if(requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
// This method allows users to crop image in square.
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
// This method ensures there are no errors in cropping.
private void handleCrop(int resultCode, Intent result) {
if(resultCode == RESULT_OK) {
picture.setImageURI(Crop.getOutput(result));
uriPicture = Crop.getOutput(result).toString();
} else if(resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
TableDatabase.java
public class TableDatabase extends SQLiteOpenHelper {
public String query = "CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.SMILEY + " INTEGER NOT NULL, " +
TableData.TableInfo.TITLE + " TEXT, " +
TableData.TableInfo.DATE + " TEXT, " +
TableData.TableInfo.CAPTION + " TEXT, " +
TableData.TableInfo.IMAGE + " TEXT);";
public TableDatabase(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, TableData.TableInfo.DATABASE_VERSION);
// Check if database is created
Log.d("Database operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase db) {
// Create table
db.execSQL(query);
Log.d("Database operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Insert user information into the database
public void putInformation(TableDatabase data, int smiley, String title, String date, String caption, String image) {
// Write data into database
SQLiteDatabase sqLiteDatabase = data.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// Add value from each column into contentvalue
contentValues.put(TableData.TableInfo.SMILEY, smiley);
contentValues.put(TableData.TableInfo.TITLE, title);
contentValues.put(TableData.TableInfo.DATE, date);
contentValues.put(TableData.TableInfo.CAPTION, caption);
contentValues.put(TableData.TableInfo.IMAGE, image);
// Insert into sqlite database
sqLiteDatabase.insert(TableData.TableInfo.TABLE_NAME, null, contentValues);
Log.d("Database operations", "One row inserted");
}
// Retrieve data from database
public Cursor getInformation(TableDatabase data) {
// Read data from sqlite database
SQLiteDatabase sqLiteDatabase = data.getReadableDatabase();
String[] columns = { TableData.TableInfo.SMILEY, TableData.TableInfo.TITLE, TableData.TableInfo.DATE, TableData.TableInfo.CAPTION, TableData.TableInfo.IMAGE };
// Points to first row of table
return sqLiteDatabase.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
}
In my activity I add to it some stuff by checking checkbox and if
list.size()>0 (this condition is in my adapter) shows up button which is redirecting me to second activity. In second activity I display listview filled with items from static list , when I click on it i delete object from list, also Ive made button in second activity which make this list.clear(); finish(); When I return to first activity i've still visible button even if static list was cleared. How to solve it ? I need the simplest ideas becouse i'm a beginner in android. All answers, suggestions, clues are wellcome. If you don't know how to do it, pop up thread. Thank you for your time.
public class TowarAdapter extends ArrayAdapter<Towar> {
private List<Towar> items;
private Activity context;
private int i = 0;
ImageButton b_zatwierdz;
int counter = 0;
boolean user_checked = false;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public TowarAdapter(Activity context, int resource, List<Towar> items,
ImageButton b_zatwierdz) {
super(context, resource);
this.b_zatwierdz = b_zatwierdz;
this.items = items;
this.context = context;
}
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Towar getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
static class ViewHolder {
TextView tvNazwaT;
TextView tvCenaT;
ImageView ivTowar;
CheckBox chb_czy_zamowic;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder view;
// LayoutInflater inflator = activity.getLayoutInflater();
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = new ViewHolder();
convertView = inflator.inflate(R.layout.element, null);
view.tvNazwaT = (TextView) convertView.findViewById(R.id.tvNazwaT);
view.tvCenaT = (TextView) convertView.findViewById(R.id.tvCenaT);
view.chb_czy_zamowic = (CheckBox) convertView
.findViewById(R.id.chb_czy_zamowic);
view.ivTowar = (ImageView) convertView.findViewById(R.id.ivTowar);
convertView.setTag(view);
} else {
view = (ViewHolder) convertView.getTag();
}
view.tvNazwaT.setText(items.get(position).getTow_nazwa());
view.tvNazwaT.setTextColor(Color.BLACK);
view.tvCenaT.setText(items.get(position).getTow_cena() + "zł");
for (int i = 0; i < items.size(); i++) {
String s = Integer.valueOf(items.get(position).Kat_id).toString();
int resourceId = context.getResources().getIdentifier("a" + s + i,
"drawable", context.getPackageName());
view.ivTowar.setImageResource(resourceId);
}
view.chb_czy_zamowic
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
final CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
user_checked = true;
if (user_checked == true) {
final Dialog d1 = new Dialog(context);
d1.setContentView(R.layout.ilosc);
d1.getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
d1.setTitle("Wybierz ilość");
final EditText et_Ilosc;
Button b_Ok;
Button b_Odejmij;
Button b_Dodaj;
et_Ilosc = (EditText) d1
.findViewById(R.id.et_Ilosc);
et_Ilosc.setText(String.valueOf(i));
view.chb_czy_zamowic.setClickable(false);
b_Dodaj = (Button) d1
.findViewById(R.id.b_Dodaj);
b_Dodaj.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmienna_pom = et_Ilosc.getText()
.toString();
i = Integer.valueOf(zmienna_pom);
if (i < 0) {
Toast t = Toast.makeText(
getContext(),
"Niepoprawna wartość",
Toast.LENGTH_SHORT);
t.show();
} else if (i == items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Osiągnięto wartość maksymalną "
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
} else if (i > items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Przekroczono wartość maksymalną "
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
}
else if (et_Ilosc.getText().toString()
.equals("")) {
Toast t = Toast.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
setI(i);
int k = getI();
k++;
setI(k);
et_Ilosc.setText(String.valueOf(i));
}
}
});
b_Odejmij = (Button) d1
.findViewById(R.id.b_Odejmij);
b_Odejmij
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmienna_pom = et_Ilosc
.getText().toString();
i = Integer
.valueOf(zmienna_pom);
if (i < 0) {
Toast t = Toast
.makeText(
getContext(),
"Niepoprawna wartość",
Toast.LENGTH_SHORT);
t.show();
} else if (et_Ilosc.getText()
.toString().equals("")) {
Toast t = Toast
.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
setI(i);
i--;
setI(i);
et_Ilosc.setText(String
.valueOf(i));
}
}
});
b_Ok = (Button) d1.findViewById(R.id.b_Ok);
b_Ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String zmiennna_pom = et_Ilosc
.getText().toString();
int k = Integer.valueOf(zmiennna_pom);
if (k <= 0
|| k > items.get(position)
.getTow_ilosc_value()) {
Toast t = Toast
.makeText(
getContext(),
"Wybierz z przedziału 1-"
+ items.get(
position)
.getTow_ilosc_value(),
Toast.LENGTH_SHORT);
t.show();
} else if (et_Ilosc.getText()
.toString().equals("")) {
Toast t = Toast.makeText(
getContext(),
"Uzupełnij pole ilość",
Toast.LENGTH_SHORT);
t.show();
} else {
view.chb_czy_zamowic
.setEnabled(false);
// String zmiennna_pom = et_Ilosc
// / .getText().toString();
// int k = Integer
// .valueOf(zmiennna_pom);
items.get(position).Tow_ilosc -= k;
Towar checkedObject = new Towar();
checkedObject.Tow_ilosc = k;
checkedObject.Kat_id = items
.get(position).Kat_id;
checkedObject.kategoria = items
.get(position).kategoria;
checkedObject.Tow_cena = items
.get(position).Tow_cena;
checkedObject.Tow_id = items
.get(position).Tow_id;
checkedObject.Tow_nazwa = items
.get(position).Tow_nazwa;
MainActivity.lista_wybranych_towarow
.add(checkedObject);
k = 0;
setI(0);
// et_Ilosc.setText("");
d1.dismiss();
}
// view.chb_czy_zamowic.setChecked(false);
if (MainActivity.lista_wybranych_towarow
.size() > 0) {
b_zatwierdz
.setVisibility(View.VISIBLE);
}
else
b_zatwierdz
.setVisibility(View.INVISIBLE);
}
});
d1.show();
}
;
}
}
});
return convertView;
}
}
To make the button invisible, you need to do the following (I'm just mentioning the logic for hiding the button - you will have to implement this in a listener):
Button button = (Button) findViewById(R.layout.button_id); // Point it to the button
if(list_is_empty) {
button.setVisibility(Button.GONE); // This line hides the button
}
Know that in Android, 'GONE' is used to hide the element from the view and this space is now available in the layout. 'INVISIBLE' means that while the widget is hidden, the space for this widget is still unavailable.
You could put an extra in the intent when calling the activity, or save the flag in a shared preference. Then depending on the flag you can set the visibility to true or false?
you can use startActivityForResult here. when you delete object from list. pass back the boolean where like 'isDelete' and check this variable in onActivityResult (it is first activity) if it is true i.e object is delete so set button visibility to false else do nothing.
you can also used sharedpreferences here. track the boolean variable and depending on its value set the button visibility.
for shared preference do this :
when you delete object do this, to write boolean value to shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); //creating object of shared preference
SharedPreferences.Editor editor = preferences.edit(); //getting editor to write value
editor.putBoolean("isShow",false); //first value is key and second is the value which you are going to assign it
editor.commit();
and in your main adapter class do :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean show = preferences.getBoolean("isShow",false); //first value is key and second value is used if isShow is not defined.
if(show)
//show the button
else
//hide the button
I have a custom ListView, each list item has four TextViews showing bank name, amount, date and time. This data is stored in a database. The idea is that on the Activity there is a quick action dialog which opens on clicking the sort button. The Dialog has three options as "Sort by bank name" ascending order, "Sort by Date" newest first and "Sort by amount" larger amount in the top of the list. I don't have any idea of how to proceed with the sorting task to be written in onItemClick(int pos). Can anyone please help me on this?
public class TransactionMenu extends Activity implements OnItemClickListener, OnActionItemClickListener {
String[] TransId ;
String[] mBankName;
String[] mAmount;
String[] mDate;
String[] mTime;
Button SortButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction_screen);
SortButton = (Button)findViewById(R.id.sortKey);
//Bank Name action item
ActionItem bName = new ActionItem();
bName.setTitle("Bank Name");
bName.setIcon(getResources().getDrawable(R.drawable.bank_256));
//Amount action item
ActionItem amt = new ActionItem();
amt.setTitle("Amount");
amt.setIcon(getResources().getDrawable(R.drawable.cash));
//date action item
ActionItem date = new ActionItem();
date.setTitle("Date");
date.setIcon(getResources().getDrawable(R.drawable.calender));
//create quickaction
final QuickAction quickAction = new QuickAction(this);
quickAction.addActionItem(bName);
quickAction.addActionItem(amt);
quickAction.addActionItem(date);
quickAction.setOnActionItemClickListener(this);
SortButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
//quickAction.setAnimStyle(QuickAction.ANIM_REFLECT);
}
});
DBAdapter lDBAdapter = new DBAdapter(this);
lDBAdapter.open();
/* getTransDetails() returns all the detials stored in the transaction table*/
Cursor mCursor =lDBAdapter.getAllTransDetails();
System.out.println("cur..........."+mCursor);
lDBAdapter.close();
if (mCursor != null) {
int size = mCursor.getCount();
if (mCursor.moveToFirst()) {
TransId = new String[size];
mAmount = new String[size];
mBankName = new String[size];
mDate = new String[size];
mTime = new String[size];
for (int i = 0; i < size; i++, mCursor.moveToNext()) {
TransId[i] = mCursor.getString(0);
mAmount[i] = mCursor.getString(1);
mBankName[i] = mCursor.getString(3);
mDate[i] = mCursor.getString(2);
mTime[i] = mCursor.getString(4);
}
}
}
for (int i = 0; i < mCursor.getCount(); i++) {
System.out.println("TransId is+++++++++++++++ "+TransId[i]);
System.out.println("amount is+++++++++++++++ "+mAmount[i]);
System.out.println("bankName is+++++++++++++++ "+mBankName[i]);
System.out.println("date is+++++++++++++++ "+mDate[i]);
System.out.println("time is+++++++++++++++ "+mTime[i]);
}
ListView myListView = (ListView) findViewById(R.id.transactionListView);
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
myListView.setAdapter(myAdapterObj);
myListView.setOnItemClickListener((OnItemClickListener) this);
}
private class MyBaseAdapter extends ArrayAdapter<String> {
public MyBaseAdapter(Context context, int textViewResourceId, String[] transId) {
super(context, textViewResourceId, transId);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_item, parent, false);
TextView label = (TextView)row.findViewById(R.id.textview1);
label.setText("Amount: "+mAmount[position]);
TextView label1 = (TextView) row.findViewById(R.id.textview2);
label1.setText("Bank Name: "+mBankName[position]);
TextView label2 = (TextView) row.findViewById(R.id.textview3);
label2.setText("Date: "+mDate[position]);
TextView label3 = (TextView) row.findViewById(R.id.textview4);
label3.setText("Time: "+mTime[position]);
return row;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("arg2 is++++++++++++++"+arg2);
int lRowId = Integer.parseInt(TransId[arg2]);
}
public void onItemClick(int pos) {
MyBaseAdapter myAdapterObj = new MyBaseAdapter(TransactionMenu.this, R.layout.list_item, TransId);
if (pos == 0) {
Toast.makeText(TransactionMenu.this, "Bank name item selected", Toast.LENGTH_SHORT).show();
}
else if (pos ==1) {
Toast.makeText(TransactionMenu.this, "amount item selected", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TransactionMenu.this, "Date item selected", Toast.LENGTH_SHORT).show();
}
}
}
I will give you the way i would do this, not the best probably but it will work fine.
Fisrt of all as user7777777777 said it's better to keep related infos into the same object so i'd define BankInfo class as shown below:
private class BankInfo{
String TransId ;
String mBankName;
String mAmount;
String mDate;
String mTime;
public BankInfo(String TransId,String mBankName,String mAmount,String mDate,String mTime)
{
//fields init
}
}
once you have this you will define an Array of this object BankInfo[] trans. In the adapter you can use this array to bind values into views.
then to manage to implement the sorting function the thing i would do is to put a static variable into the BankInfo class and override the CompareTo() method to use that field:
static int AMMOUNT = 0;
static int DATE = 1;
static int NAME = 2;
static public int sort_by;
public int compareTo(BankInfo info){
switch (sorty_by){
case(AMMOUNT):
return //compare by ammount
case(DATE):
return //compare by date
case(NAME):
return //compare by name
}
}
with this inside of BankInfo you will have only to add your array to a TreeSet<BankInfo> and all your item will be sortet using the compareTo() method.
Inside the adapter put this method to sort elements in the adapter
public void sort_datas(int sort_by);
{
//set the type of sort you want
BankInfo.sortBy = sort_by;
//build a Sorted treeSet by the BankInfo array
TreeSet<BankInfo> sorted_info = new TreeSet<BankInfo>();
list.addAll(Arrays.asList(trans));
//replace the BankInfo array with the new sorted one
trans = (BankInfo[])sorted_info.toArray();
//notify to the adapter that the data set changed
notifyDataSetChanged();
}
You can use the following code. You need to maintain the bank info in a BankInfo object. Create an ArrayList of BankInfo objects and then you can use this code. Its not a good practice to keep related info into separate arrays.
Collections.sort(mBankInfoArrayList, new Comparator<BankInfo>() {
int compare(BankInfo obj1, BankInfo obj2) {
return obj1.getBankName().compareToIgnoreCase(obj2.getBankName());
}
});