NullPointer in everything I do in onPostExecute - android

I have to update an expandableList from server, I am using asyncTask to download and fill new values in local database, everything is done in doInBackground but after its done I tried to refresh my expandableList in onPostExecute but I am getting a nullPointer on the very statement which runs fine before loading new data. All I am doing is calling the same method which instializes expandableList in the first place..
The method which intializes list for the first time:
public void initializeExpandableList() {
// TODO Auto-generated method stub
getValuesForList();
setupList();
setupClickListenersOnExpandList();
}
And the code for getValuesForList() and setUpList() is:
public void getValuesForList() {
// get which list_id are present in subtopic table
DataBaseHelper myDbHelper = new DataBaseHelper(context);
ArrayList<String> ids = myDbHelper.getListIdsFromSubTopic();
ArrayList<String> typeList = myDbHelper.getTypeListFromDB(ids);
// typeList = myDbHelper.getTypeListFromDB();
Log.v("typelist", typeList + "");
arrGroupelements = typeList.toArray(new String[typeList.size()]);
Log.v("arrGrp", arrGroupelements.toString() + "");
ArrayList<ArrayList<String>> subtopics = myDbHelper.getChildForGroup();
arrChildelements = new String[subtopics.size()][];
for (int i = 0; i < subtopics.size(); i++) {
ArrayList<String> row = subtopics.get(i);
arrChildelements[i] = row.toArray(new String[row.size()]);
}
Log.e("arrChildElements", arrChildelements.toString());
}
And for setUpList() method:
public void setupList() {
expList.setAdapter(adap);
// adap.notifyDataSetChanged();
((BaseAdapter) expList.getAdapter()).notifyDataSetChanged();
}
After inserting data in doInBackground(), inside onPostExecute I am calling a method refresh() which again makes a call to initializeExpandableList() where I am getting null pointer.
private void refresh() {
// TODO Auto-generated method stub
initializeExpandableList();
}
Instead of initializeExpandableLIst, also tried
((BaseAdapter) expList.getAdapter()).notifyDataSetChanged();
and also tried restarting the activity:
Intent intent = getIntent();
finish();
startActivity(intent);
again getting null pointer in last line startActivity(intent);
What am I missing here??

Related

Loader, Json and reload the data coming from the server

