display hashmapped values in alertbox in android - java

I am getting some details from webservice and i need to display those details with checkboxes associated with it on its leftside dynamically(using java code).I already mapped all details to a Hashmap Arraylist correctly,What to do next is that display all the details to the alertbox,which is defined in my code..I tried a lot.Can anybody help me any help will be highly appreciable.....
selectButton.setOnClickListener(new View.OnClickListener() {
private Builder mDialog;
#Override
public void onClick(View v) {
Log.e(tag,"alertbox for onclickworked");
Context c =getParent();
this.mDialog = new AlertDialog.Builder(c);
alertDialog = mDialog.create();
// Setting Dialog Title
alertDialog.setTitle("Intrested In");
new Serviceclass().execute();
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.gate_logo);
alertDialog.show();
}
class Serviceclass extends AsyncTask<Void, Void, String>
{
protected String doInBackground(
Void... params) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
Log.e(tag,"inside getvaluesforcheckbox()");
offferList = new ArrayList<HashMap<String, String>>();
Log.e(tag,"arraylist created");
try{
UserFunctions usf=new UserFunctions();
JSONObject json2 = usf.intrestlist(user_id);
Log.e(tag,"before try");
Log.e(tag,"after try");
JSONArray contacts = json2.getJSONArray("interested_list");
Log.e(tag,"outside forloop");
for(int i = 0; i < contacts.length(); i++){
Log.e(tag,"inside forloop");
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = contacts.getJSONObject(i);
map.put(KEY_INTRESTID, c.getString("interested_id"));
Log.e("requestclass.java",c.getString("interested_id"));
map.put(KEY_INTRESTNAME, c.getString("interested_name"));
Log.e("requestclass.java",c.getString("interested_name"));
map.put(KEY_STAUS, c.getString("status"));
Log.e("requestclass.java",c.getString("status"));
if(c.getString("interested_info").equals("null"))
{
map.put(KEY_INTERESTINFO,"");
}
else
{
map.put(KEY_INTERESTINFO,c.getString("interested_info"));
}
offferList.add(map);
// cadapter = new ClientListAdapter(this, R.layout.client_list,
// ClientDetailsCollection.getClientDetailssAsArray(), this);
}
Log.e(tag,"datas added to arraylist");
checkboxgeneration();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
HERE I NEED TO WRITE THE CODE
}
}
Advance Thanks.....

You have web request to make and display the records in dialog. Here what I suggest you.
1. Use DialogFragments.
2. Inside fragment make a listview, create custom adapter according to your design. 3. Make Web Request inside fragment. 4. For your ease you can read this Tutorial Android DialogFragment and ListView

Related

How to change recycler view item dynamically?

I have created a RecyclerView to show each node that I have connected. In the RecyclerView I have added two buttons and one TextView. The TextView will show the current status of the node i.e. whether the node in currently on or off. The nodes are sending their current status over MQTT, I am able to detect the current status of every node on my app but I am unable to update the TextView according to it. How can I update the TextView?
I have tried adding new item and deleting the previous one, but none of them works for me. I have added the code where I am detecting from which node the status message is coming.
//From this section I am getting details of my all node stored into the database
public void addData()
{
pumpList = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, REQUEST_URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONArray pumpData = new JSONArray(response);
for(int i = 0; i < pumpData.length(); i++)
{
JSONObject pump = pumpData.getJSONObject(i);
String name = pump.getString("name");
String device_id = pump.getString("device_id");
String stat = pump.getString("stat");
Log.d("HTTP",String.valueOf(name));
Log.d("HTTP",String.valueOf(device_id));
Log.d("HTTP",String.valueOf(stat));
pumpList.add(new pumpData(name,device_id,stat));
}
pumpAdapter adapter = new pumpAdapter(getActivity(),pumpList);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
catch (JSONException e)
{
e.printStackTrace();
progressDialog.dismiss();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getActivity(),error.getMessage(),Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
//When I get a message over MQTT then I am showing from which device the MQTT Message is Coming from
public void changeDataByFiltering(String MQTT_TOPIC, String MQTT_PAYLOAD)
{
for(pumpData pD: pumpList)
{
insertStringSubscribe INSSUB = new insertStringSubscribe();
String mqtt_topic_from_list = INSSUB.insertString(pD.getDeviceID());
if(mqtt_topic_from_list.trim().toLowerCase().equals(MQTT_TOPIC.trim().toLowerCase()))
[enter image description here][1]{
if(MQTT_PAYLOAD.trim().toLowerCase().equals(payloadON.trim().toLowerCase()))
{
Toast.makeText(mCtx, pD.getName()+": ON",Toast.LENGTH_SHORT).show();
}
if(MQTT_PAYLOAD.trim().toLowerCase().equals(payloadOFF.trim().toLowerCase()))
{
Toast.makeText(mCtx, pD.getName()+": OFF",Toast.LENGTH_SHORT).show();
}
}
}
}
I assume that we have a List<String> data as our data source and we have rvadapter which is our RecyclerView.Adapter . and we will do as below to update an item:
data.set(position,"newdata");
rvadapter.notifyItemChanged(position);
Also, you can change the range of items. and insert new item or delete item but have to call notify... related function in rvadapter
but if you recreate the data for example :
data = new ... then you have to use notifydatasetchanged;

Android app extremely slow to swipe viewpager and scroll through recyclerview, how to pintpoint cause?

So, I've been stuck on this issue for a week where I launch my app and it freezes for almost 10 seconds on a white screen and after that the app gets really slow. I have a bottomnavigationview with a viewpager that loads four fragments, some of which have recyclerviews with custom adapters. Everytime I swipe or select a different tab, the app is painfully slow to select the new tab. Even the recyclerview scrolling is really slow. The weird part is that when data is switched off, the app works just fine and the viewpager swipes and recyclerview scrolls are fast enough.
I have seen several suggestions which suggest using gson parsing for the json data received from online, but the performance increase was negligible. I have also tried viewPager.setOffscreenPageLimit(4); but that hasn't helped. All my network calls have been placed on an asycntask and I have used StrictMode to confirm that. The app also works ok on an emulator, so the problem is only on real devices of all apis that I have tested.
//First Fragment
public void loadData(final Context context, final boolean b) {
HurlStack hurlStack = new HurlStack() {
#Override
protected HttpURLConnection createConnection(URL url) {
HttpsURLConnection httpsURLConnection = null;
try {
httpsURLConnection = CustomCAHttpsProvider.getHttpsUrlConnection(ServerConstants.LOAD_CHAT_URL, InfosylumApplication.getContext(), R.raw.certificate, false);
} catch (Exception e) {
e.printStackTrace();
Helper.showErrorDialog(e.getMessage(), e.toString(), InfosylumApplication.getContext());
}
return httpsURLConnection;
}
};
StringRequest stringRequest = new StringRequest(Request.Method.POST, ServerConstants.LOAD_CHAT_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mSwipeRefreshLayout.setRefreshing(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isRunning) {
loadData(context, b);
}
}
}, 3000);
try {
JSONObject jsonObject = new JSONObject(response).getJSONObject("object");
TinyDB tinyDB = new TinyDB(context);
tinyDB.putString(TinyDBConstants.LOCAL_TYPING, "");
if (jsonObject.has("groupsAndInd")) {
final JSONArray array = jsonObject.getJSONArray("groupsAndInd");
LinkedHashMap<String, ChatNotification> chatNotificationLinkedHashMap = new LinkedHashMap<>();
final JSONArray localChatArray;
if (!tinyDB.getString(TinyDBConstants.LOCAL_CHAT_OTHER).isEmpty()) {
localChatArray = new JSONArray(tinyDB.getString(TinyDBConstants.LOCAL_CHAT_OTHER));
} else {
localChatArray = new JSONArray();
}
ArrayList<String> localChatIds = new ArrayList<>();
final ArrayList<String> onlineChatIds = new ArrayList<>();
String idsString = "";
for (int i = 0; i < localChatArray.length(); i++) {
JSONObject foodJson = localChatArray.getJSONObject(i);
localChatIds.add(foodJson.getString("id"));
idsString += foodJson.getString("id") + "\n";
}
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
List<String> urlList = Arrays.asList(object.getString("seenUsers").split(","));
if ((!urlList.contains(PatriceUser.getCurrentUser().getObjectId()) || object.getInt("messageStatus") < (Const.MESSAGE_STATUS_RECEIVED)) && !localChatIds.contains(object.getString("id")) && !object.getString("senderId").equals(PatriceUser.getCurrentUser().getObjectId())) {
String id = null, chatType = null;
switch (object.getString("chatType")) {
case Const.CHAT_TYPE_GROUP:
id = object.getString("groupId");
chatType = Const.CHAT_TYPE_GROUP;
break;
case Const.CHAT_TYPE_INDIVIDUAL:
id = object.getString(Const.SENDER_ID);
chatType = Const.CHAT_TYPE_INDIVIDUAL;
break;
}
boolean found = false;
if (chatNotificationLinkedHashMap.containsKey(id)) {
ChatNotification chatNotification = chatNotificationLinkedHashMap.get(id);
chatNotification.addChatObject(object);
chatNotificationLinkedHashMap.put(id, chatNotification);
} else {
ChatNotification chatNotification = new ChatNotification(context, chatType, id, object);
chatNotificationLinkedHashMap.put(id, chatNotification);
}
}
onlineChatIds.add(object.getString("id"));
}
tinyDB.putString(TinyDBConstants.LOCAL_CHAT_OTHER, array.toString());
for (Map.Entry<String, ChatNotification> entry : chatNotificationLinkedHashMap.entrySet()) {
String key = entry.getKey();
ChatNotification value = entry.getValue();
final InfosylumNotification infosylumNotification = new InfosylumNotification(context);
infosylumNotification.showNotification(value);
}
}
try {
if (jsonObject.has("groupsAndInd")) {
getActualMessages(jsonObject.getJSONArray("groupsAndInd"), jsonObject.getJSONArray("unread"));
}
if (jsonObject.has("notes")) {
loadNotes(jsonObject.getJSONArray("notes"));
}
} catch (NullPointerException ignore) {
Helper.showErrorDialog("ignore", ignore.getMessage(), getActivity());
}
} catch (JSONException e) {
} catch (NullPointerException e) {
//When the user has logged out
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userId", PatriceUser.getCurrentUser().getObjectId());
params.put("loadGroupsQuery", loadGroupsQuery);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
40000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(activity).addToRequestQueue(stringRequest);
stringRequest.setTag(REQUEST_TAG);
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(InfosylumApplication.getContext(), hurlStack);
}
requestQueue.add(stringRequest);
}
The other fragments are quite similar in how they obtain data there are also background jobs within the app and I think the hardest thing to do is to pinpoint which method is causing the bug. Also, using the profiler is out of the question because the device being used is of API 17. I'd just like to ask, is there any way I can pinpoint which method exactly is causing the sluggishness and the occasional ANRs that I receive?
Looking at your code you are creating new HttpURLConnection every time you call loadData(), which is unnecessary.Try to use Singleton design pattern to create httpConnection instance only once.
Here : new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isRunning) {
loadData(context, b);
}
}
}, 3000);
this code you are executing from loadData() so there is recursive call (you call this method again and again every 3 seconds (if isRunning==true)).
In that case try to create all variable (specially lists) outside of the this method so you will just use them repeatedly not create new instance every time.
When you don't have an internet it is working fast because you aren't executing onResponse (which contains several loops) but only small onErrorResponse.
What are you trying to do with method? maybe I can help you by providing some alternative solution for it.
UPDATE where are you performing asynch tasks? Handler performs on the same thread it was created? is it AsynchTask or is it main thread are calling loadData()

