Debugging with breakpoints never enters subclass - java

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

Related

doInBackground does not run inside Activity onCreate

What I have :
I have a SearchActivity which receives an ArrayList (NameDesSearch) from a fragment(after a button click) and it updates a simple listview. When I click a list view item a new view is appearing by the corresponding object (orgDesObj) of the clicked list item. This functionality works well.
Currently receiving list (NameDesSearch) consists of names and descriptions. All are strings.
But, I wanted to show lists names only. Hence I tried creating a function (titlefunc()).
Here a new ArrayList ( NameDesTitles ) was crated to add relevent names only.
Issue:
But, seems like Do In background function is not working by the time I call titlefunc().
Attempts:
I put several Log to capture the point.
I'm using the same function (getLocDesOb()) in the list view on item clicked as well.
Surprisingly it works, even the doInBackground function also works.
But when the search activity creates and titlefunc() is called, search list (finalODescriptionArrayList) in doInBackground is empty().
Form the Logs I receive the content of finalODescriptionArrayList as [] and size as 0.
But, when I click list view item finalODescriptionArrayList updates.
I even tried by moving NameDesSearch = getIntent().getStringArrayListExtra("searched"); outside of the function as well.
Seems like my doInBackground method is calling only when the list item clicked but not activity on creates. Every other function works well. I'm not sure by the time when why my titlefunc() is called, why finalODescriptionArrayList does not update.
I would appreciate any suggestions on this. Thank you !
My Code: I have removed Logs for clearness.
public class SearchActivity extends AppCompatActivity {
ListView searchedListView;
String SearchedWord;
private ArrayAdapter<String> orgAdapter;
ArrayList<String> NameDesSearch = new ArrayList<String>();
ArrayList<String> NameDesTitles = new ArrayList<String>();
private OService OService;
ArrayList<ODescription> finalODescriptionArrayList = new ArrayList<ODescription>();
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
searchedListView = (ListView) findViewById(R.id.searched_list_view);
new GetCourse().execute();
titlefunc();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, NameDesTitles);
searchedListView.setAdapter(arrayAdapter);
searchedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItemText = parent.getItemAtPosition(position).toString();
ODescription orgDesObj = getLocDesOb(selectedItemText);
if (orgDesObj != null) {
Intent intent = new Intent(SearchActivity.this, View.class);
intent.putExtra("sOb", orgDesObj);
startActivity(intent);
}
}
});
}
#SuppressLint("StaticFieldLeak")
private class GetCourse extends AsyncTask<Void, Void, Void> {
#TargetApi(Build.VERSION_CODES.N)
#Override
protected Void doInBackground(Void... voids) {
try {
finalODescriptionArrayList = JsontoObject.jsonToObjectData(getResources().openRawResource(R.raw.newdb));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public ODescription getLocDesOb(String selectedItemText) {
if (finalODescriptionArrayList == null) {
return null;
}
for (ODescription locDescObj : finalODescriptionArrayList) {
if (locDescObj.getName().equals(selectedItemText) || locDescObj.getDescription().equals(selectedItemText)) {
return locDescObj;
}
}
return null;
}
public void titlefunc() {
NameDesSearch = getIntent().getStringArrayListExtra("searched");
for (String searchNameDes : NameDesSearch) {
ODescription orgDesObj2 = getLocDesOb(searchNameDes);
if (orgDesObj2 != null) {
NameDesTitles.add(orgDesObj2.getName());
}
}
}
}
Attempts After Answer Below
AsyncTask update with onPostExecute. Then Since it take a little bit of time a progress bar added with onPreExecute. titlefunc() in oncreate method removed.
This method works now. But, sometimes the same issue exists. Arraylist to adapter is empty so that listview is empty. Seems like still taking lot of time to do the background task.
Updated AsyncTask
#SuppressLint("StaticFieldLeak")
private class GetCourse extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(SearchActivity.this);
progressDialog.setMessage("Searching");
progressDialog.setCancelable(false);
progressDialog.show();
}
#TargetApi(Build.VERSION_CODES.N)
#Override
protected Void doInBackground(Void... voids) {
try {
finalODescriptionArrayList = JsontoObject.jsonToObjectData(getResources().openRawResource(R.raw.newdb));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
titlefunc();
arrayAdapter.notifyDataSetChanged();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
Modifed titlefunc() - to remove duplicates
Set<String > set = new HashSet<>( NameDesTitles);
NameDesTitles.clear();
NameDesTitles.addAll(set);
Your AsyncTask runs asynchronously, in the background. It will (most likely) not be finished when you call titleFunc() (which is what you are seeing).
You can fix this in many ways. One way would be to update the content of your adapter after the AsyncTask completes. You can do this in onPostExecute() of your AsyncTask which will be called when the background processing completes. In that method you can run your titleFunc() or something similar to filter the results you want to display. You then need to tell your Adapter to update the view by calling notifyDatasetChanged() on the Adapter.

JSON download to ListView [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I found this code that I have modified to suit my needs. However I am facing a bit of an issue. It appears that the data is obtained from the remote host but cannot be parsed into adapter.
I have reviewed my entire code structure to ensure that everything is in place but I cant seem to find the problem. The ListView is inside of a Fragment that is part of a TabbedActivity.
This my code:
Fragment inside a Tabbed Activity
public class shops extends Fragment {
String url="http://link to remote webservice";
//FragmentManager fm;
//newInstance() method return reference to fragment
public static shops newInstance(){
shops fragment = new shops();
return fragment;
}
public shops() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//fm = getFragmentManager();
View view = inflater.inflate(R.layout.fragment_shops, container, false);
final ListView listView = (ListView)view.findViewById(R.id.shops_info);
final Downloader d =new Downloader(getActivity(),url,listView);
d.execute();
//calls DialoFragment
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab_edset);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment newEdQua = new createNewEdQua();
newEdQua.show(getActivity().getFragmentManager(), "createNewEdQua");
}
});
// Inflate the layout for this fragment
return view;
}
}
Downloader(receives data and parses in the same class)
public class Downloader extends AsyncTask<Void,Integer,String> {
Context c;
String retredq_url;
ListView listView;
String data;
ArrayList<String> shopl=new ArrayList<String>();//its the ArrayList that we bind to ListView
ProgressDialog pd;
public Downloader(Context c, String retredq_url, ListView listView){
this.c=c;
this.retredq_url=retredq_url;
this.listView=listView;
}
//Before job starts
#Override
protected void onPreExecute(){
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Refreshing List");
pd.setMessage("Please Wait...");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
data=downloadData();
return data;
}
#Override
protected void onPostExecute(String s){
super.onPostExecute(s);
pd.dismiss();
if (s !=null){
try{
JSONArray ja=new JSONArray(data);
//JSONObject jo=null;
shopl.clear();//we need to add the data to ArrayList, so clear list first to avoid duplicates
for (int i=0;i<ja.length();i++){
String shops=ja.getJSONObject(i).getString("Qualification")+ ja.getJSONObject(i).get("eq_end_date")+
ja.getJSONObject(i).get("eq_loc_shops");//retrieve the column name into a string
shopl.add(shops);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(c,R.layout.list_item_shopl,shopl);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Snackbar.make(view,shopl.get(i),Snackbar.LENGTH_LONG).show();
}
});
}
} catch (JSONException e) {
Log.e("Downloader", "Error", e);
}
/*
//call the Parser here to parse the JSON after we confirm string writer is not null
Parser p=new Parser(c,s,listView);
p.execute();*/
}else {
Toast.makeText(c,"Unable to download data", Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream inputStream=null;
String line=null;
try{
URL url=new URL(retredq_url);
HttpURLConnection con=(HttpURLConnection) url.openConnection();
inputStream=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
StringBuffer sb=new StringBuffer();
if (br !=null){
while ((line=br.readLine()) !=null){
sb.append(line+"\n");
}
}else{return null;}
return sb.toString();
} catch (MalformlocRLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream !=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
JSON output (Checked with ARC plugin on Chrome)
{"qualifications":[{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"}],"success":1}
A slight difference from what ADM sees (The success message comes first here)
{"success":1,"qualifications":[{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"},{"eq_edu_Institution":"Oracle","eq_start_Date":"1998-06-14","eq_end_date":"2005-08-23","Qualification":"Software Engineer"}]}
I defined the success message while struturing the array in php webservice
I intend use the Downloader class in several tabs for the same purpose(retrieve data from url parse and display in ListView). The urls and data are independent ot each other so I guess it should work...
Going over LogCat and reviewing JSON data obtained from server I was able to figure the problem. My previous code would have worked without any issues if the data was an Array with Objects in it. But I checked and the structure of the JSON was an Object with the Array inside.
What I had to do was get the Object with JSONObject then that Object retrieve the Array with JSONArray.. Like this:
JSONObject jsonObject=new JSONObject(data);
JSONArray jsonArray= jsonObject.getJSONArray("qualifications");
//now this Array has Objects needed
for (int i=0;i<jsonArray.length();i++){
String institution=jsonArray.getJSONObject(i).getString("Qualification");
edqua.add(institution);
}
//provide the ArrayAdapter<> needed
ArrayAdapter<String> adapter=new ArrayAdapter<String>(c,R.layout.list_item_edqua,edqua);
listView.setAdapter(adapter);
It should be in a try-catch block.. It is good to know the structure of the JSON that is expected. I was rather asking for an Array when Object was being offerd, hence the type mis-match error. I also realised that I will be unable to use the same class for different data sources, as the tables are completely. Any suggestions of how to use one class for different data urls will appreciated.
As the ArrayList<String> shows, the list item will be like
Qualification eq_end_date eq_loc_shops as a single string, so initialize the adapter like
adapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,shopl);
Most of your code can be reused but the part which starts from data generated by downloadData() to the JSONArrayObject that your listview needs.
So you can extract these code to an Interface(here called IPreParser)'s method (called JSONArrayObject arrayFromData(String)), like this:
public interface IPreParser{
JSONArrayObject arrayFromData(String data);
}
Your Downloader need hold a reference to IPreParser, and invoke its method in onPostExecute(). And you can initialize this reference by declaring doInBackground(IPreParser).
In anywhere you what download and parse your data, just implement IPreParser, and then execute your downloader with downloader.execute(yourImplementor);

display hashmapped values in alertbox in android

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

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.

Android - saving checked items of a ListView on app shutdown

I am making an application for the Android platform in Eclipse, and I need help with something. :)
What I want for one part to do is create an arraylist from items that are checked in another ListView. I figured out how to make that and here is the code:
public class MusicList extends Activity {
private ListView lvCheckBox;
private String[] arr = { "Depeche Mode", "The Prodigy", "Rammstein",
"Manilla Road", "Led Zeppelin", "AC/DC", "Massive Attack",
"Skrillex", "Deadmau5" };
ArrayList<String> arrList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.musiclist);
lvCheckBox = (ListView) findViewById(R.id.lvCheckBox);
lvCheckBox.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvCheckBox.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, arr));
arrList = new ArrayList<String>();
lvCheckBox.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(arrList.contains(lvCheckBox.getItemAtPosition(arg2).toString()))
{
arrList.remove(lvCheckBox.getItemAtPosition(arg2).toString());
}
else
{
arrList.add(lvCheckBox.getItemAtPosition(arg2).toString());
}
Collections.sort(arrList);
String strText = "";
for(int i=0 ; i<arrList.size(); i++)
strText += arrList.get(i) + ",";
Toast.makeText(MusicList.this, "Item Clicked: "+ strText, Toast.LENGTH_SHORT).show();
}
});
}
}
BUT!
Now I need to save that arraylist (like some "user settings" (actually the music which the user likes)) even when the app closes completely and when I come back to the list screen previously checked items need to be checked again (bear in mind I will be adding a lot more musicians to the starting list!!). So, anyone knows how to do that? :)
That's all, thanks in advance, and also I am new here so sorry if I messed something up :(
Android has a SharedPreferences class that will allow you to save information to the App's "cache".
So, you'd be able to save and retrieve the list information.
http://developer.android.com/reference/android/content/SharedPreferences.html

Categories