I'm working on a simple and small app (as an exercise) that suppose to collect some data from a JSON file and display in an activity.
The same activity has a spinner that when the user select an element should "reload" the Loader by passing a parameter that will modify the query to the server and get different info from the JSON file.
public class ChooseMatchActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Match>> {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_match);
Intent intent = getIntent();
mCurrentPetUri = intent.getData();
ArrayList<String> days = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
for (int i = 0; i < 7; i++) {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.DATE, i);
String day = sdf.format(calendar.getTime());
days.add(day);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, days);
final Spinner spinDays = (Spinner)findViewById(R.id.spinner_days);
spinDays.setAdapter(adapter);
spinDays.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
setMatchesOfTheDay(spinDays.getSelectedItem().toString().toLowerCase());
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ListView matchListView = (ListView) findViewById(R.id.list);
mAdapter = new MatchAdapter(this, new ArrayList<Match>());
matchListView.setAdapter(mAdapter);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
matchListView.setEmptyView(mEmptyStateTextView);
mStateProgressBar = (ProgressBar) findViewById(R.id.loading_spinner);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// Get details on the currently active default data network
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// If there is a network connection, fetch data
if (networkInfo != null && networkInfo.isConnected()) {
// Get a reference to the LoaderManager, in order to interact with loaders.
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
loaderManager.initLoader(MATCH_LOADER_ID, null, this);
} else {
// Otherwise, display error
// First, hide loading indicator so error message will be visible
mStateProgressBar.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
The following are the 4 methods that I use to deal with the loader and to intercept the value selected on the spinner
public void setMatchesOfTheDay(String day) {
Toast.makeText(this, "You choose the day: " + day,
Toast.LENGTH_SHORT).show();
Uri baseUri = Uri.parse(USGS_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("format", "geojson");
uriBuilder.appendQueryParameter("limit", "30");
new MatchLoader(this, uriBuilder.toString());
}
#Override
public Loader<List<Match>> onCreateLoader(int i, Bundle bundle ) {
// Create a new loader for the given URL
Uri baseUri = Uri.parse(USGS_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("format", "geojson");
uriBuilder.appendQueryParameter("limit", "10");
return new MatchLoader(this, uriBuilder.toString());
}
#Override
public void onLoadFinished(Loader<List<Match>> loader, List<Match> matches) {
// Set empty state text to display "No earthquakes found."
mEmptyStateTextView.setText(R.string.no_matches);
mStateProgressBar.setVisibility(View.GONE);
// Clear the adapter of previous earthquake data
mAdapter.clear();
// If there is a valid list of {#link Match}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (matches != null && !matches.isEmpty()) {
mAdapter.addAll(matches);
}
}
#Override
public void onLoaderReset(Loader<List<Match>> loader) {
// Loader reset, so we can clear out our existing data.
mAdapter.clear();
}
The first time I access the activity everything is working perfectly but as soon as I select an element from the spinner I can see the Toast message but nothing change in the listview.
I tried several option but I definitely feeling confuse about working with the Loader
Hope someone can clarify a bit the concepts
Your setMatchesOfTheDay method is calling new MatchLoader(this, uriBuilder.toString());, but that does nothing - it creates a new Loader, but doesn't actually start it loading. The only way to start something loading is via initLoader (which only creates a Loader for the given ID if it doesn't already exist) or restartLoader (which throws away any existing Loader for the given ID and creates a new Loader).
In your case, it looks like you should be calling restartLoader(MATCH_LOADER_ID, null, this) at the end of your setMatchesOfTheDay to recreate your Loader with the newly selected date.

how to refresh and load data from a json feed in android?

I have a json feed from this URL which contains 20 fields and I parse all the datas..but again I need to load more data from the json feed after showing the 20 fields in listview.
I have created a AsyncTask and loaded the json in listview. this is my class
public void onCreate(Bundle savedInstanceState) {
new DoInBackgrd().execute();
}
private class DoInBackgrd extends AsyncTask<Void, Void, Void> implements
DialogInterface.OnCancelListener {
private ProgressDialog processDialog;
#Override
protected void onPreExecute() {
processDialog = ProgressDialog.show(List.this, "",
getString(R.string.loading), true);
processDialog.setCancelable(true);
}
public void onCancel(DialogInterface arg0) {
// TODO Auto-generated method stub
if (processDialog.isShowing()) {
processDialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
Jsonfunctions jParser = new Jsonfunctions();
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
results = json.getJSONArray(TAG_RESULTS);
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
id = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
adress = c.getString(TAG_ADRRESS);
latitude = c.getString(TAG_LATITUDE);
latitudeAry.add(c.getString(TAG_LATITUDE).toString());
longitude = c.getString(TAG_lONGITUDE);
latitudeAry.add(c.getString(TAG_lONGITUDE).toString());
distance = c.getString(TAG_DISTANCE);
image = c.getString(TAG_IMAGE);
phone = c.getString(TAG_TELEPHONE);
telphonenumberAry
.add(c.getString(TAG_TELEPHONE).toString());
NameAry.add(c.getString(TAG_NAME).toString());
resourceAry.add(new ResourceClass(point, id, name, adress,
distance, latitude, longitude, phone));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
if (processDialog.isShowing()) {
processDialog.dismiss();
}
listView.setAdapter(new ASyncAdapter());
listView.setDividerHeight(2);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
Intent details = new Intent(List.this, Details.class);
details.putExtra("position", position + 1);
details.putExtra("name", resourceAry.get(position)
.getName());
details.putExtra("adress", resourceAry.get(position)
.getAdress());
details.putExtra("phone", resourceAry.get(position)
.getTelephone());
details.putExtra("latitudes", latitude);
details.putExtra("longitudes", longitude);
startActivity(details);
}
});
}
}
Thanks in advance
I had just finished working on similar kind of requirement(issue faced on is specified in)
Hence I'm hoping to provide you proper solution that is helpful to you and saves ur time.
If I'm not wrong you need to populate same ListView with next 20(i.e. 21 - 40) fields obtained in response for server api.
In that case u need to call server api again and again for that u need an event. Say u add a 'Next' button and on its click u retrive next 20 fields(21 - 40).
Currently in ur code in 'DoInBackgrd', you are binding/setting Adapter(ASyncAdapter) each time you need to bind new records/fields to ListView. This is not a good practice, also it at a instance it will not refresh fields of newly assigned adapter in listView.
Hence you should :
Just retrieve/parse new fileds from JSon and set them in adapter. Adapter will notify your listView about data change and listView will refresh its view.
Considering that 'ASyncAdapter' is your custom adapter that implements ArrayAdapter, just add following(change Variable type from Restaurant to as per your requirement) method to it.
public void reSet(ArrayList<Resturant> resturantsCache) {
//This will clear your current fields/records in adpter
clear();
//This will new fields/records in adpter from provided resturantsCache ArrayList.
for (Resturant resturant : resturantsCache) {
add(resturant);
}
}
Hope you will be able to replace variable types in provided method and use it as per you requirements, In case you need more help please provide ASyncAdapter code.
Thanks.

How to remove an item from ListView