I'm Using NotifydataAdapter But It's Not Working When Value change on database;

I am getting data from server as json. Everything works but notifyDataSetChanged is not working.
BackGroundTask backGroundtask = new BackGroundtask();
backGroundTask.execute(arrayList);
private class BackGroundWorkeroneSignup extends AsyncTask<List<CheckingDTO>,CheckingDTO, CheckingDTO> {
#Override
public void onResponse(JSONObject response) {
CheckingDTO check = new CheckingDTO(email_c+"=="+pass_c,email_c,pass_c,email_c,pass_c);
arrayList.add(checkingDTO);
adapterActivity = new HistoryAdapter(arrayList);
recyclerView.setAdapter(adapterActivity);
#Override
protected void onPostExecute(CheckingDTO data) {
super.onPostExecute(data);
arrayList.clear();
List<CheckingDTO> list = new ArrayList<>();
list.add(data);
adapterActivity = new HistoryAdapter(list);
adapterActivity.notifyDataSetChanged();
}
I'm posting the relevant code that I've sent you in the email.
oncreate method
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
adapterActivity = new HistoryAdapter(arrayList);
recyclerView.setAdapter(adapterActivity);
backGroundWorkeroneSignup = new BackGroundWorkeroneSignup();
backGroundWorkeroneSignup.execute(arrayList);
background method:
try {
JSONArray jsonArray = response.getJSONArray("get_request");// this is your array containing data
for (int i=0;i<jsonArray.length();i++) {
JSONObject jobj = jsonArray.getJSONObject(i);
String id = jobj.getString("id");
String email_c =jobj.getString("pick_lat");
String pass_c = jobj.getString("pick_lon");
checkingDTO = new CheckingDTO(email_c+"=="+pass_c,email_c,pass_c,email_c,pass_c);
CheckingDTO check = new CheckingDTO(email_c+"=="+pass_c,email_c,pass_c,email_c,pass_c);
arrayList.add(check);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
on PostExecute
adapterActivity.notifyDataSetChanged();
In First Part Notice the recyclerView.setAdapter(adapterActivity);
In Background Mode:
when you loop in Array always remember: index starts from 0 therefore it's always less then size of array i.e. for (int i=0;i<jsonArray.length();i++)
You should always create new object of Model class in loop for and then add it in loop. There in no need of calling the notifydatasetchanged in loop.
In onPostExecute: we call the notifydatasetchanged only because we've already added all the elements in the list.
hope that explains all of your queries. let me know if you have confusion in any case

loading data from online MySQL database to android application

I am using this code to load data from online database to my android application .
I am wondering what can i add to make this code better ?
Sometimes the progress dialog keeps spinning and never gets the data, the application is stuck then, any ideas on how i can prevent that ?
class LoadAllSections extends AsyncTask<String, String, String>
{
// make a progress dialog appear with the selected specifics
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading all sections, please wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
// in the background run this code to retrieve data from the server
protected String doInBackground(String... args)
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_Sections,"POST", params);
try
{
int success = json.getInt(TAG_SUCCESS);
sections = json.getJSONArray(TAG_SECTIONS);
if (success == 1)
{
for (int i = 0; i < sections.length(); i++)
{
JSONObject c = sections.getJSONObject(i);
section_id = c.getString(TAG_SECTION_ID);
section_name = c.getString(TAG_SECTION_NAME);
section_desc = c.getString(TAG_SECTION_DESC);
section_image = c.getString(TAG_SECTION_IMAGE);
section_valid = c.getString(TAG_SECTION_VALID);
HashMap <String,String> sectionmap = new HashMap<String,String>();
sectionmap.put(TAG_SECTION_ID, section_id);
sectionmap.put(TAG_SECTION_NAME, section_name);
sectionmap.put(TAG_SECTION_DESC, section_desc);
sectionmap.put(TAG_SECTION_IMAGE, section_image);
sectionmap.put(TAG_SECTION_VALID, section_valid);
sectionlist.add(sectionmap);
}
}
else
{
finish();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
// disable the progress dialog and load data to the gridview
protected void onPostExecute(String file_url)
{
pDialog.dismiss();
adapter=new SectionAdapter(MainActivity.this,sectionlist);
SectionsGridView.setAdapter(adapter);
}
}
I wanted to add a comment, but I am not allowed to.
Don't have enough reputation :-(
Pass url_section as argument to doInBackground instead of making it global.
I would place the httpRequest insde a try catch block.
Did you set the timeout, if the httpRequest is not answering? I would set that to
60 seconds. I think by default this is set to 600 seconds.
Why do you pass the file_url to onPostExecute instead of passing the
sectionList?
Take a look at AsyncTask. If you don't want to pass anything between the methods, you can also use Void. So in your case AsyncTask would also do it.

Debugging with breakpoints never enters subclass

My listview is not being populated with the data I am pulling from a MySQL database. I have tested the web service and everything is perfect. I was debugging it and I noticed that when I set a breakpoint inside my asynctask it never went there. I stepped from the execute command and it never went inside. Everything runs fine with no errors. I am confused and new, please be gentle.
public class Favorites extends Activity{
UserFunctions userFunctions = new UserFunctions();
ArrayList<String> zipcodes = new ArrayList<String>(0);
ArrayAdapter<String> arrayAdapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favoritespage);
arrayAdapter1 = new ArrayAdapter<String>(Favorites.this,android.R.layout.activity_list_item,zipcodes);
new DownloadDataTask().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main_screen, menu);
return true;
}
private class DownloadDataTask extends AsyncTask<JSONArray, JSONArray, ArrayList<String> > {
#Override
protected ArrayList<String> doInBackground(JSONArray... params) {
JSONArray json = userFunctions.ziplistrequest("37.5", "140.45", "20");
for(int i=0; i < json.length() ; i++) {
JSONObject jarray = null;
try {
jarray = json.getJSONObject(i);
String zip = jarray.getString("ZIPCODE");
zipcodes.add(zip);
arrayAdapter1.add(zip);
Log.d(zip,"Output");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return zipcodes;
}
protected void onPostExecute(){
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(arrayAdapter1);
}
}
If any additional answers are needed please let me know.
Good stuff. I'll add my comment as an answer for Q&A closure and pure SO point greed :)
What happens if you stick the debug point directly on the async task
doInBackground? Clean & build your project (if using an Eclipse IDE)
in case there are some compiler/class generation issues

Categories