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.
Related
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 !
****Working code posted****
I am trying to update buttons where the text will be dynamically programmed from an ArrayList. The data is being retrieved from mySQL. I can get the data in and fill the array with what I need (familyMemberArray). However for some reason when the information is gathered, the program does not go on to implementing the "trending" array or the rest of the layout programming, after the array information has been produced.
I need to formulate the data first so I know how big the array is to create the amount of buttons necessary. If I call in a basic String array it populates the buttons just fine. I remember being stuck on this problem on a uni project and ended up giving up because I just could not get it to work and time was ticking. Please put me out of my misery
public class TrendingMealsFragment extends Fragment {
private TableRow tr;
//SQLite Database
private static final String SELECT_SQL = "SELECT * FROM family_account";
private SQLiteDatabase db;
private Cursor c;
private static final String DATABASE_NAME = "FamVsFam.db";
// Logging
private final String TAG = this.getClass().getName();
private static final String EXTRA_CHALLENGE_ID = "boo.famvsfam.challenge_id";
//Results
private JSONArray resultFamilyMember;
private String dbID;
public static final String JSON_ARRAY = "result";
private List<String> familyMemberArray;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openDatabase();
setHasOptionsMenu(true);
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
getRecords();
}
protected void openDatabase() {
db = getActivity().openOrCreateDatabase(DATABASE_NAME, android.content.Context.MODE_PRIVATE, null); // db = SQLiteDatabase.openOrCreateDatabase("FamVsFam", Context.MODE_PRIVATE, null);
}
protected void getRecords() {
dbID = c.getString(0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getData();
/** Declaring an ArrayAdapter to set items to ListView */
familyMemberArray = new ArrayList<>();
//Menu
setHasOptionsMenu(true);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
View view = inflater.inflate(R.layout.activity_resturants, container, false);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar();
/**
ArrayList<String> trending1 = new ArrayList<String>() {
{
add("one");
add("two");
add("three");
add("four");
add("five");
add("six");
add("seven");
add("eight");
add("nine");
add("ten");
add("eleven");
}
};*/
ArrayList<String> trending = new ArrayList<String>() {
{
for(int i = 0; i < familyMemberArray.size() ; i++){
add(familyMemberArray.get(i));
}}
};
// LAYOUT SETTING 1
RelativeLayout root = new RelativeLayout(getActivity());
// root.setId(Integer.parseInt(MEAL_SELECTION_ID));
LayoutParams param1 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
root.setFitsSystemWindows(true);
}
root.setLayoutParams(param1);
//LAYOUT SETTINGS 2 - TOP BANNER - WITH PAGE HEADING
RelativeLayout rLayout1 = new RelativeLayout(getActivity());
LayoutParams param2 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
float topBannerDim = getResources().getDimension(R.dimen.top_banner);
param2.height = (int) topBannerDim;
param2.addRule(RelativeLayout.BELOW, root.getId());
int ele = (int) getResources().getDimension(R.dimen.elevation);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
rLayout1.setElevation(ele);
}
rLayout1.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout1.setLayoutParams(param2);
//TEXT VIEW
TextView text1 = new TextView(getActivity());
text1.setText(R.string.diet_req);
LayoutParams param3 = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
param3.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
text1.setTextColor(Color.parseColor("#8A1F1D"));
text1.setTypeface(Typeface.DEFAULT_BOLD);
text1.setLayoutParams(param3);
//LAYOUT SETTINGS 4
RelativeLayout rLayout4 = new RelativeLayout(getActivity());
LayoutParams param5 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
topBannerDim = getResources().getDimension(R.dimen.top_banner);
param5.height = (int) topBannerDim;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
param5.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.ALIGN_START);
}
param5.addRule(RelativeLayout.BELOW, rLayout1.getId());
rLayout4.setId(R.id.id_relative_4);
rLayout4.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout4.setLayoutParams(param5);
//LAYOUT SETTINGS 5
TableLayout rLayout5 = new TableLayout(getActivity());
rLayout5.setOrientation(TableLayout.VERTICAL);
LayoutParams param7 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
param7.addRule(RelativeLayout.BELOW, rLayout4.getId());
rLayout5.setBackgroundColor(Color.parseColor("#EEEBAA"));
rLayout5.setLayoutParams(param7);
// List<ToggleButton> togButtStore = new ArrayList<ToggleButton>();
int i = 0;
while (i < trending.size()) {
if (i % 3 == 0) {
tr = new TableRow(getActivity());
rLayout5.addView(tr);
}
ToggleButton toggleBtn = new ToggleButton(getActivity());
toggleBtn.setText(trending.get(i));
toggleBtn.setId(i);
toggleBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
// The toggle is disabled
}
}
});
tr.addView(toggleBtn);
i++;
}
//LAYOUT SETTINGS 6
FrameLayout youBeenFramed = new FrameLayout(getActivity());
LayoutParams param8 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
param8.addRule(RelativeLayout.BELOW, rLayout5.getId());
youBeenFramed.setBackgroundColor(Color.parseColor("#EEEBAA"));
root.addView(youBeenFramed);
root.addView(rLayout1);
rLayout1.addView(text1);
root.addView(rLayout4);
root.addView(rLayout5);
getActivity().setContentView(root);
return view;
}
public void getData() {
//// TODO: 03/08/2016 Progress Dialogs : on getting data
// final ProgressDialog loading = ProgressDialog.show(getActivity(), "Loading Data", "Please wait...", false, false);
StringRequest strReq = new StringRequest(Request.Method.POST,
PHPConfigURLS.URL_ALL_FAMILY_MEMBERS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
JSONObject j = null;
try {
// loading.dismiss();
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFamilyMember = j.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getDBFamilyName(resultFamilyMember);
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
String id = dbID;
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
// params.put("email", email);
// params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(strReq);
}
private void getDBFamilyName(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
FamilyAccount familyMember = new FamilyAccount();
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
familyMember = new FamilyAccount();
familyMember.setName(json.getString("name"));
familyMember.setID(json.getInt("id"));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the title of the challenge to array list
familyMemberArray.add(familyMember.getName());
}
}
}
Thanks in advance
for some reason when the information is gathered, the program does not go on to implementing the "trending" array or the rest of the layout programming, after the array information has been produced.
That's because the layout doesn't "dynamically" update when you call this when the request finishes.
familyMemberArray.add(familyMember.getName());
You'll have to clear the view, and redo all the view adding again, or "extract" all the view generation code into it's own method that you can call with the parameter of your ArrayList.
Basically, everything between // LAYOUT SETTING 1 and return view (non-inclusive) needs to be moved into a public void generateView(ArrayList<String> familyMemberArray) method that can optionally return the root View that was generated, if necessary.
Then, at the end of getFamilyName(), outside the loop, call that method with your ArrayList.
I need to formulate the data first so I know how big the array is to create the amount of buttons necessary.
I'm not sure I see where you are doing that. Unless you mean here
while (i < trending.size()) {
Which, instead, trending is an entirely different list reference than familyMemberArray, so it won't update either. Though, it contains the exact same data?
ArrayList<String> trending = new ArrayList<String>() {
{
for(int i = 0; i < familyMemberArray.size() ; i++){
add(familyMemberArray.get(i));
}}
};
That block of code looks a bit odd, considering the ArrayList constructor already provides that functionality
ArrayList<String> trending = new ArrayList<String>(familyMemberArray);
*****WORKING CODE****** Credit to cricket_007
FIELDS
public class TrendingMealsFragment extends Fragment {
// Logging
private final String TAG = this.getClass().getName();
//Results
private JSONArray resultFamilyMember;
public static final String JSON_ARRAY = "result";
private ArrayList<String> familyMemberArray;
//Layout
private TableRow tr;
OnCreateView()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_resturants, container, false);
generateView(familyMemberArray);
getData();
return view;
}
GetData()
public void getData() {
StringRequest strReq = new StringRequest(Request.Method.POST,
PHPConfigURLS.URL_ALL_FAMILY_MEMBERS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFamilyMember = j.getJSONArray(JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getDBFamilyName(resultFamilyMember);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
String id = dbID;
Map<String, String> params = new HashMap<String, String>();
params.put("id", id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(strReq);
}
getDBFamilyName()
private void getDBFamilyName(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
FamilyAccount familyMember = new FamilyAccount();
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
familyMember = new FamilyAccount();
familyMember.setName(json.getString("name"));
familyMember.setID(json.getInt("id"));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the title of the challenge to array list
familyMemberArray.add(familyMember.getName());
generateView(familyMemberArray);
}
}
generateView()
public View generateView(ArrayList<String> familyMemberArray) {
...
rLayout5.setLayoutParams(param7);
//Create Buttons
int i = 0;
while (i < familyMemberArray.size()) {
if (i % 3 == 0) {
tr = new TableRow(getActivity());
rLayout5.addView(tr);
}
ToggleButton toggleBtn = new ToggleButton(getActivity());
toggleBtn.setText(familyMemberArray.get(i));
toggleBtn.setId(i);
toggleBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Context context = getActivity().getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} else {
// The toggle is disabled
}
}
});
tr.addView(toggleBtn);
i++;
}
...
root.addView(rLayout5);
getActivity().setContentView(root);
return root;
}
}
I dont know why i cant compile my code , it is setting me that ContentProvider.createUri cannot resolve method. What i am missing can anyone tell me please. Here is my code for class:
public class Connectivity extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
MySQLiteHelper db;
String[] name;
String[] username;
String[] password;
String[] category;
int[] ids;
int[] color;
ListView listView;
Cursor identityCursor;
FloatingActionButton addIndentity;
int REQUEST_CODE =0;
int color1;
ToastersAdapter customAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.cards_frag, container, false);
addIndentity = (FloatingActionButton) android.findViewById(R.id.fab3);
db = new MySQLiteHelper(getActivity());
final List<IdentityHelper> list = db.getAllIdentities();
name= new String[db.getIdentitiesCount()];
username = new String[db.getIdentitiesCount()];
password = new String[db.getIdentitiesCount()];
category = new String[db.getIdentitiesCount()];
color = new int[db.getIdentitiesCount()];
ids = new int[db.getIdentitiesCount()];
for (int i = 0; i < list.size(); i++) {
IdentityHelper n= list.get(i);
name[i]= n.getName();
username[i]=n.getUsername();
password[i]=n.getPassword();
category[i]=n.getCategory();
color[i] = n.getColor();
ids[i] = n.getId();
}
addIndentity.setOnClickListener(handler);
// Get access to the underlying writeable database
SQLiteDatabase dbs = db.getWritableDatabase();
// Query for items from the database and get a cursor back
identityCursor = dbs.rawQuery("SELECT * FROM Identities ORDER BY category", null);
listView = (ListView) android.findViewById(R.id.listView1);
customAdapter = new ToastersAdapter(getActivity(), identityCursor);
listView.setAdapter(customAdapter);
addIndentity.attachToListView(listView);
getActivity().getSupportLoaderManager().initLoader(0, null, Connectivity.this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
ToastersAdapter adapter1 = (ToastersAdapter) adapter.getAdapter();
Object sectionObject = adapter1.getItem(position);
int cursorPosition = adapter1.getCursorPositionWithoutSections(position);
if (adapter1.isSection(position) && sectionObject != null) {
// Handle the section being clicked on.
Toast.makeText(getActivity(),"Header Clicked", Toast.LENGTH_SHORT).show();
} else if (cursorPosition != SectionCursorAdapter.NO_CURSOR_POSITION) {
// Handle the cursor item being clicked on.
//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("Name", name[cursorPosition]);
bundle.putString("Username",username[cursorPosition]);
bundle.putString("Password",password[cursorPosition]);
bundle.putString("Category", category[cursorPosition]);
bundle.putInt("Color", color[cursorPosition]);
bundle.putInt("ID", ids[cursorPosition]);
Intent intent = new Intent(getActivity(), theIdentity.class);
intent.putExtras(bundle);
Connectivity.this.startActivity(intent);
getActivity().overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);
getActivity().finish();
}}
});
return android;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
**String orderBy = category[id] + " ASC, " + name[id] + " ASC";
return new CursorLoader(this, ContentProvider.createUri(IdentityHelper.class, null), null, null, null, orderBy);**
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
customAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
customAdapter.swapCursor(null);
}
I have used https://github.com/twotoasters/SectionCursorAdapter, for Cursor adapter to manipulate the ListView. I will really appreciate any help
Since there is no createUri method in android.content.ContentProvider class, it appears to me that your ContentProvider class is from some other library.
May be it is ActiveAndroid, which has createUri method in com.activeandroid.content.ContentProvider class.
I dont know why i cant compile my code , it is setting me that ContentProvider.createUri cannot resolve method
There is no method named createUri() on ContentProvider, whether static or otherwise.
I have a Custom ArrayList as follows.
public class sendivitesadapter extends ArrayAdapter<Item>{
private Context context;
private ArrayList<Item> items;
private qrusers qrusers;
private LayoutInflater vi;
public sendivitesadapter(Context context,ArrayList<Item> items) {
super(context, 0,items);
this.context= context;
this.qrusers =(qrusers) context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
#Override
public Item getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
}else{
sendItem ei = (sendItem)i;
v = vi.inflate(R.layout.checkboxlist, null);
final TextView title = (TextView)v.findViewById(R.id.contactname);
final TextView subtitle = (TextView)v.findViewById(R.id.companyname);
final CheckBox checkBox=(CheckBox)v.findViewById(R.id.checboxlist);
if (title != null)
title.setText(ei.contactname);
if(subtitle != null)
subtitle.setText(ei.companyname);
}
}
return v;
}
and it looks like following image.
My java file is as follows.
#Override
protected void onPostExecute(String result) {
JSONArray jarray;
try {
jarray= new JSONArray(result);
name= new String[jarray.length()];
company=new String[jarray.length()];
for (int i=0;i<jarray.length();i++){
JSONObject jobj = jarray.getJSONObject(i);
name[i]= jobj.getString("Name");
company[i]=jobj.getString("Company");
items.add(new sendItem(name[i], company[i], checkBox));
adapter = new sendivitesadapter(qrusers.this,items);
listView.setAdapter(adapter);
Now I get the names from webservice which I am diplaying it in a listview as shown above.
With every name I get a USerID. So my question is whenever the user checks the checkbox in any sequence and click on add user I want the UserID of the checked checkboxes in array. How can I achieve this?
Sounds like it's a good candidate for View.setTag(). You could set the tag on each CheckBox to the id of the user [when you create it, or assign the Name and Company values]. Then in an OnClick or OnChecked type event, you can call view.getTag() to retrieve the id of the currently checked box.
You need to use OnCheckedChangeListener to get the cheched CheckBox ID. This SO will help you- How to handle onCheckedChangeListener for a RadioGroup in a custom ListView adapter . You need to modify the onCheckedChangeListener according to your need.
In your adapter set the position in check box like
checkBox.setTag(position);
And as i think you have to add checked user on click of Add User button. So on click of that button write following code.
public void onClick(View v) {
// TODO Auto-generated method stub
String categoryArray = "";
String[] categoryId;
if(v == AddUser){
int count = 0;
for(int i = 0; i < listViewRightSlideMenu.getChildCount(); i ++){
RelativeLayout relativeLayout = (RelativeLayout)listViewRightSlideMenu.getChildAt(i);
CheckBox ch = (CheckBox) relativeLayout.findViewById(R.id.checkBoxCategory); //use same id of check box which you used in adapter
if(ch.isChecked()){
count++;
categoryArray = categoryArray+ch.getTag()+",";
}
}
if(categoryArray.length() > 0) {
categoryArray = categoryArray.substring(0, categoryArray.length() - 1);
String[] array = categoryArray.split(",");
categoryId = new String[array.length];
for(int i = 0; i< array.length; i++) {
categoryId[i] = listCategory.get(Integer.valueOf(array[i])).getId();
}
for(int i = 0; i < categoryId.length; i++){
String a = categoryId[i];
System.out.println("category id is: "+a);
}
System.out.println("array position: "+categoryId);
}
}
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());
}
});