I am building one app having One list view showing the list of My favorites Fans. My list of Fans is this!
When i click on any item of this list then it show me complete profile of the concern Fan e.g., this
My Code is ->
public class FavouriteFansActivity extends ListActivity implements OnItemClickListener, OnLongClickListener {
ListView mFavFansListView;
JSONArray jArrayFavFans;//jArrayFavFans that contains jobjects of all fans. each jobj hv data of 1 unique fan!
JSONObject jFavFan_Data;//contain data of an indivisual fan
LazyAdapter adapter;
ArrayList<Object> favFansList;
ArrayList<String> mfavFansImgs;
ItemBean bean;
String favFans;
//String url="http://XXXXX/ManU/";//Live
String url="http://XXXXX/ManU/";//Local
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.on_favourite_fan_list);
prepareFavFanArrayLits();//method that prepare list of my favorite fans....
mFavFansListView = (ListView) findViewById(android.R.id.list);
adapter = new LazyAdapter(this, mfavFansImgs, favFansList);
mFavFansListView.setAdapter(adapter);
mFavFansListView.setOnItemClickListener(this);
mFavFansListView.setOnLongClickListener(this);
/** I am still not getting that when to call onPause(), onResume(), onRestart()... etc ??? */
}
/* .........onItemClick......... */
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
ItemBean bean = (ItemBean) adapter.getItem(position);
/**from here-> I am going to start one activity that show the complete profile of a
* particular Fan... According to the unique id received from clicking on ListItem!
*/
Intent in= new Intent(getParent(), FavFanProfile.class);
TabGroupActivity prnt = (TabGroupActivity) getParent();
Bundle fBundle= new Bundle();
fBundle.putString("fanId", bean.getUid());
in.putExtras(fBundle);
prnt.startChildActivity("FavFanProfile", in);
}
/* .........onLongClick......... */
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(FavouriteFansActivity.this, "To remove...Clk", Toast.LENGTH_SHORT).show();
return false;
}
/** Method used to prepare the List of Favorite Fans
* #author Rupesh */
public void prepareFavFanArrayLits() {
/* return me array containing data of all favFans */
Boolean mkFavFansList=false;
SharedPreferences favFansData = getSharedPreferences("jArrayFavFansPref", MODE_WORLD_WRITEABLE);
favFans=favFansData.getString("favFansData", "");
Log.i("FavFans_List->", "FavFans_DATA readed from prefs:"+favFans.toString());
if(!favFans.equals("")){
try {
mkFavFansList=true;
jArrayFavFans=new JSONArray(favFans);
favFansList = new ArrayList<Object>();
mfavFansImgs = new ArrayList<String>();
Log.i("fav_fansONfav", jArrayFavFans.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else {
Log.i("else_favList_img", "list & image are initialized");
favFansList = new ArrayList<Object>();
mfavFansImgs = new ArrayList<String>();
}
// ++++++++
if(mkFavFansList){
try {
for (int i = 0; i < jArrayFavFans.length(); i++) {
// will return the data of each row fetched from JSONArray returned by location1.php
String data_of_each_user = jArrayFavFans.get(i).toString();
Log.i("Data Of User at index " + i + " is", data_of_each_user);
// I put the object at index "i" into JSONObject & retrieve data from name-value pair
jFavFan_Data = jArrayFavFans.getJSONObject(i);// data of User at index i
// in array
AddObjectToList(jFavFan_Data.getString("uniqid").toString(), jFavFan_Data.getString("name"),
jFavFan_Data.getString("distance"));
//Log.i("URL", url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
mfavFansImgs.add(url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
Log.i("IMG_URL", url+"images/"+jFavFan_Data.get("uniqid").toString()+".png");
String nm = jFavFan_Data.get("name").toString();
String uid = jFavFan_Data.get("uniqid").toString();
String dis = jFavFan_Data.get("distance").toString();
//System.out.println("Your Name: " + nm);
System.out.println("Your Unique Id: " + uid);
//System.out.println("Your Distance: " + dis);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} else {
Log.i("NO_FAVORITE_FANS", "No Favorite Fans are added in favorites List!");
Toast.makeText(FavouriteFansActivity.this, "No Fans in Favorite List!", Toast.LENGTH_SHORT).show();
}
// ++++++++++
}
//**********************setting vales in bean*************************
public void AddObjectToList(String uid, String title, String desc) {
bean = new ItemBean();
bean.setUid(uid);
bean.setDescription(desc);
bean.setTitle(title);
favFansList.add(bean);
}
//***********************************************
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i("favFansData_FavoriteFansActivity.java", "hi...on resume"+favFans);
prepareFavFanArrayLits();
setContentView(R.layout.on_favourite_fan_list);
mFavFansListView = (ListView) findViewById(android.R.id.list);
adapter = new LazyAdapter(this, mfavFansImgs, favFansList);
mFavFansListView.setAdapter(adapter);// come null pointer exception when no fan data is returned! hendle it...
mFavFansListView.setOnItemClickListener(this);
}
}
I stuck at the point -> That, how to remove one Item(one Fan) from this list(favorite_fans_list) ...???
I try to do something on onLongClick Listener but it doesn`t work.... I pleased to have any pointer or some sample which help me to overcome from this problem!!!
One way would be to modify the content in the adapter and then notify the listview has changed.
Your adapter holds an ArrayList for the data backing it.
You need to remove the object from the list. Then notify the adapter that the set has changed as follows.
favFansList.remove(index);
adapter.notifyDataSetChanged()

thread exiting error in android

Please help with this error .... In the following code the get info function works correctly but it gives an error saying the thread caught an exception at exiting.... I am trying to use a tab host and the first tab page is the following... In this i show a progress dialog until i get my data and then show it in a list view
public class History extends Activity implements OnItemClickListener
{
/** Called when the activity is first created. */
ListView list;
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems;
//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;
private String resDriver,resPassenger,ID;
private ProgressDialog dialog;
ArrayList<HashMap<String, Object>> listInfo = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> item;
JSONObject jDriver;
//JSONObject jPassenger;
// Make strings for logging
private final String TAG = this.getClass().getSimpleName();
private final String RESTORE = ", can restore state";
private final String state = "Home Screen taking care of all the tabs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent loginIntent = getIntent();
ID = loginIntent.getStringExtra("ID");
listItems = new ArrayList<String>();
Log.i(TAG, "Started view active rides");
setContentView(R.layout.searchresults);
list = (ListView)findViewById(R.id.ListView01);
list.setOnItemClickListener(this);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems);
list.setAdapter(adapter);
getInfo();
}
The function getInfo is used to start a thread which shows a dialog box and starts a http request to get some data ...
public void getInfo(){
GetInfoThread checkUpdate = new GetInfoThread();
checkUpdate.start();
dialog = ProgressDialog.show(History.this, "Retrieving Info","Please Wait ...", true);
}
private class GetInfoThread extends Thread
{
public void run() {
jDriver = new JSONObject();
try {
jDriver.put("ID", ID);
jDriver.put("task", "GET DATES");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listItems = new ArrayList<String>();
Log.i(TAG,"Sending data for the driver rides");
resDriver = HTTPPoster.sendJson(jDriver,"http://dsadsada"); // Any Server URL
JSONObject driver;
try {
driver = new JSONObject(resDriver);
Log.i(TAG,"Recieved Driver details");
listItems.add(array[0]);
handler.sendEmptyMessage(0);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
listItems.add("No driver rides created");
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
dialog.dismiss();
Log.i(TAG,"hello 123");
adapter.notifyDataSetChanged();
}
};
}
I am not sure exactly what is causing your error but I suspect it has to do with UI changes not running on the actual UI thread. In Android there is a class called AsyncTask that will do the threading for you and handle the passing of data between the background thread an the UI thread. I would suggest rewriting your code to utilize the AsyncTask class.

Asyc Task return Arraylist retrieve it?

new DownloadFilesTask().execute(myPrefs.getString("IP", ""), null, null);
I returns an Arraylist from the dobackground method..how to put it into my arraylist?
Arraylist al=null;
al=new DownloadFilesTask().execute(myPrefs.getString("IP", ""), null, null);
not working.
I returns an Arraylist from the dobackground method..how to put it into my arraylist?
By assigning your local ArrayList from the doInBackground() method to your global ArrayList before returning it.
Sample code:
#Override
protected ArrayList doInBackground(...) {
ArrayList localArrayList = new ArrayList();
// Other stuff you might have.
// ...
return mYourGlobalArrayList = localArrayList;
}
Try like this in ur code
//After Preexecute...
#Override
protected ArrayList doInBackground(...) {
ArrayList localArrayList = new ArrayList();
// Other stuff you might have.
// ...
return localArrayList;
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
if(result!= null)
{
ArrayList<String> category = new ArrayList<String>();
category = (ArrayList<String>) result;
}
}
}
Then You can assign this arraylist to your arraylist in post execute
Return it from your doInBackground method, and bind that in onPostExecute method.
In onPostExecute method, you can get return value of doInBackground as parameter value
new AsyncTask<String, Void, ArrayList<String>>() {
#Override
protected ArrayList<String> doInBackground(String... params) {
//result = do some work
ArrayList localArrayList = new ArrayList();
// localArrayList = get from your website or from database
// assign arraylist globally
return result;
}
}.execute("");

Categories

Resources